Mercurial > cortex
view org/touch.org @ 245:102ac596cc3f
minor formatting changes
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Sun, 12 Feb 2012 14:33:52 -0700 |
parents | f23217324f72 |
children | 63da037ce1c5 |
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.org9 * Touch11 Touch is critical to navigation and spatial reasoning and as such I12 need a simulated version of it to give to my AI creatures.14 However, touch in my virtual can not exactly correspond to human touch15 because my creatures are made out of completely rigid segments that16 don't deform like human skin.18 Human skin has a wide array of touch sensors, each of which speciliaze19 in detecting different vibrational modes and pressures. These sensors20 can integrate a vast expanse of skin (i.e. your entire palm), or a21 tiny patch of skin at the tip of your finger. The hairs of the skin22 help detect objects before they even come into contact with the skin23 proper.25 Instead of measuring deformation or vibration, I surround each rigid26 part with a plenitude of hair-like objects which do not interact with27 the physical world. Physical objects can pass through them with no28 effect. The hairs are able to measure contact with other objects, and29 constantly report how much of their extent is covered. So, even though30 the creature's body parts do not deform, the hairs create a margin31 around those body parts which achieves a sense of touch which is a32 hybrid between a human's sense of deformation and sense from hairs.34 Implementing touch in jMonkeyEngine follows a different techinal route35 than vision and hearing. Those two senses piggybacked off36 jMonkeyEngine's 3D audio and video rendering subsystems. To simulate37 Touch, I use jMonkeyEngine's physics system to execute many small38 collision detections, one for each "hair". The placement of the39 "hairs" is determined by a UV-mapped image which shows where each hair40 should be on the 3D surface of the body.43 * Defining Touch Meta-Data in Blender45 Each geometry can have a single UV map which describes the position of46 the "hairs" which will constitute its sense of touch. This image path47 is stored under the "touch" key. The image itself is black and white,48 with black meaning a hair length of 0 (no hair is present) and white49 meaning a hair length of =scale=, which is a float stored under the50 key "scale". I call these "hairs" /feelers/.52 #+name: meta-data53 #+begin_src clojure54 (defn tactile-sensor-profile55 "Return the touch-sensor distribution image in BufferedImage format,56 or nil if it does not exist."57 [#^Geometry obj]58 (if-let [image-path (meta-data obj "touch")]59 (load-image image-path)))61 (defn tactile-scale62 "Return the maximum length of a hair. All hairs are scalled between63 0.0 and this length, depending on their color. Black is 0, and64 white is maximum length, and everything in between is scalled65 linearlly. Default scale is 0.01 jMonkeyEngine units."66 [#^Geometry obj]67 (if-let [scale (meta-data obj "scale")]68 scale 0.1))69 #+end_src71 ** TODO add image showing example touch-uv map72 ** TODO add metadata display for worm75 * Skin Creation77 =(touch-kernel)= generates the functions which implement the sense of78 touch for a creature. These functions must do 6 things to obtain touch79 data.81 - Get the tactile profile image and scale paramaters which describe82 the layout of feelers along the object's surface.83 =(tactile-sensor-profile)=, =(tactile-scale)=85 - Find the triangles which make up the mesh in pixel-space and in86 world-space.87 =(triangles)= =(pixel-triangles)=89 - Find the coordinates of each pixel in pixel space. These90 coordinates are used to make the touch-topology.91 =(feeler-pixel-coords)=93 - Find the coordinates of each pixel in world-space. These94 coordinates are the origins of the feelers. =(feeler-origins)=96 - Calculate the normals of the triangles in world space, and add97 them to each of the origins of the feelers. These are the98 normalized coordinates of the tips of the feelers.99 For both of these, =(feeler-tips)=101 - Generate some sort of topology for the sensors.102 =(touch-topology)=105 #+name: kernel106 #+begin_src clojure107 (in-ns 'cortex.touch)109 (defn set-ray [#^Ray ray #^Matrix4f transform110 #^Vector3f origin #^Vector3f tip]111 ;; Doing everything locally recduces garbage collection by enough to112 ;; be worth it.113 (.mult transform origin (.getOrigin ray))115 (.mult transform tip (.getDirection ray))116 (.subtractLocal (.getDirection ray) (.getOrigin ray)))118 (defn touch-kernel119 "Constructs a function which will return tactile sensory data from120 'geo when called from inside a running simulation"121 [#^Geometry geo]122 (if-let123 [profile (tactile-sensor-profile geo)]124 (let [ray-reference-origins (feeler-origins geo profile)125 ray-reference-tips (feeler-tips geo profile)126 ray-length (tactile-scale geo)127 current-rays (map (fn [_] (Ray.)) ray-reference-origins)128 topology (touch-topology geo profile)]129 (dorun (map #(.setLimit % ray-length) current-rays))130 (fn [node]131 (let [transform (.getWorldMatrix geo)]132 (dorun133 (map (fn [ray ref-origin ref-tip]134 (set-ray ray transform ref-origin ref-tip))135 current-rays ray-reference-origins136 ray-reference-tips))137 (vector138 topology139 (vec140 (for [ray current-rays]141 (do142 (let [results (CollisionResults.)]143 (.collideWith node ray results)144 (let [touch-objects145 (filter #(not (= geo (.getGeometry %)))146 results)]147 [(if (empty? touch-objects)148 (.getLimit ray)149 (.getDistance (first touch-objects)))150 (.getLimit ray)])))))))))))152 (defn touch!153 "Endow the creature with the sense of touch. Returns a sequence of154 functions, one for each body part with a tactile-sensor-proile,155 each of which when called returns sensory data for that body part."156 [#^Node creature]157 (filter158 (comp not nil?)159 (map touch-kernel160 (filter #(isa? (class %) Geometry)161 (node-seq creature)))))162 #+end_src164 * Sensor Related Functions166 These functions analyze the touch-sensor-profile image convert the167 location of each touch sensor from pixel coordinates to UV-coordinates168 and XYZ-coordinates.170 #+name: sensors171 #+begin_src clojure172 (in-ns 'cortex.touch)174 (defn feeler-pixel-coords175 "Returns the coordinates of the feelers in pixel space in lists, one176 list for each triangle, ordered in the same way as (triangles) and177 (pixel-triangles)."178 [#^Geometry geo image]179 (map180 (fn [pixel-triangle]181 (filter182 (fn [coord]183 (inside-triangle? (->triangle pixel-triangle)184 (->vector3f coord)))185 (white-coordinates image (convex-bounds pixel-triangle))))186 (pixel-triangles geo image)))188 (defn feeler-world-coords [#^Geometry geo image]189 (let [transforms190 (map #(triangles->affine-transform191 (->triangle %1) (->triangle %2))192 (pixel-triangles geo image)193 (triangles geo))]194 (map (fn [transform coords]195 (map #(.mult transform (->vector3f %)) coords))196 transforms (feeler-pixel-coords geo image))))198 (defn feeler-origins [#^Geometry geo image]199 (reduce concat (feeler-world-coords geo image)))201 (defn feeler-tips [#^Geometry geo image]202 (let [world-coords (feeler-world-coords geo image)203 normals204 (map205 (fn [triangle]206 (.calculateNormal triangle)207 (.clone (.getNormal triangle)))208 (map ->triangle (triangles geo)))]210 (mapcat (fn [origins normal]211 (map #(.add % normal) origins))212 world-coords normals)))214 (defn touch-topology [#^Geometry geo image]215 (collapse (reduce concat (feeler-pixel-coords geo image))))216 #+end_src218 * Visualizing Touch219 #+name: visualization220 #+begin_src clojure221 (in-ns 'cortex.touch)223 (defn touch->gray224 "Convert a pair of [distance, max-distance] into a grayscale pixel."225 [distance max-distance]226 (gray (- 255 (rem (int (* 255 (/ distance max-distance))) 256))))228 (defn view-touch229 "Creates a function which accepts a list of touch sensor-data and230 displays each element to the screen."231 []232 (view-sense233 (fn234 [[coords sensor-data]]235 (let [image (points->image coords)]236 (dorun237 (for [i (range (count coords))]238 (.setRGB image ((coords i) 0) ((coords i) 1)239 (apply touch->gray (sensor-data i)))))240 image))))241 #+end_src245 * Triangle Manipulation Functions247 The rigid bodies which make up a creature have an underlying248 =Geometry=, which is a =Mesh= plus a =Material= and other important249 data involved with displaying the body.251 A =Mesh= is composed of =Triangles=, and each =Triangle= has three252 verticies which have coordinates in XYZ space and UV space.254 Here, =(triangles)= gets all the triangles which compose a mesh, and255 =(triangle-UV-coord)= returns the the UV coordinates of the verticies256 of a triangle.258 #+name: triangles-1259 #+begin_src clojure260 (in-ns 'cortex.touch)262 (defn vector3f-seq [#^Vector3f v]263 [(.getX v) (.getY v) (.getZ v)])265 (defn triangle-seq [#^Triangle tri]266 [(vector3f-seq (.get1 tri))267 (vector3f-seq (.get2 tri))268 (vector3f-seq (.get3 tri))])270 (defn ->vector3f271 ([coords] (Vector3f. (nth coords 0 0)272 (nth coords 1 0)273 (nth coords 2 0))))275 (defn ->triangle [points]276 (apply #(Triangle. %1 %2 %3) (map ->vector3f points)))278 (defn triangle279 "Get the triangle specified by triangle-index from the mesh."280 [#^Geometry geo triangle-index]281 (triangle-seq282 (let [scratch (Triangle.)]283 (.getTriangle (.getMesh geo) triangle-index scratch) scratch)))285 (defn triangles286 "Return a sequence of all the Triangles which compose a given287 Geometry."288 [#^Geometry geo]289 (map (partial triangle geo) (range (.getTriangleCount (.getMesh geo)))))291 (defn triangle-vertex-indices292 "Get the triangle vertex indices of a given triangle from a given293 mesh."294 [#^Mesh mesh triangle-index]295 (let [indices (int-array 3)]296 (.getTriangle mesh triangle-index indices)297 (vec indices)))299 (defn vertex-UV-coord300 "Get the UV-coordinates of the vertex named by vertex-index"301 [#^Mesh mesh vertex-index]302 (let [UV-buffer303 (.getData304 (.getBuffer305 mesh306 VertexBuffer$Type/TexCoord))]307 [(.get UV-buffer (* vertex-index 2))308 (.get UV-buffer (+ 1 (* vertex-index 2)))]))310 (defn pixel-triangle [#^Geometry geo image index]311 (let [mesh (.getMesh geo)312 width (.getWidth image)313 height (.getHeight image)]314 (vec (map (fn [[u v]] (vector (* width u) (* height v)))315 (map (partial vertex-UV-coord mesh)316 (triangle-vertex-indices mesh index))))))318 (defn pixel-triangles [#^Geometry geo image]319 (let [height (.getHeight image)320 width (.getWidth image)]321 (map (partial pixel-triangle geo image)322 (range (.getTriangleCount (.getMesh geo))))))324 #+end_src326 * Triangle Affine Transforms328 The position of each hair is stored in a 2D image in UV329 coordinates. To place the hair in 3D space we must convert from UV330 coordinates to XYZ coordinates. Each =Triangle= has coordinates in331 both UV-space and XYZ-space, which defines a unique [[http://mathworld.wolfram.com/AffineTransformation.html ][Affine Transform]]332 for translating any coordinate within the UV triangle to the333 cooresponding coordinate in the XYZ triangle.335 #+name: triangles-3336 #+begin_src clojure337 (in-ns 'cortex.touch)339 (defn triangle->matrix4f340 "Converts the triangle into a 4x4 matrix: The first three columns341 contain the vertices of the triangle; the last contains the unit342 normal of the triangle. The bottom row is filled with 1s."343 [#^Triangle t]344 (let [mat (Matrix4f.)345 [vert-1 vert-2 vert-3]346 ((comp vec map) #(.get t %) (range 3))347 unit-normal (do (.calculateNormal t)(.getNormal t))348 vertices [vert-1 vert-2 vert-3 unit-normal]]349 (dorun350 (for [row (range 4) col (range 3)]351 (do352 (.set mat col row (.get (vertices row)col))353 (.set mat 3 row 1)))) mat))355 (defn triangles->affine-transform356 "Returns the affine transformation that converts each vertex in the357 first triangle into the corresponding vertex in the second358 triangle."359 [#^Triangle tri-1 #^Triangle tri-2]360 (.mult361 (triangle->matrix4f tri-2)362 (.invert (triangle->matrix4f tri-1))))363 #+end_src366 * Schrapnel Conversion Functions368 It is convienent to treat a =Triangle= as a sequence of verticies, and369 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion370 functions make this easy. If these classes implemented =Iterable= then371 this code would not be necessary. Hopefully they will in the future.374 * Triangle Boundaries376 For efficiency's sake I will divide the UV-image into small squares377 which inscribe each UV-triangle, then extract the points which lie378 inside the triangle and map them to 3D-space using379 =(triangle-transform)= above. To do this I need a function,380 =(inside-triangle?)=, which determines whether a point is inside a381 triangle in 2D UV-space.383 #+name: triangles-4384 #+begin_src clojure385 (defn convex-bounds386 "Returns the smallest square containing the given vertices, as a387 vector of integers [left top width height]."388 [verts]389 (let [xs (map first verts)390 ys (map second verts)391 x0 (Math/floor (apply min xs))392 y0 (Math/floor (apply min ys))393 x1 (Math/ceil (apply max xs))394 y1 (Math/ceil (apply max ys))]395 [x0 y0 (- x1 x0) (- y1 y0)]))397 (defn same-side?398 "Given the points p1 and p2 and the reference point ref, is point p399 on the same side of the line that goes through p1 and p2 as ref is?"400 [p1 p2 ref p]401 (<=402 0403 (.dot404 (.cross (.subtract p2 p1) (.subtract p p1))405 (.cross (.subtract p2 p1) (.subtract ref p1)))))407 (defn inside-triangle?408 "Is the point inside the triangle?"409 {:author "Dylan Holmes"}410 [#^Triangle tri #^Vector3f p]411 (let [[vert-1 vert-2 vert-3] [(.get1 tri) (.get2 tri) (.get3 tri)]]412 (and413 (same-side? vert-1 vert-2 vert-3 p)414 (same-side? vert-2 vert-3 vert-1 p)415 (same-side? vert-3 vert-1 vert-2 p))))416 #+end_src418 * Physics Collision Objects420 The "hairs" are actually =Rays= which extend from a point on a421 =Triangle= in the =Mesh= normal to the =Triangle's= surface.423 * Headers425 #+name: touch-header426 #+begin_src clojure427 (ns cortex.touch428 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry429 to be outfitted with touch sensors with density determined by a UV430 image. In this way a Geometry can know what parts of itself are431 touching nearby objects. Reads specially prepared blender files to432 construct this sense automatically."433 {:author "Robert McIntyre"}434 (:use (cortex world util sense))435 (:use clojure.contrib.def)436 (:import (com.jme3.scene Geometry Node Mesh))437 (:import com.jme3.collision.CollisionResults)438 (:import com.jme3.scene.VertexBuffer$Type)439 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))440 #+end_src442 * Adding Touch to the Worm444 #+name: test-touch445 #+begin_src clojure446 (ns cortex.test.touch447 (:use (cortex world util sense body touch))448 (:use cortex.test.body))450 (cortex.import/mega-import-jme3)452 (defn test-touch []453 (let [the-worm (doto (worm) (body!))454 touch (touch! the-worm)455 touch-display (view-touch)]456 (world (nodify [the-worm (floor)])457 standard-debug-controls459 (fn [world]460 (speed-up world)461 (light-up-everything world))463 (fn [world tpf]464 (touch-display (map #(% (.getRootNode world)) touch))465 ))))466 #+end_src467 * Source Listing468 * Next471 * COMMENT Code Generation472 #+begin_src clojure :tangle ../src/cortex/touch.clj473 <<touch-header>>474 <<meta-data>>475 <<triangles-1>>476 <<triangles-3>>477 <<triangles-4>>478 <<sensors>>479 <<kernel>>480 <<visualization>>481 #+end_src484 #+begin_src clojure :tangle ../src/cortex/test/touch.clj485 <<test-touch>>486 #+end_src