Mercurial > cortex
view org/touch.org @ 235:be78d7bd6920
fixed major bug in collapse
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Sun, 12 Feb 2012 09:56:38 -0700 |
parents | 712bd7e5b148 |
children | 3fa49ff1649a |
line wrap: on
line source
1 #+title: Simulated Sense of Touch2 #+author: Robert McIntyre3 #+email: rlm@mit.edu4 #+description: Simulated touch for AI research using JMonkeyEngine and clojure.5 #+keywords: simulation, tactile sense, jMonkeyEngine3, clojure6 #+SETUPFILE: ../../aurellem/org/setup.org7 #+INCLUDE: ../../aurellem/org/level-0.org11 * Touch13 Touch is critical to navigation and spatial reasoning and as such I14 need a simulated version of it to give to my AI creatures.16 However, touch in my virtual can not exactly correspond to human touch17 because my creatures are made out of completely rigid segments that18 don't deform like human skin.20 Human skin has a wide array of touch sensors, each of which speciliaze21 in detecting different vibrational modes and pressures. These sensors22 can integrate a vast expanse of skin (i.e. your entire palm), or a23 tiny patch of skin at the tip of your finger. The hairs of the skin24 help detect objects before they even come into contact with the skin25 proper.27 Instead of measuring deformation or vibration, I surround each rigid28 part with a plenitude of hair-like objects which do not interact with29 the physical world. Physical objects can pass through them with no30 effect. The hairs are able to measure contact with other objects, and31 constantly report how much of their extent is covered. So, even though32 the creature's body parts do not deform, the hairs create a margin33 around those body parts which achieves a sense of touch which is a34 hybrid between a human's sense of deformation and sense from hairs.36 Implementing touch in jMonkeyEngine follows a different techinal route37 than vision and hearing. Those two senses piggybacked off38 jMonkeyEngine's 3D audio and video rendering subsystems. To simulate39 Touch, I use jMonkeyEngine's physics system to execute many small40 collision detections, one for each "hair". The placement of the41 "hairs" is determined by a UV-mapped image which shows where each hair42 should be on the 3D surface of the body.45 * Defining Touch Meta-Data in Blender47 Each geometry can have a single UV map which describes the position48 and length of the "hairs" which will constitute its sense of49 touch. This image path is stored under the "touch" key. The image50 itself is grayscale, with black meaning a hair length of 0 (no hair is51 present) and white meaning a hair length of =scale=, which is a float52 stored under the key "scale". If the pixel is gray then the resultant53 hair length is linearly interpolated between 0 and =scale=.55 #+name: meta-data56 #+begin_src clojure57 (defn tactile-sensor-profile58 "Return the touch-sensor distribution image in BufferedImage format,59 or nil if it does not exist."60 [#^Geometry obj]61 (if-let [image-path (meta-data obj "touch")]62 (load-image image-path)))64 (defn tactile-scale65 "Return the maximum length of a hair. All hairs are scalled between66 0.0 and this length, depending on their color. Black is 0, and67 white is maximum length, and everything in between is scalled68 linearlly. Default scale is 0.01 jMonkeyEngine units."69 [#^Geometry obj]70 (if-let [scale (meta-data obj "scale")]71 scale 0.1))72 #+end_src74 ** TODO add image showing example touch-uv map75 ** TODO add metadata display for worm78 * Skin Creation79 * TODO get the actual lengths for each hair81 #+begin_src clojure82 pixel-triangles83 xyz-triangles84 conversions (map triangles->affine-transform pixel-triangles85 xyz-triangles)87 #+end_src89 #+name: kernel90 #+begin_src clojure91 (in-ns 'cortex.touch)93 (declare touch-topology touch-hairs set-ray)95 (defn touch-kernel96 "Constructs a function which will return tactile sensory data from97 'geo when called from inside a running simulation"98 [#^Geometry geo]99 (let [[ray-reference-origins100 ray-reference-tips101 ray-lengths] (touch-hairs geo)102 current-rays (map (fn [] (Ray.)) ray-reference-origins)103 topology (touch-topology geo)]104 (if (empty? ray-reference-origins) nil105 (fn [node]106 (let [transform (.getWorldMatrix geo)]107 (dorun108 (map (fn [ray ref-origin ref-tip length]109 (set-ray ray transform ref-origin ref-tip length))110 current-rays ray-reference-origins111 ray-reference-tips ray-lengths))112 (vector113 topology114 (vec115 (for [ray current-rays]116 (do117 (let [results (CollisionResults.)]118 (.collideWith node ray results)119 (let [touch-objects120 (filter #(not (= geo (.getGeometry %)))121 results)]122 [(if (empty? touch-objects)123 (.getLimit ray)124 (.getDistance (first touch-objects)))125 (.getLimit ray)])))))))))))127 (defn touch-kernel*128 "Returns a function which returns tactile sensory data when called129 inside a running simulation."130 [#^Geometry geo]131 (let [feeler-coords (feeler-coordinates geo)132 tris (triangles geo)133 limit (tactile-scale geo)]134 (if (empty? (touch-topology geo))135 nil136 (fn [node]137 (let [sensor-origins138 (map139 #(map (partial local-to-world geo) %)140 feeler-coords)141 triangle-normals142 (map (partial get-ray-direction geo)143 tris)144 rays145 (flatten146 (map (fn [origins norm]147 (map #(doto (Ray. % norm)148 (.setLimit limit)) origins))149 sensor-origins triangle-normals))]150 (vector151 (touch-topology geo)152 (vec153 (for [ray rays]154 (do155 (let [results (CollisionResults.)]156 (.collideWith node ray results)157 (let [touch-objects158 (filter #(not (= geo (.getGeometry %)))159 results)]160 [(if (empty? touch-objects)161 limit (.getDistance (first touch-objects)))162 limit])))))))))))164 (defn touch!165 "Endow the creature with the sense of touch. Returns a sequence of166 functions, one for each body part with a tactile-sensor-proile,167 each of which when called returns sensory data for that body part."168 [#^Node creature]169 (filter170 (comp not nil?)171 (map touch-kernel172 (filter #(isa? (class %) Geometry)173 (node-seq creature)))))174 #+end_src176 * Visualizing Touch177 #+name: visualization178 #+begin_src clojure179 (in-ns 'cortex.touch)181 (defn touch->gray182 "Convert a pair of [distance, max-distance] into a grayscale pixel"183 [distance max-distance]184 (gray185 (- 255186 (rem187 (int188 (* 255 (/ distance max-distance)))189 256))))191 (defn view-touch192 "Creates a function which accepts a list of touch sensor-data and193 displays each element to the screen."194 []195 (view-sense196 (fn197 [[coords sensor-data]]198 (let [image (points->image coords)]199 (dorun200 (for [i (range (count coords))]201 (.setRGB image ((coords i) 0) ((coords i) 1)202 (apply touch->gray (sensor-data i)))))203 image))))204 #+end_src208 * Triangle Manipulation Functions210 The rigid bodies which make up a creature have an underlying211 =Geometry=, which is a =Mesh= plus a =Material= and other important212 data involved with displaying the body.214 A =Mesh= is composed of =Triangles=, and each =Triangle= has three215 verticies which have coordinates in XYZ space and UV space.217 Here, =(triangles)= gets all the triangles which compose a mesh, and218 =(triangle-UV-coord)= returns the the UV coordinates of the verticies219 of a triangle.221 #+name: triangles-1222 #+begin_src clojure223 (defn triangles224 "Return a sequence of all the Triangles which compose a given225 Geometry."226 [#^Geometry geom]227 (let228 [mesh (.getMesh geom)229 triangles (transient [])]230 (dorun231 (for [n (range (.getTriangleCount mesh))]232 (let [tri (Triangle.)]233 (.getTriangle mesh n tri)234 ;; (.calculateNormal tri)235 ;; (.calculateCenter tri)236 (conj! triangles tri))))237 (persistent! triangles)))239 (defn mesh-triangle240 "Get the triangle specified by triangle-index from the mesh within241 bounds."242 [#^Mesh mesh triangle-index]243 (let [scratch (Triangle.)]244 (.getTriangle mesh triangle-index scratch)245 scratch))247 (defn triangle-vertex-indices248 "Get the triangle vertex indices of a given triangle from a given249 mesh."250 [#^Mesh mesh triangle-index]251 (let [indices (int-array 3)]252 (.getTriangle mesh triangle-index indices)253 (vec indices)))255 (defn vertex-UV-coord256 "Get the UV-coordinates of the vertex named by vertex-index"257 [#^Mesh mesh vertex-index]258 (let [UV-buffer259 (.getData260 (.getBuffer261 mesh262 VertexBuffer$Type/TexCoord))]263 [(.get UV-buffer (* vertex-index 2))264 (.get UV-buffer (+ 1 (* vertex-index 2)))]))266 (defn triangle-UV-coord267 "Get the UV-cooridnates of the triangle's verticies."268 [#^Mesh mesh width height triangle-index]269 (map (fn [[u v]] (vector (* width u) (* height v)))270 (map (partial vertex-UV-coord mesh)271 (triangle-vertex-indices mesh triangle-index))))272 #+end_src274 * Schrapnel Conversion Functions276 It is convienent to treat a =Triangle= as a sequence of verticies, and277 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion278 functions make this easy. If these classes implemented =Iterable= then279 this code would not be necessary. Hopefully they will in the future.281 #+name: triangles-2282 #+begin_src clojure283 (defn triangle-seq [#^Triangle tri]284 [(.get1 tri) (.get2 tri) (.get3 tri)])286 (defn vector3f-seq [#^Vector3f v]287 [(.getX v) (.getY v) (.getZ v)])289 (defn point->vector2f [[u v]]290 (Vector2f. u v))292 (defn vector2f->vector3f [v]293 (Vector3f. (.getX v) (.getY v) 0))295 (defn map-triangle [f #^Triangle tri]296 (Triangle.297 (f 0 (.get1 tri))298 (f 1 (.get2 tri))299 (f 2 (.get3 tri))))301 (defn points->triangle302 "Convert a list of points into a triangle."303 [points]304 (apply #(Triangle. %1 %2 %3)305 (map (fn [point]306 (let [point (vec point)]307 (Vector3f. (get point 0 0)308 (get point 1 0)309 (get point 2 0))))310 (take 3 points))))311 #+end_src313 * Triangle Affine Transforms315 The position of each hair is stored in a 2D image in UV316 coordinates. To place the hair in 3D space we must convert from UV317 coordinates to XYZ coordinates. Each =Triangle= has coordinates in318 both UV-space and XYZ-space, which defines a unique [[http://mathworld.wolfram.com/AffineTransformation.html ][Affine Transform]]319 for translating any coordinate within the UV triangle to the320 cooresponding coordinate in the XYZ triangle.322 #+name: triangles-3323 #+begin_src clojure324 (defn triangle->matrix4f325 "Converts the triangle into a 4x4 matrix: The first three columns326 contain the vertices of the triangle; the last contains the unit327 normal of the triangle. The bottom row is filled with 1s."328 [#^Triangle t]329 (let [mat (Matrix4f.)330 [vert-1 vert-2 vert-3]331 ((comp vec map) #(.get t %) (range 3))332 unit-normal (do (.calculateNormal t)(.getNormal t))333 vertices [vert-1 vert-2 vert-3 unit-normal]]334 (dorun335 (for [row (range 4) col (range 3)]336 (do337 (.set mat col row (.get (vertices row)col))338 (.set mat 3 row 1))))339 mat))341 (defn triangle-transformation342 "Returns the affine transformation that converts each vertex in the343 first triangle into the corresponding vertex in the second344 triangle."345 [#^Triangle tri-1 #^Triangle tri-2]346 (.mult347 (triangle->matrix4f tri-2)348 (.invert (triangle->matrix4f tri-1))))349 #+end_src351 * Triangle Boundaries353 For efficiency's sake I will divide the UV-image into small squares354 which inscribe each UV-triangle, then extract the points which lie355 inside the triangle and map them to 3D-space using356 =(triangle-transform)= above. To do this I need a function,357 =(inside-triangle?)=, which determines whether a point is inside a358 triangle in 2D UV-space.360 #+name: triangles-4361 #+begin_src clojure362 (defn convex-bounds363 "Returns the smallest square containing the given vertices, as a364 vector of integers [left top width height]."365 [uv-verts]366 (let [xs (map first uv-verts)367 ys (map second uv-verts)368 x0 (Math/floor (apply min xs))369 y0 (Math/floor (apply min ys))370 x1 (Math/ceil (apply max xs))371 y1 (Math/ceil (apply max ys))]372 [x0 y0 (- x1 x0) (- y1 y0)]))374 (defn same-side?375 "Given the points p1 and p2 and the reference point ref, is point p376 on the same side of the line that goes through p1 and p2 as ref is?"377 [p1 p2 ref p]378 (<=379 0380 (.dot381 (.cross (.subtract p2 p1) (.subtract p p1))382 (.cross (.subtract p2 p1) (.subtract ref p1)))))384 (defn inside-triangle?385 "Is the point inside the triangle?"386 {:author "Dylan Holmes"}387 [#^Triangle tri #^Vector3f p]388 (let [[vert-1 vert-2 vert-3] (triangle-seq tri)]389 (and390 (same-side? vert-1 vert-2 vert-3 p)391 (same-side? vert-2 vert-3 vert-1 p)392 (same-side? vert-3 vert-1 vert-2 p))))393 #+end_src396 * Sensor Related Functions398 These functions analyze the touch-sensor-profile image convert the399 location of each touch sensor from pixel coordinates to UV-coordinates400 and XYZ-coordinates.402 #+name: sensors403 #+begin_src clojure404 (defn sensors-in-triangle405 "Locate the touch sensors in the triangle, returning a map of their406 UV and geometry-relative coordinates."407 [image mesh tri-index]408 (let [width (.getWidth image)409 height (.getHeight image)410 UV-vertex-coords (triangle-UV-coord mesh width height tri-index)411 bounds (convex-bounds UV-vertex-coords)413 cutout-triangle (points->triangle UV-vertex-coords)414 UV-sensor-coords415 (filter (comp (partial inside-triangle? cutout-triangle)416 (fn [[u v]] (Vector3f. u v 0)))417 (white-coordinates image bounds))418 UV->geometry (triangle-transformation419 cutout-triangle420 (mesh-triangle mesh tri-index))421 geometry-sensor-coords422 (map (fn [[u v]] (.mult UV->geometry (Vector3f. u v 0)))423 UV-sensor-coords)]424 {:UV UV-sensor-coords :geometry geometry-sensor-coords}))426 (defn-memo locate-feelers427 "Search the geometry's tactile UV profile for touch sensors,428 returning their positions in geometry-relative coordinates."429 [#^Geometry geo]430 (let [mesh (.getMesh geo)431 num-triangles (.getTriangleCount mesh)]432 (if-let [image (tactile-sensor-profile geo)]433 (map434 (partial sensors-in-triangle image mesh)435 (range num-triangles))436 (repeat (.getTriangleCount mesh) {:UV nil :geometry nil}))))438 (defn-memo touch-topology439 "Return a sequence of vectors of the form [x y] describing the440 \"topology\" of the tactile sensors. Points that are close together441 in the touch-topology are generally close together in the simulation."442 [#^Gemoetry geo]443 (vec (collapse (reduce concat (map :UV (locate-feelers geo))))))445 (defn-memo feeler-coordinates446 "The location of the touch sensors in world-space coordinates."447 [#^Geometry geo]448 (vec (map :geometry (locate-feelers geo))))449 #+end_src451 * Physics Collision Objects453 The "hairs" are actually =Rays= which extend from a point on a454 =Triangle= in the =Mesh= normal to the =Triangle's= surface.456 #+name: rays457 #+begin_src clojure458 (defn get-ray-origin459 "Return the origin which a Ray would have to have to be in the exact460 center of a particular Triangle in the Geometry in World461 Coordinates."462 [geom tri]463 (let [new (Vector3f.)]464 (.calculateCenter tri)465 (.localToWorld geom (.getCenter tri) new) new))467 (defn get-ray-direction468 "Return the direction which a Ray would have to have to be to point469 normal to the Triangle, in coordinates relative to the center of the470 Triangle."471 [geom tri]472 (let [n+c (Vector3f.)]473 (.calculateNormal tri)474 (.calculateCenter tri)475 (.localToWorld476 geom477 (.add (.getCenter tri) (.getNormal tri)) n+c)478 (.subtract n+c (get-ray-origin geom tri))))479 #+end_src480 * Headers482 #+name: touch-header483 #+begin_src clojure484 (ns cortex.touch485 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry486 to be outfitted with touch sensors with density determined by a UV487 image. In this way a Geometry can know what parts of itself are488 touching nearby objects. Reads specially prepared blender files to489 construct this sense automatically."490 {:author "Robert McIntyre"}491 (:use (cortex world util sense))492 (:use clojure.contrib.def)493 (:import (com.jme3.scene Geometry Node Mesh))494 (:import com.jme3.collision.CollisionResults)495 (:import com.jme3.scene.VertexBuffer$Type)496 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))497 #+end_src499 * Adding Touch to the Worm501 #+name: test-touch502 #+begin_src clojure503 (ns cortex.test.touch504 (:use (cortex world util sense body touch))505 (:use cortex.test.body))507 (cortex.import/mega-import-jme3)509 (defn test-touch []510 (let [the-worm (doto (worm) (body!))511 touch (touch! the-worm)512 touch-display (view-touch)]513 (world (nodify [the-worm (floor)])514 standard-debug-controls516 (fn [world]517 (light-up-everything world))519 (fn [world tpf]520 (touch-display (map #(% (.getRootNode world)) touch))))))521 #+end_src522 * Source Listing523 * Next526 * COMMENT Code Generation527 #+begin_src clojure :tangle ../src/cortex/touch.clj528 <<touch-header>>529 <<meta-data>>530 <<triangles-1>>531 <<triangles-2>>532 <<triangles-3>>533 <<triangles-4>>534 <<sensors>>535 <<rays>>536 <<kernel>>537 <<visualization>>538 #+end_src541 #+begin_src clojure :tangle ../src/cortex/test/touch.clj542 <<test-touch>>543 #+end_src