Mercurial > cortex
view org/touch.org @ 244:f23217324f72
changed semantics of feeler lengths
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Sun, 12 Feb 2012 14:29:09 -0700 |
parents | f33fec68f775 |
children | 102ac596cc3f |
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 position46 and length of the "hairs" which will constitute its sense of47 touch. This image path is stored under the "touch" key. The image48 itself is grayscale, with black meaning a hair length of 0 (no hair is49 present) and white meaning a hair length of =scale=, which is a float50 stored under the key "scale". If the pixel is gray then the resultant51 hair length is linearly interpolated between 0 and =scale=. I call52 these "hairs" /feelers/.54 #+name: meta-data55 #+begin_src clojure56 (defn tactile-sensor-profile57 "Return the touch-sensor distribution image in BufferedImage format,58 or nil if it does not exist."59 [#^Geometry obj]60 (if-let [image-path (meta-data obj "touch")]61 (load-image image-path)))63 (defn tactile-scale64 "Return the maximum length of a hair. All hairs are scalled between65 0.0 and this length, depending on their color. Black is 0, and66 white is maximum length, and everything in between is scalled67 linearlly. Default scale is 0.01 jMonkeyEngine units."68 [#^Geometry obj]69 (if-let [scale (meta-data obj "scale")]70 scale 0.1))71 #+end_src73 ** TODO add image showing example touch-uv map74 ** TODO add metadata display for worm77 * Skin Creation78 * TODO get the actual lengths for each feeler81 =(touch-kernel)= generates the functions which implement the sense of82 touch for a creature. These functions must do 6 things to obtain touch83 data.85 - Get the tactile profile image and scale paramaters which describe86 the layout of feelers along the object's surface.87 =(tactile-sensor-profile)=, =(tactile-scale)=89 - Get the lengths of each feeler by analyzing the color of the90 pixels in the tactile profile image.91 NOT IMPLEMENTED YET93 - Find the triangles which make up the mesh in pixel-space and in94 world-space.95 =(triangles)= =(pixel-triangles)=97 - Find the coordinates of each pixel in pixel space. These98 coordinates are used to make the touch-topology.99 =(feeler-pixel-coords)=101 - Find the coordinates of each pixel in world-space. These102 coordinates are the origins of the feelers. =(feeler-origins)=104 - Calculate the normals of the triangles in world space, and add105 them to each of the origins of the feelers. These are the106 normalized coordinates of the tips of the feelers.107 For both of these, =(feeler-tips)=109 - Generate some sort of topology for the sensors.110 =(touch-topology)=113 #+name: kernel114 #+begin_src clojure115 (in-ns 'cortex.touch)117 (declare touch-topology feelers set-ray)119 (defn set-ray [#^Ray ray #^Matrix4f transform120 #^Vector3f origin #^Vector3f tip]121 ;; Doing everything locally recduces garbage collection by enough to122 ;; be worth it.123 (.mult transform origin (.getOrigin ray))125 (.mult transform tip (.getDirection ray))126 (.subtractLocal (.getDirection ray) (.getOrigin ray)))128 (defn touch-kernel129 "Constructs a function which will return tactile sensory data from130 'geo when called from inside a running simulation"131 [#^Geometry geo]132 (if-let133 [profile (tactile-sensor-profile geo)]134 (let [ray-reference-origins (feeler-origins geo profile)135 ray-reference-tips (feeler-tips geo profile)136 ray-length (tactile-scale geo)137 current-rays (map (fn [_] (Ray.)) ray-reference-origins)138 topology (touch-topology geo profile)]139 (dorun (map #(.setLimit % ray-length) current-rays))140 (fn [node]141 (let [transform (.getWorldMatrix geo)]142 (dorun143 (map (fn [ray ref-origin ref-tip]144 (set-ray ray transform ref-origin ref-tip))145 current-rays ray-reference-origins146 ray-reference-tips))147 (vector148 topology149 (vec150 (for [ray current-rays]151 (do152 (let [results (CollisionResults.)]153 (.collideWith node ray results)154 (let [touch-objects155 (filter #(not (= geo (.getGeometry %)))156 results)]157 [(if (empty? touch-objects)158 (.getLimit ray)159 (.getDistance (first touch-objects)))160 (.getLimit ray)])))))))))))162 (defn touch!163 "Endow the creature with the sense of touch. Returns a sequence of164 functions, one for each body part with a tactile-sensor-proile,165 each of which when called returns sensory data for that body part."166 [#^Node creature]167 (filter168 (comp not nil?)169 (map touch-kernel170 (filter #(isa? (class %) Geometry)171 (node-seq creature)))))172 #+end_src174 #+results: kernel175 : #'cortex.touch/touch!177 * Sensor Related Functions179 These functions analyze the touch-sensor-profile image convert the180 location of each touch sensor from pixel coordinates to UV-coordinates181 and XYZ-coordinates.183 #+name: sensors184 #+begin_src clojure185 (in-ns 'cortex.touch)187 (defn feeler-pixel-coords188 "Returns the coordinates of the feelers in pixel space in lists, one189 list for each triangle, ordered in the same way as (triangles) and190 (pixel-triangles)."191 [#^Geometry geo image]192 (map193 (fn [pixel-triangle]194 (filter195 (fn [coord]196 (inside-triangle? (->triangle pixel-triangle)197 (->vector3f coord)))198 (white-coordinates image (convex-bounds pixel-triangle))))199 (pixel-triangles geo image)))201 (defn feeler-world-coords [#^Geometry geo image]202 (let [transforms203 (map #(triangles->affine-transform204 (->triangle %1) (->triangle %2))205 (pixel-triangles geo image)206 (triangles geo))]207 (map (fn [transform coords]208 (map #(.mult transform (->vector3f %)) coords))209 transforms (feeler-pixel-coords geo image))))211 (defn feeler-origins [#^Geometry geo image]212 (reduce concat (feeler-world-coords geo image)))214 (defn feeler-tips [#^Geometry geo image]215 (let [world-coords (feeler-world-coords geo image)216 normals217 (map218 (fn [triangle]219 (.calculateNormal triangle)220 (.clone (.getNormal triangle)))221 (map ->triangle (triangles geo)))]223 (mapcat (fn [origins normal]224 (map #(.add % normal) origins))225 world-coords normals)))228 (defn touch-topology [#^Geometry geo image]229 (collapse (reduce concat (feeler-pixel-coords geo image))))230 #+end_src232 * Visualizing Touch233 #+name: visualization234 #+begin_src clojure235 (in-ns 'cortex.touch)237 (defn touch->gray238 "Convert a pair of [distance, max-distance] into a grayscale pixel"239 [distance max-distance]240 (gray241 (- 255242 (rem243 (int244 (* 255 (/ distance max-distance)))245 256))))247 (defn view-touch248 "Creates a function which accepts a list of touch sensor-data and249 displays each element to the screen."250 []251 (view-sense252 (fn253 [[coords sensor-data]]254 (let [image (points->image coords)]255 (dorun256 (for [i (range (count coords))]257 (.setRGB image ((coords i) 0) ((coords i) 1)258 (apply touch->gray (sensor-data i)))))259 image))))260 #+end_src264 * Triangle Manipulation Functions266 The rigid bodies which make up a creature have an underlying267 =Geometry=, which is a =Mesh= plus a =Material= and other important268 data involved with displaying the body.270 A =Mesh= is composed of =Triangles=, and each =Triangle= has three271 verticies which have coordinates in XYZ space and UV space.273 Here, =(triangles)= gets all the triangles which compose a mesh, and274 =(triangle-UV-coord)= returns the the UV coordinates of the verticies275 of a triangle.277 #+name: triangles-1278 #+begin_src clojure279 (in-ns 'cortex.touch)281 (defn vector3f-seq [#^Vector3f v]282 [(.getX v) (.getY v) (.getZ v)])284 (defn triangle-seq [#^Triangle tri]285 [(vector3f-seq (.get1 tri))286 (vector3f-seq (.get2 tri))287 (vector3f-seq (.get3 tri))])289 (defn ->vector3f290 ([coords] (Vector3f. (nth coords 0 0)291 (nth coords 1 0)292 (nth coords 2 0))))294 (defn ->triangle [points]295 (apply #(Triangle. %1 %2 %3) (map ->vector3f points)))297 (defn triangle298 "Get the triangle specified by triangle-index from the mesh within299 bounds."300 [#^Geometry geo triangle-index]301 (triangle-seq302 (let [scratch (Triangle.)]303 (.getTriangle (.getMesh geo) triangle-index scratch) scratch)))305 (defn triangles306 "Return a sequence of all the Triangles which compose a given307 Geometry."308 [#^Geometry geo]309 (map (partial triangle geo) (range (.getTriangleCount (.getMesh geo)))))311 (defn triangle-vertex-indices312 "Get the triangle vertex indices of a given triangle from a given313 mesh."314 [#^Mesh mesh triangle-index]315 (let [indices (int-array 3)]316 (.getTriangle mesh triangle-index indices)317 (vec indices)))319 (defn vertex-UV-coord320 "Get the UV-coordinates of the vertex named by vertex-index"321 [#^Mesh mesh vertex-index]322 (let [UV-buffer323 (.getData324 (.getBuffer325 mesh326 VertexBuffer$Type/TexCoord))]327 [(.get UV-buffer (* vertex-index 2))328 (.get UV-buffer (+ 1 (* vertex-index 2)))]))330 (defn pixel-triangle [#^Geometry geo image index]331 (let [mesh (.getMesh geo)332 width (.getWidth image)333 height (.getHeight image)]334 (vec (map (fn [[u v]] (vector (* width u) (* height v)))335 (map (partial vertex-UV-coord mesh)336 (triangle-vertex-indices mesh index))))))338 (defn pixel-triangles [#^Geometry geo image]339 (let [height (.getHeight image)340 width (.getWidth image)]341 (map (partial pixel-triangle geo image)342 (range (.getTriangleCount (.getMesh geo))))))344 #+end_src346 * Triangle Affine Transforms348 The position of each hair is stored in a 2D image in UV349 coordinates. To place the hair in 3D space we must convert from UV350 coordinates to XYZ coordinates. Each =Triangle= has coordinates in351 both UV-space and XYZ-space, which defines a unique [[http://mathworld.wolfram.com/AffineTransformation.html ][Affine Transform]]352 for translating any coordinate within the UV triangle to the353 cooresponding coordinate in the XYZ triangle.355 #+name: triangles-3356 #+begin_src clojure357 (in-ns 'cortex.touch)359 (defn triangle->matrix4f360 "Converts the triangle into a 4x4 matrix: The first three columns361 contain the vertices of the triangle; the last contains the unit362 normal of the triangle. The bottom row is filled with 1s."363 [#^Triangle t]364 (let [mat (Matrix4f.)365 [vert-1 vert-2 vert-3]366 ((comp vec map) #(.get t %) (range 3))367 unit-normal (do (.calculateNormal t)(.getNormal t))368 vertices [vert-1 vert-2 vert-3 unit-normal]]369 (dorun370 (for [row (range 4) col (range 3)]371 (do372 (.set mat col row (.get (vertices row)col))373 (.set mat 3 row 1))))374 mat))376 (defn triangles->affine-transform377 "Returns the affine transformation that converts each vertex in the378 first triangle into the corresponding vertex in the second379 triangle."380 [#^Triangle tri-1 #^Triangle tri-2]381 (.mult382 (triangle->matrix4f tri-2)383 (.invert (triangle->matrix4f tri-1))))384 #+end_src387 * Schrapnel Conversion Functions389 It is convienent to treat a =Triangle= as a sequence of verticies, and390 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion391 functions make this easy. If these classes implemented =Iterable= then392 this code would not be necessary. Hopefully they will in the future.395 * Triangle Boundaries397 For efficiency's sake I will divide the UV-image into small squares398 which inscribe each UV-triangle, then extract the points which lie399 inside the triangle and map them to 3D-space using400 =(triangle-transform)= above. To do this I need a function,401 =(inside-triangle?)=, which determines whether a point is inside a402 triangle in 2D UV-space.404 #+name: triangles-4405 #+begin_src clojure406 (defn convex-bounds407 "Returns the smallest square containing the given vertices, as a408 vector of integers [left top width height]."409 [verts]410 (let [xs (map first verts)411 ys (map second verts)412 x0 (Math/floor (apply min xs))413 y0 (Math/floor (apply min ys))414 x1 (Math/ceil (apply max xs))415 y1 (Math/ceil (apply max ys))]416 [x0 y0 (- x1 x0) (- y1 y0)]))418 (defn same-side?419 "Given the points p1 and p2 and the reference point ref, is point p420 on the same side of the line that goes through p1 and p2 as ref is?"421 [p1 p2 ref p]422 (<=423 0424 (.dot425 (.cross (.subtract p2 p1) (.subtract p p1))426 (.cross (.subtract p2 p1) (.subtract ref p1)))))428 (defn inside-triangle?429 "Is the point inside the triangle?"430 {:author "Dylan Holmes"}431 [#^Triangle tri #^Vector3f p]432 (let [[vert-1 vert-2 vert-3] [(.get1 tri) (.get2 tri) (.get3 tri)]]433 (and434 (same-side? vert-1 vert-2 vert-3 p)435 (same-side? vert-2 vert-3 vert-1 p)436 (same-side? vert-3 vert-1 vert-2 p))))437 #+end_src439 * Physics Collision Objects441 The "hairs" are actually =Rays= which extend from a point on a442 =Triangle= in the =Mesh= normal to the =Triangle's= surface.444 * Headers446 #+name: touch-header447 #+begin_src clojure448 (ns cortex.touch449 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry450 to be outfitted with touch sensors with density determined by a UV451 image. In this way a Geometry can know what parts of itself are452 touching nearby objects. Reads specially prepared blender files to453 construct this sense automatically."454 {:author "Robert McIntyre"}455 (:use (cortex world util sense))456 (:use clojure.contrib.def)457 (:import (com.jme3.scene Geometry Node Mesh))458 (:import com.jme3.collision.CollisionResults)459 (:import com.jme3.scene.VertexBuffer$Type)460 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))461 #+end_src463 * Adding Touch to the Worm465 #+name: test-touch466 #+begin_src clojure467 (ns cortex.test.touch468 (:use (cortex world util sense body touch))469 (:use cortex.test.body))471 (cortex.import/mega-import-jme3)473 (defn test-touch []474 (let [the-worm (doto (worm) (body!))475 touch (touch! the-worm)476 touch-display (view-touch)]477 (world (nodify [the-worm (floor)])478 standard-debug-controls480 (fn [world]481 (speed-up world)482 (light-up-everything world))484 (fn [world tpf]485 (touch-display (map #(% (.getRootNode world)) touch))486 ))))487 #+end_src488 * Source Listing489 * Next492 * COMMENT Code Generation493 #+begin_src clojure :tangle ../src/cortex/touch.clj494 <<touch-header>>495 <<meta-data>>496 <<triangles-1>>497 <<triangles-3>>498 <<triangles-4>>499 <<sensors>>500 <<kernel>>501 <<visualization>>502 #+end_src505 #+begin_src clojure :tangle ../src/cortex/test/touch.clj506 <<test-touch>>507 #+end_src