Mercurial > cortex
view org/touch.org @ 242:a7f26a074071
saving progress...
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Sun, 12 Feb 2012 13:48:28 -0700 |
parents | f2e583be8584 |
children | f33fec68f775 |
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=. I call54 these "hairs" /feelers/.56 #+name: meta-data57 #+begin_src clojure58 (defn tactile-sensor-profile59 "Return the touch-sensor distribution image in BufferedImage format,60 or nil if it does not exist."61 [#^Geometry obj]62 (if-let [image-path (meta-data obj "touch")]63 (load-image image-path)))65 (defn tactile-scale66 "Return the maximum length of a hair. All hairs are scalled between67 0.0 and this length, depending on their color. Black is 0, and68 white is maximum length, and everything in between is scalled69 linearlly. Default scale is 0.01 jMonkeyEngine units."70 [#^Geometry obj]71 (if-let [scale (meta-data obj "scale")]72 scale 0.1))73 #+end_src75 ** TODO add image showing example touch-uv map76 ** TODO add metadata display for worm79 * Skin Creation80 * TODO get the actual lengths for each hair82 #+begin_src clojure83 pixel-triangles84 xyz-triangles85 conversions (map triangles->affine-transform pixel-triangles86 xyz-triangles)88 #+end_src91 =(touch-kernel)= generates the functions which implement the sense of92 touch for a creature. These functions must do 6 things to obtain touch93 data.95 - Get the tactile profile image and scale paramaters which describe96 the layout of feelers along the object's surface.97 =(tactile-sensor-profile)=, =(tactile-scale)=99 - Get the lengths of each feeler by analyzing the color of the100 pixels in the tactile profile image.101 NOT IMPLEMENTED YET103 - Find the triangles which make up the mesh in pixel-space and in104 world-space.105 =(triangles)= =(pixel-triangles)=107 - Find the coordinates of each pixel in pixel space. These108 coordinates are used to make the touch-topology.109 =(feeler-pixel-coords)=111 - Find the coordinates of each pixel in world-space. These112 coordinates are the origins of the feelers. =(feeler-origins)=114 - Calculate the normals of the triangles in world space, and add115 them to each of the origins of the feelers. These are the116 normalized coordinates of the tips of the feelers.117 For both of these, =(feeler-tips)=119 - Generate some sort of topology for the sensors.120 =(touch-topology)=122 #+begin_src clojure127 #+end_src131 #+name: kernel132 #+begin_src clojure133 (in-ns 'cortex.touch)135 (declare touch-topology feelers set-ray)137 (defn set-ray [#^Ray ray #^Matrix4f transform138 #^Vector3f origin #^Vector3f tip139 length]140 (.setOrigin ray (.mult transform origin))141 (.setDirection ray (.subtract142 (.mult transform tip)143 (.getOrigin ray)))144 (.setLimit ray length)145 ray)148 (defn touch-kernel149 "Constructs a function which will return tactile sensory data from150 'geo when called from inside a running simulation"151 [#^Geometry geo]152 (let [profile (tactile-sensor-profile geo)153 ray-reference-origins (feeler-origins geo profile)154 ray-reference-tips (feeler-tips geo profile)155 ray-lengths (repeat 9000 0.1)156 current-rays (map (fn [] (Ray.)) ray-reference-origins)157 topology (touch-topology geo profile)]158 (if (empty? ray-reference-origins) nil159 (fn [node]160 (let [transform (.getWorldMatrix geo)]161 (dorun162 (map (fn [ray ref-origin ref-tip length]163 (set-ray ray transform ref-origin ref-tip length))164 current-rays ray-reference-origins165 ray-reference-tips ray-lengths))166 (vector167 topology168 (vec169 (for [ray current-rays]170 (do171 (let [results (CollisionResults.)]172 (.collideWith node ray results)173 (let [touch-objects174 (filter #(not (= geo (.getGeometry %)))175 results)]176 [(if (empty? touch-objects)177 (.getLimit ray)178 (.getDistance (first touch-objects)))179 (.getLimit ray)])))))))))))181 (defn touch-kernel*182 "Returns a function which returns tactile sensory data when called183 inside a running simulation."184 [#^Geometry geo]185 (let [feeler-coords (feeler-coordinates geo)186 tris (triangles geo)187 limit (tactile-scale geo)]188 (if (empty? (touch-topology geo))189 nil190 (fn [node]191 (let [sensor-origins192 (map193 #(map (partial local-to-world geo) %)194 feeler-coords)195 triangle-normals196 (map (partial get-ray-direction geo)197 tris)198 rays199 (flatten200 (map (fn [origins norm]201 (map #(doto (Ray. % norm)202 (.setLimit limit)) origins))203 sensor-origins triangle-normals))]204 (vector205 (touch-topology geo)206 (vec207 (for [ray rays]208 (do209 (let [results (CollisionResults.)]210 (.collideWith node ray results)211 (let [touch-objects212 (filter #(not (= geo (.getGeometry %)))213 results)]214 [(if (empty? touch-objects)215 limit (.getDistance (first touch-objects)))216 limit])))))))))))218 (defn touch!219 "Endow the creature with the sense of touch. Returns a sequence of220 functions, one for each body part with a tactile-sensor-proile,221 each of which when called returns sensory data for that body part."222 [#^Node creature]223 (filter224 (comp not nil?)225 (map touch-kernel226 (filter #(isa? (class %) Geometry)227 (node-seq creature)))))228 #+end_src230 * Sensor Related Functions232 These functions analyze the touch-sensor-profile image convert the233 location of each touch sensor from pixel coordinates to UV-coordinates234 and XYZ-coordinates.236 #+name: sensors237 #+begin_src clojure238 (in-ns 'cortex.touch)240 (defn feeler-pixel-coords241 "Returns the coordinates of the feelers in pixel space in lists, one242 list for each triangle, ordered in the same way as (triangles) and243 (pixel-triangles)."244 [#^Geometry geo image]245 (map246 (fn [pixel-triangle]247 (filter248 (fn [coord]249 (inside-triangle? (->triangle pixel-triangle)250 (->vector3f coord)))251 (white-coordinates image (convex-bounds pixel-triangle))))252 (pixel-triangles geo image)))254 (defn feeler-world-coords [#^Geometry geo image]255 (let [transforms256 (map #(triangles->affine-transform257 (->triangle %1) (->triangle %2))258 (pixel-triangles geo image)259 (triangles geo))]260 (map (fn [transform coords]261 (map #(.mult transform (->vector3f %)) coords))262 transforms (feeler-pixel-coords geo image))))264 (defn feeler-origins [#^Geometry geo image]265 (reduce concat (feeler-world-coords geo image)))267 (defn feeler-tips [#^Geometry geo image]268 (let [world-coords (feeler-world-coords geo image)269 normals270 (map271 (fn [triangle]272 (.calculateNormal triangle)273 (.clone (.getNormal triangle)))274 (map ->triangle (triangles geo)))]276 (mapcat (fn [origins normal]277 (map #(.add % normal) origins))278 world-coords normals)))281 (defn touch-topology [#^Geometry geo image]282 (collapse (feeler-pixel-coords geo image)))285 (defn sensors-in-triangle286 "Locate the touch sensors in the triangle, returning a map of their287 UV and geometry-relative coordinates."288 [image mesh tri-index]289 (let [width (.getWidth image)290 height (.getHeight image)291 UV-vertex-coords (triangle-UV-coord mesh width height tri-index)292 bounds (convex-bounds UV-vertex-coords)294 cutout-triangle (points->triangle UV-vertex-coords)295 UV-sensor-coords296 (filter (comp (partial inside-triangle? cutout-triangle)297 (fn [[u v]] (Vector3f. u v 0)))298 (white-coordinates image bounds))299 UV->geometry (triangle-transformation300 cutout-triangle301 (mesh-triangle mesh tri-index))302 geometry-sensor-coords303 (map (fn [[u v]] (.mult UV->geometry (Vector3f. u v 0)))304 UV-sensor-coords)]305 {:UV UV-sensor-coords :geometry geometry-sensor-coords}))307 (defn-memo locate-feelers308 "Search the geometry's tactile UV profile for touch sensors,309 returning their positions in geometry-relative coordinates."310 [#^Geometry geo]311 (let [mesh (.getMesh geo)312 num-triangles (.getTriangleCount mesh)]313 (if-let [image (tactile-sensor-profile geo)]314 (map315 (partial sensors-in-triangle image mesh)316 (range num-triangles))317 (repeat (.getTriangleCount mesh) {:UV nil :geometry nil}))))319 (defn-memo touch-topology320 "Return a sequence of vectors of the form [x y] describing the321 \"topology\" of the tactile sensors. Points that are close together322 in the touch-topology are generally close together in the simulation."323 [#^Gemoetry geo]324 (vec (collapse (reduce concat (map :UV (locate-feelers geo))))))326 (defn-memo feeler-coordinates327 "The location of the touch sensors in world-space coordinates."328 [#^Geometry geo]329 (vec (map :geometry (locate-feelers geo))))330 #+end_src335 * Visualizing Touch336 #+name: visualization337 #+begin_src clojure338 (in-ns 'cortex.touch)340 (defn touch->gray341 "Convert a pair of [distance, max-distance] into a grayscale pixel"342 [distance max-distance]343 (gray344 (- 255345 (rem346 (int347 (* 255 (/ distance max-distance)))348 256))))350 (defn view-touch351 "Creates a function which accepts a list of touch sensor-data and352 displays each element to the screen."353 []354 (view-sense355 (fn356 [[coords sensor-data]]357 (let [image (points->image coords)]358 (dorun359 (for [i (range (count coords))]360 (.setRGB image ((coords i) 0) ((coords i) 1)361 (apply touch->gray (sensor-data i)))))362 image))))363 #+end_src367 * Triangle Manipulation Functions369 The rigid bodies which make up a creature have an underlying370 =Geometry=, which is a =Mesh= plus a =Material= and other important371 data involved with displaying the body.373 A =Mesh= is composed of =Triangles=, and each =Triangle= has three374 verticies which have coordinates in XYZ space and UV space.376 Here, =(triangles)= gets all the triangles which compose a mesh, and377 =(triangle-UV-coord)= returns the the UV coordinates of the verticies378 of a triangle.380 #+name: triangles-1381 #+begin_src clojure382 (in-ns 'cortex.touch)384 (defn vector3f-seq [#^Vector3f v]385 [(.getX v) (.getY v) (.getZ v)])387 (defn triangle-seq [#^Triangle tri]388 [(vector3f-seq (.get1 tri))389 (vector3f-seq (.get2 tri))390 (vector3f-seq (.get3 tri))])392 (defn ->vector3f393 ([coords] (Vector3f. (nth coords 0 0)394 (nth coords 1 0)395 (nth coords 2 0))))397 (defn ->triangle [points]398 (apply #(Triangle. %1 %2 %3) (map ->vector3f points)))400 (defn triangle401 "Get the triangle specified by triangle-index from the mesh within402 bounds."403 [#^Geometry geo triangle-index]404 (triangle-seq405 (let [scratch (Triangle.)]406 (.getTriangle (.getMesh geo) triangle-index scratch) scratch)))408 (defn triangles409 "Return a sequence of all the Triangles which compose a given410 Geometry."411 [#^Geometry geo]412 (map (partial triangle geo) (range (.getTriangleCount (.getMesh geo)))))414 (defn triangle-vertex-indices415 "Get the triangle vertex indices of a given triangle from a given416 mesh."417 [#^Mesh mesh triangle-index]418 (let [indices (int-array 3)]419 (.getTriangle mesh triangle-index indices)420 (vec indices)))422 (defn vertex-UV-coord423 "Get the UV-coordinates of the vertex named by vertex-index"424 [#^Mesh mesh vertex-index]425 (let [UV-buffer426 (.getData427 (.getBuffer428 mesh429 VertexBuffer$Type/TexCoord))]430 [(.get UV-buffer (* vertex-index 2))431 (.get UV-buffer (+ 1 (* vertex-index 2)))]))433 (defn pixel-triangle [#^Geometry geo image index]434 (let [mesh (.getMesh geo)435 width (.getWidth image)436 height (.getHeight image)]437 (vec (map (fn [[u v]] (vector (* width u) (* height v)))438 (map (partial vertex-UV-coord mesh)439 (triangle-vertex-indices mesh index))))))441 (defn pixel-triangles [#^Geometry geo image]442 (let [height (.getHeight image)443 width (.getWidth image)]444 (map (partial pixel-triangle geo image)445 (range (.getTriangleCount (.getMesh geo))))))447 #+end_src449 * Triangle Affine Transforms451 The position of each hair is stored in a 2D image in UV452 coordinates. To place the hair in 3D space we must convert from UV453 coordinates to XYZ coordinates. Each =Triangle= has coordinates in454 both UV-space and XYZ-space, which defines a unique [[http://mathworld.wolfram.com/AffineTransformation.html ][Affine Transform]]455 for translating any coordinate within the UV triangle to the456 cooresponding coordinate in the XYZ triangle.458 #+name: triangles-3459 #+begin_src clojure460 (defn triangle->matrix4f461 "Converts the triangle into a 4x4 matrix: The first three columns462 contain the vertices of the triangle; the last contains the unit463 normal of the triangle. The bottom row is filled with 1s."464 [#^Triangle t]465 (let [mat (Matrix4f.)466 [vert-1 vert-2 vert-3]467 ((comp vec map) #(.get t %) (range 3))468 unit-normal (do (.calculateNormal t)(.getNormal t))469 vertices [vert-1 vert-2 vert-3 unit-normal]]470 (dorun471 (for [row (range 4) col (range 3)]472 (do473 (.set mat col row (.get (vertices row)col))474 (.set mat 3 row 1))))475 mat))477 (defn triangles->affine-transform478 "Returns the affine transformation that converts each vertex in the479 first triangle into the corresponding vertex in the second480 triangle."481 [#^Triangle tri-1 #^Triangle tri-2]482 (.mult483 (triangle->matrix4f tri-2)484 (.invert (triangle->matrix4f tri-1))))485 #+end_src488 * Schrapnel Conversion Functions490 It is convienent to treat a =Triangle= as a sequence of verticies, and491 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion492 functions make this easy. If these classes implemented =Iterable= then493 this code would not be necessary. Hopefully they will in the future.495 #+name: triangles-2496 #+begin_src clojure497 (defn point->vector2f [[u v]]498 (Vector2f. u v))500 (defn vector2f->vector3f [v]501 (Vector3f. (.getX v) (.getY v) 0))503 (defn map-triangle [f #^Triangle tri]504 (Triangle.505 (f 0 (.get1 tri))506 (f 1 (.get2 tri))507 (f 2 (.get3 tri))))509 (defn points->triangle510 "Convert a list of points into a triangle."511 [points]512 (apply #(Triangle. %1 %2 %3)513 (map (fn [point]514 (let [point (vec point)]515 (Vector3f. (get point 0 0)516 (get point 1 0)517 (get point 2 0))))518 (take 3 points))))519 #+end_src522 * Triangle Boundaries524 For efficiency's sake I will divide the UV-image into small squares525 which inscribe each UV-triangle, then extract the points which lie526 inside the triangle and map them to 3D-space using527 =(triangle-transform)= above. To do this I need a function,528 =(inside-triangle?)=, which determines whether a point is inside a529 triangle in 2D UV-space.531 #+name: triangles-4532 #+begin_src clojure533 (defn convex-bounds534 "Returns the smallest square containing the given vertices, as a535 vector of integers [left top width height]."536 [verts]537 (let [xs (map first verts)538 ys (map second verts)539 x0 (Math/floor (apply min xs))540 y0 (Math/floor (apply min ys))541 x1 (Math/ceil (apply max xs))542 y1 (Math/ceil (apply max ys))]543 [x0 y0 (- x1 x0) (- y1 y0)]))545 (defn same-side?546 "Given the points p1 and p2 and the reference point ref, is point p547 on the same side of the line that goes through p1 and p2 as ref is?"548 [p1 p2 ref p]549 (<=550 0551 (.dot552 (.cross (.subtract p2 p1) (.subtract p p1))553 (.cross (.subtract p2 p1) (.subtract ref p1)))))555 (defn inside-triangle?556 "Is the point inside the triangle?"557 {:author "Dylan Holmes"}558 [#^Triangle tri #^Vector3f p]559 (let [[vert-1 vert-2 vert-3] [(.get1 tri) (.get2 tri) (.get3 tri)]]560 (and561 (same-side? vert-1 vert-2 vert-3 p)562 (same-side? vert-2 vert-3 vert-1 p)563 (same-side? vert-3 vert-1 vert-2 p))))564 #+end_src566 #+results: triangles-4567 : #'cortex.touch/inside-triangle?570 * Physics Collision Objects572 The "hairs" are actually =Rays= which extend from a point on a573 =Triangle= in the =Mesh= normal to the =Triangle's= surface.575 #+name: rays576 #+begin_src clojure577 (defn get-ray-origin578 "Return the origin which a Ray would have to have to be in the exact579 center of a particular Triangle in the Geometry in World580 Coordinates."581 [geom tri]582 (let [new (Vector3f.)]583 (.calculateCenter tri)584 (.localToWorld geom (.getCenter tri) new) new))586 (defn get-ray-direction587 "Return the direction which a Ray would have to have to be to point588 normal to the Triangle, in coordinates relative to the center of the589 Triangle."590 [geom tri]591 (let [n+c (Vector3f.)]592 (.calculateNormal tri)593 (.calculateCenter tri)594 (.localToWorld595 geom596 (.add (.getCenter tri) (.getNormal tri)) n+c)597 (.subtract n+c (get-ray-origin geom tri))))598 #+end_src599 * Headers601 #+name: touch-header602 #+begin_src clojure603 (ns cortex.touch604 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry605 to be outfitted with touch sensors with density determined by a UV606 image. In this way a Geometry can know what parts of itself are607 touching nearby objects. Reads specially prepared blender files to608 construct this sense automatically."609 {:author "Robert McIntyre"}610 (:use (cortex world util sense))611 (:use clojure.contrib.def)612 (:import (com.jme3.scene Geometry Node Mesh))613 (:import com.jme3.collision.CollisionResults)614 (:import com.jme3.scene.VertexBuffer$Type)615 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))616 #+end_src618 * Adding Touch to the Worm620 #+name: test-touch621 #+begin_src clojure622 (ns cortex.test.touch623 (:use (cortex world util sense body touch))624 (:use cortex.test.body))626 (cortex.import/mega-import-jme3)628 (defn test-touch []629 (let [the-worm (doto (worm) (body!))630 touch (touch! the-worm)631 touch-display (view-touch)]632 (world (nodify [the-worm (floor)])633 standard-debug-controls635 (fn [world]636 (light-up-everything world))638 (fn [world tpf]639 (touch-display (map #(% (.getRootNode world)) touch))))))640 #+end_src641 * Source Listing642 * Next645 * COMMENT Code Generation646 #+begin_src clojure :tangle ../src/cortex/touch.clj647 <<touch-header>>648 <<meta-data>>649 <<triangles-1>>650 <<triangles-2>>651 <<triangles-3>>652 <<triangles-4>>653 <<sensors>>654 <<rays>>655 <<kernel>>656 <<visualization>>657 #+end_src660 #+begin_src clojure :tangle ../src/cortex/test/touch.clj661 <<test-touch>>662 #+end_src