view org/touch.org @ 247:4e220c8fb1ed

first pass at rough draft complete
author Robert McIntyre <rlm@mit.edu>
date Sun, 12 Feb 2012 15:46:01 -0700
parents 63da037ce1c5
children 267add63b168
line wrap: on
line source
1 #+title: Simulated Sense of Touch
2 #+author: Robert McIntyre
3 #+email: rlm@mit.edu
4 #+description: Simulated touch for AI research using JMonkeyEngine and clojure.
5 #+keywords: simulation, tactile sense, jMonkeyEngine3, clojure
6 #+SETUPFILE: ../../aurellem/org/setup.org
7 #+INCLUDE: ../../aurellem/org/level-0.org
9 * Touch
11 Touch is critical to navigation and spatial reasoning and as such I
12 need a simulated version of it to give to my AI creatures.
14 However, touch in my virtual can not exactly correspond to human touch
15 because my creatures are made out of completely rigid segments that
16 don't deform like human skin.
18 Human skin has a wide array of touch sensors, each of which speciliaze
19 in detecting different vibrational modes and pressures. These sensors
20 can integrate a vast expanse of skin (i.e. your entire palm), or a
21 tiny patch of skin at the tip of your finger. The hairs of the skin
22 help detect objects before they even come into contact with the skin
23 proper.
25 Instead of measuring deformation or vibration, I surround each rigid
26 part with a plenitude of hair-like objects (/feelers/) which do not
27 interact with the physical world. Physical objects can pass through
28 them with no effect. The feelers are able to measure contact with
29 other objects, and constantly report how much of their extent is
30 covered. So, even though the creature's body parts do not deform, the
31 feelers create a margin around those body parts which achieves a sense
32 of touch which is a hybrid between a human's sense of deformation and
33 sense from hairs.
35 Implementing touch in jMonkeyEngine follows a different techinal route
36 than vision and hearing. Those two senses piggybacked off
37 jMonkeyEngine's 3D audio and video rendering subsystems. To simulate
38 touch, I use jMonkeyEngine's physics system to execute many small
39 collision detections, one for each feeler. The placement of the
40 feelers is determined by a UV-mapped image which shows where each
41 feeler should be on the 3D surface of the body.
43 * Defining Touch Meta-Data in Blender
45 Each geometry can have a single UV map which describes the position of
46 the feelers which will constitute its sense of touch. This image path
47 is stored under the "touch" key. The image itself is black and white,
48 with black meaning a feeler length of 0 (no feeler is present) and
49 white meaning a feeler length of =scale=, which is a float stored
50 under the key "scale".
52 #+name: meta-data
53 #+begin_src clojure
54 (defn tactile-sensor-profile
55 "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-scale
62 "Return the length of each feeler. Default scale is 0.01
63 jMonkeyEngine units."
64 [#^Geometry obj]
65 (if-let [scale (meta-data obj "scale")]
66 scale 0.1))
67 #+end_src
69 Here is an example of a UV-map which specifies the position of touch
70 sensors along the surface of the upper segment of the worm.
72 #+attr_html: width=755
73 #+caption: This is the tactile-sensor-profile for the upper segment of the worm. It defines regions of high touch sensitivity (where there are many white pixels) and regions of low sensitivity (where white pixels are sparse).
74 [[../images/finger-UV.png]]
76 * Implementation Summary
78 To simulate touch there are three conceptual steps. For each solid
79 object in the creature, you first have to get UV image and scale
80 paramater which define the position and length of the feelers. Then,
81 you use the triangles which compose the mesh and the UV data stored in
82 the mesh to determine the world-space position and orientation of each
83 feeler. Once every frame, update these positions and orientations to
84 match the current position and orientation of the object, and use
85 physics collision detection to gather tactile data.
87 Extracting the meta-data has already been described. The third step,
88 physics collision detection, is handled in =(touch-kernel)=.
89 Translating the positions and orientations of the feelers from the
90 UV-map to world-space is also a three-step process.
92 - Find the triangles which make up the mesh in pixel-space and in
93 world-space. =(triangles)= =(pixel-triangles)=.
95 - Find the coordinates of each feeler in world-space. These are the
96 origins of the feelers. =(feeler-origins)=.
98 - Calculate the normals of the triangles in world space, and add
99 them to each of the origins of the feelers. These are the
100 normalized coordinates of the tips of the feelers. =(feeler-tips)=.
102 * Triangle Math
103 ** Schrapnel Conversion Functions
105 #+name: triangles-1
106 #+begin_src clojure
107 (defn vector3f-seq [#^Vector3f v]
108 [(.getX v) (.getY v) (.getZ v)])
110 (defn triangle-seq [#^Triangle tri]
111 [(vector3f-seq (.get1 tri))
112 (vector3f-seq (.get2 tri))
113 (vector3f-seq (.get3 tri))])
115 (defn ->vector3f
116 ([coords] (Vector3f. (nth coords 0 0)
117 (nth coords 1 0)
118 (nth coords 2 0))))
120 (defn ->triangle [points]
121 (apply #(Triangle. %1 %2 %3) (map ->vector3f points)))
122 #+end_src
124 It is convienent to treat a =Triangle= as a sequence of verticies, and
125 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion
126 functions make this easy. If these classes implemented =Iterable= then
127 =(seq)= would work on them automitacally.
128 ** Decomposing a 3D shape into Triangles
130 The rigid bodies which make up a creature have an underlying
131 =Geometry=, which is a =Mesh= plus a =Material= and other important
132 data involved with displaying the body.
134 A =Mesh= is composed of =Triangles=, and each =Triangle= has three
135 verticies which have coordinates in world space and UV space.
137 Here, =(triangles)= gets all the world-space triangles which compose a
138 mesh, while =(pixel-triangles)= gets those same triangles expressed in
139 pixel coordinates (which are UV coordinates scaled to fit the height
140 and width of the UV image).
142 #+name: triangles-2
143 #+begin_src clojure
144 (in-ns 'cortex.touch)
145 (defn triangle
146 "Get the triangle specified by triangle-index from the mesh."
147 [#^Geometry geo triangle-index]
148 (triangle-seq
149 (let [scratch (Triangle.)]
150 (.getTriangle (.getMesh geo) triangle-index scratch) scratch)))
152 (defn triangles
153 "Return a sequence of all the Triangles which compose a given
154 Geometry."
155 [#^Geometry geo]
156 (map (partial triangle geo) (range (.getTriangleCount (.getMesh geo)))))
158 (defn triangle-vertex-indices
159 "Get the triangle vertex indices of a given triangle from a given
160 mesh."
161 [#^Mesh mesh triangle-index]
162 (let [indices (int-array 3)]
163 (.getTriangle mesh triangle-index indices)
164 (vec indices)))
166 (defn vertex-UV-coord
167 "Get the UV-coordinates of the vertex named by vertex-index"
168 [#^Mesh mesh vertex-index]
169 (let [UV-buffer
170 (.getData
171 (.getBuffer
172 mesh
173 VertexBuffer$Type/TexCoord))]
174 [(.get UV-buffer (* vertex-index 2))
175 (.get UV-buffer (+ 1 (* vertex-index 2)))]))
177 (defn pixel-triangle [#^Geometry geo image index]
178 (let [mesh (.getMesh geo)
179 width (.getWidth image)
180 height (.getHeight image)]
181 (vec (map (fn [[u v]] (vector (* width u) (* height v)))
182 (map (partial vertex-UV-coord mesh)
183 (triangle-vertex-indices mesh index))))))
185 (defn pixel-triangles [#^Geometry geo image]
186 (let [height (.getHeight image)
187 width (.getWidth image)]
188 (map (partial pixel-triangle geo image)
189 (range (.getTriangleCount (.getMesh geo))))))
190 #+end_src
191 ** The Affine Transform from one Triangle to Another
193 =(pixel-triangles)= gives us the mesh triangles expressed in pixel
194 coordinates and =(triangles)= gives us the mesh triangles expressed in
195 world coordinates. The tactile-sensor-profile gives the position of
196 each feeler in pixel-space. In order to convert pixel-dpace
197 coordinates into world-space coordinates we need something that takes
198 coordinates on the surface of one triangle and gives the corresponding
199 coordinates on the surface of another triangle.
201 Triangles are [[http://mathworld.wolfram.com/AffineTransformation.html ][affine]], which means any triangle can be transformed into
202 any other by a combination of translation, scaling, and
203 rotation. jMonkeyEngine's =Matrix4f= objects can describe any affine
204 transformation. The affine transformation from one triangle to another
205 is readily computable if the triangle is expressed in terms of a $4x4$
206 matrix.
208 \begin{bmatrix}
209 x_1 & x_2 & x_3 & n_x \\
210 y_1 & y_2 & y_3 & n_y \\
211 z_1 & z_2 & z_3 & n_z \\
212 1 & 1 & 1 & 1
213 \end{bmatrix}
215 Here, the first three columns of the matrix are the verticies of the
216 triangle. The last column is the right-handed unit normal of the
217 triangle.
219 With two triangles $T_{1}$ and $T_{2}$ each expressed as a matrix like
220 above, the affine transform from $T_{1}$ to $T_{2}$ is
222 $T_{2}T_{1}^{-1}$
224 The clojure code below recaptiulates the formulas above.
226 #+name: triangles-3
227 #+begin_src clojure
228 (in-ns 'cortex.touch)
230 (defn triangle->matrix4f
231 "Converts the triangle into a 4x4 matrix: The first three columns
232 contain the vertices of the triangle; the last contains the unit
233 normal of the triangle. The bottom row is filled with 1s."
234 [#^Triangle t]
235 (let [mat (Matrix4f.)
236 [vert-1 vert-2 vert-3]
237 ((comp vec map) #(.get t %) (range 3))
238 unit-normal (do (.calculateNormal t)(.getNormal t))
239 vertices [vert-1 vert-2 vert-3 unit-normal]]
240 (dorun
241 (for [row (range 4) col (range 3)]
242 (do
243 (.set mat col row (.get (vertices row) col))
244 (.set mat 3 row 1)))) mat))
246 (defn triangles->affine-transform
247 "Returns the affine transformation that converts each vertex in the
248 first triangle into the corresponding vertex in the second
249 triangle."
250 [#^Triangle tri-1 #^Triangle tri-2]
251 (.mult
252 (triangle->matrix4f tri-2)
253 (.invert (triangle->matrix4f tri-1))))
254 #+end_src
255 ** Triangle Boundaries
257 For efficiency's sake I will divide the tactile-profile image into
258 small squares which inscribe each pixel-triangle, then extract the
259 points which lie inside the triangle and map them to 3D-space using
260 =(triangle-transform)= above. To do this I need a function,
261 =(convex-bounds)= which finds the smallest box which inscribes a 2D
262 triangle.
264 =(inside-triangle?)= determines whether a point is inside a triangle
265 in 2D pixel-space.
267 #+name: triangles-4
268 #+begin_src clojure
269 (defn convex-bounds
270 "Returns the smallest square containing the given vertices, as a
271 vector of integers [left top width height]."
272 [verts]
273 (let [xs (map first verts)
274 ys (map second verts)
275 x0 (Math/floor (apply min xs))
276 y0 (Math/floor (apply min ys))
277 x1 (Math/ceil (apply max xs))
278 y1 (Math/ceil (apply max ys))]
279 [x0 y0 (- x1 x0) (- y1 y0)]))
281 (defn same-side?
282 "Given the points p1 and p2 and the reference point ref, is point p
283 on the same side of the line that goes through p1 and p2 as ref is?"
284 [p1 p2 ref p]
285 (<=
286 0
287 (.dot
288 (.cross (.subtract p2 p1) (.subtract p p1))
289 (.cross (.subtract p2 p1) (.subtract ref p1)))))
291 (defn inside-triangle?
292 "Is the point inside the triangle?"
293 {:author "Dylan Holmes"}
294 [#^Triangle tri #^Vector3f p]
295 (let [[vert-1 vert-2 vert-3] [(.get1 tri) (.get2 tri) (.get3 tri)]]
296 (and
297 (same-side? vert-1 vert-2 vert-3 p)
298 (same-side? vert-2 vert-3 vert-1 p)
299 (same-side? vert-3 vert-1 vert-2 p))))
300 #+end_src
302 * Feeler Coordinates
304 The triangle-related functions above make short work of calculating
305 the positions and orientations of each feeler in world-space.
307 #+name: sensors
308 #+begin_src clojure
309 (in-ns 'cortex.touch)
311 (defn feeler-pixel-coords
312 "Returns the coordinates of the feelers in pixel space in lists, one
313 list for each triangle, ordered in the same way as (triangles) and
314 (pixel-triangles)."
315 [#^Geometry geo image]
316 (map
317 (fn [pixel-triangle]
318 (filter
319 (fn [coord]
320 (inside-triangle? (->triangle pixel-triangle)
321 (->vector3f coord)))
322 (white-coordinates image (convex-bounds pixel-triangle))))
323 (pixel-triangles geo image)))
325 (defn feeler-world-coords
326 "Returns the coordinates of the feelers in world space in lists, one
327 list for each triangle, ordered in the same way as (triangles) and
328 (pixel-triangles)."
329 [#^Geometry geo image]
330 (let [transforms
331 (map #(triangles->affine-transform
332 (->triangle %1) (->triangle %2))
333 (pixel-triangles geo image)
334 (triangles geo))]
335 (map (fn [transform coords]
336 (map #(.mult transform (->vector3f %)) coords))
337 transforms (feeler-pixel-coords geo image))))
339 (defn feeler-origins
340 "The world space coordinates of the root of each feeler."
341 [#^Geometry geo image]
342 (reduce concat (feeler-world-coords geo image)))
344 (defn feeler-tips
345 "The world space coordinates of the tip of each feeler."
346 [#^Geometry geo image]
347 (let [world-coords (feeler-world-coords geo image)
348 normals
349 (map
350 (fn [triangle]
351 (.calculateNormal triangle)
352 (.clone (.getNormal triangle)))
353 (map ->triangle (triangles geo)))]
355 (mapcat (fn [origins normal]
356 (map #(.add % normal) origins))
357 world-coords normals)))
359 (defn touch-topology
360 "touch-topology? is not a function."
361 [#^Geometry geo image]
362 (collapse (reduce concat (feeler-pixel-coords geo image))))
363 #+end_src
364 * Simulated Touch
366 =(touch-kernel)= generates functions to be called from within a
367 simulation that perform the necessary physics collisions to collect
368 tactile data, and =(touch!)= recursively applies it to every node in
369 the creature.
371 #+name: kernel
372 #+begin_src clojure
373 (in-ns 'cortex.touch)
375 (defn set-ray [#^Ray ray #^Matrix4f transform
376 #^Vector3f origin #^Vector3f tip]
377 ;; Doing everything locally recduces garbage collection by enough to
378 ;; be worth it.
379 (.mult transform origin (.getOrigin ray))
381 (.mult transform tip (.getDirection ray))
382 (.subtractLocal (.getDirection ray) (.getOrigin ray)))
384 (defn touch-kernel
385 "Constructs a function which will return tactile sensory data from
386 'geo when called from inside a running simulation"
387 [#^Geometry geo]
388 (if-let
389 [profile (tactile-sensor-profile geo)]
390 (let [ray-reference-origins (feeler-origins geo profile)
391 ray-reference-tips (feeler-tips geo profile)
392 ray-length (tactile-scale geo)
393 current-rays (map (fn [_] (Ray.)) ray-reference-origins)
394 topology (touch-topology geo profile)]
395 (dorun (map #(.setLimit % ray-length) current-rays))
396 (fn [node]
397 (let [transform (.getWorldMatrix geo)]
398 (dorun
399 (map (fn [ray ref-origin ref-tip]
400 (set-ray ray transform ref-origin ref-tip))
401 current-rays ray-reference-origins
402 ray-reference-tips))
403 (vector
404 topology
405 (vec
406 (for [ray current-rays]
407 (do
408 (let [results (CollisionResults.)]
409 (.collideWith node ray results)
410 (let [touch-objects
411 (filter #(not (= geo (.getGeometry %)))
412 results)]
413 [(if (empty? touch-objects)
414 (.getLimit ray)
415 (.getDistance (first touch-objects)))
416 (.getLimit ray)])))))))))))
418 (defn touch!
419 "Endow the creature with the sense of touch. Returns a sequence of
420 functions, one for each body part with a tactile-sensor-proile,
421 each of which when called returns sensory data for that body part."
422 [#^Node creature]
423 (filter
424 (comp not nil?)
425 (map touch-kernel
426 (filter #(isa? (class %) Geometry)
427 (node-seq creature)))))
428 #+end_src
430 * Visualizing Touch
432 #+name: visualization
433 #+begin_src clojure
434 (in-ns 'cortex.touch)
436 (defn touch->gray
437 "Convert a pair of [distance, max-distance] into a grayscale pixel."
438 [distance max-distance]
439 (gray (- 255 (rem (int (* 255 (/ distance max-distance))) 256))))
441 (defn view-touch
442 "Creates a function which accepts a list of touch sensor-data and
443 displays each element to the screen."
444 []
445 (view-sense
446 (fn [[coords sensor-data]]
447 (let [image (points->image coords)]
448 (dorun
449 (for [i (range (count coords))]
450 (.setRGB image ((coords i) 0) ((coords i) 1)
451 (apply touch->gray (sensor-data i))))) image))))
452 #+end_src
453 * Adding Touch to the Worm
455 #+name: test-touch
456 #+begin_src clojure
457 (ns cortex.test.touch
458 (:use (cortex world util sense body touch))
459 (:use cortex.test.body))
461 (cortex.import/mega-import-jme3)
463 (defn test-touch []
464 (let [the-worm (doto (worm) (body!))
465 touch (touch! the-worm)
466 touch-display (view-touch)]
467 (world (nodify [the-worm (floor)])
468 standard-debug-controls
470 (fn [world]
471 (speed-up world)
472 (light-up-everything world))
474 (fn [world tpf]
475 (touch-display
476 (map #(% (.getRootNode world)) touch))))))
477 #+end_src
479 * Headers
481 #+name: touch-header
482 #+begin_src clojure
483 (ns cortex.touch
484 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry
485 to be outfitted with touch sensors with density determined by a UV
486 image. In this way a Geometry can know what parts of itself are
487 touching nearby objects. Reads specially prepared blender files to
488 construct this sense automatically."
489 {:author "Robert McIntyre"}
490 (:use (cortex world util sense))
491 (:use clojure.contrib.def)
492 (:import (com.jme3.scene Geometry Node Mesh))
493 (:import com.jme3.collision.CollisionResults)
494 (:import com.jme3.scene.VertexBuffer$Type)
495 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))
496 #+end_src
498 * Source Listing
499 * Next
502 * COMMENT Code Generation
503 #+begin_src clojure :tangle ../src/cortex/touch.clj
504 <<touch-header>>
505 <<meta-data>>
506 <<triangles-1>>
507 <<triangles-2>>
508 <<triangles-3>>
509 <<triangles-4>>
510 <<sensors>>
511 <<kernel>>
512 <<visualization>>
513 #+end_src
516 #+begin_src clojure :tangle ../src/cortex/test/touch.clj
517 <<test-touch>>
518 #+end_src