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 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
11 * Touch
13 Touch is critical to navigation and spatial reasoning and as such I
14 need a simulated version of it to give to my AI creatures.
16 However, touch in my virtual can not exactly correspond to human touch
17 because my creatures are made out of completely rigid segments that
18 don't deform like human skin.
20 Human skin has a wide array of touch sensors, each of which speciliaze
21 in detecting different vibrational modes and pressures. These sensors
22 can integrate a vast expanse of skin (i.e. your entire palm), or a
23 tiny patch of skin at the tip of your finger. The hairs of the skin
24 help detect objects before they even come into contact with the skin
25 proper.
27 Instead of measuring deformation or vibration, I surround each rigid
28 part with a plenitude of hair-like objects which do not interact with
29 the physical world. Physical objects can pass through them with no
30 effect. The hairs are able to measure contact with other objects, and
31 constantly report how much of their extent is covered. So, even though
32 the creature's body parts do not deform, the hairs create a margin
33 around those body parts which achieves a sense of touch which is a
34 hybrid between a human's sense of deformation and sense from hairs.
36 Implementing touch in jMonkeyEngine follows a different techinal route
37 than vision and hearing. Those two senses piggybacked off
38 jMonkeyEngine's 3D audio and video rendering subsystems. To simulate
39 Touch, I use jMonkeyEngine's physics system to execute many small
40 collision detections, one for each "hair". The placement of the
41 "hairs" is determined by a UV-mapped image which shows where each hair
42 should be on the 3D surface of the body.
45 * Defining Touch Meta-Data in Blender
47 Each geometry can have a single UV map which describes the position
48 and length of the "hairs" which will constitute its sense of
49 touch. This image path is stored under the "touch" key. The image
50 itself is grayscale, with black meaning a hair length of 0 (no hair is
51 present) and white meaning a hair length of =scale=, which is a float
52 stored under the key "scale". If the pixel is gray then the resultant
53 hair length is linearly interpolated between 0 and =scale=. I call
54 these "hairs" /feelers/.
56 #+name: meta-data
57 #+begin_src clojure
58 (defn tactile-sensor-profile
59 "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-scale
66 "Return the maximum length of a hair. All hairs are scalled between
67 0.0 and this length, depending on their color. Black is 0, and
68 white is maximum length, and everything in between is scalled
69 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_src
75 ** TODO add image showing example touch-uv map
76 ** TODO add metadata display for worm
79 * Skin Creation
80 * TODO get the actual lengths for each hair
82 #+begin_src clojure
83 pixel-triangles
84 xyz-triangles
85 conversions (map triangles->affine-transform pixel-triangles
86 xyz-triangles)
88 #+end_src
91 =(touch-kernel)= generates the functions which implement the sense of
92 touch for a creature. These functions must do 6 things to obtain touch
93 data.
95 - Get the tactile profile image and scale paramaters which describe
96 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 the
100 pixels in the tactile profile image.
101 NOT IMPLEMENTED YET
103 - Find the triangles which make up the mesh in pixel-space and in
104 world-space.
105 =(triangles)= =(pixel-triangles)=
107 - Find the coordinates of each pixel in pixel space. These
108 coordinates are used to make the touch-topology.
109 =(feeler-pixel-coords)=
111 - Find the coordinates of each pixel in world-space. These
112 coordinates are the origins of the feelers. =(feeler-origins)=
114 - Calculate the normals of the triangles in world space, and add
115 them to each of the origins of the feelers. These are the
116 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 clojure
127 #+end_src
131 #+name: kernel
132 #+begin_src clojure
133 (in-ns 'cortex.touch)
135 (declare touch-topology feelers set-ray)
137 (defn set-ray [#^Ray ray #^Matrix4f transform
138 #^Vector3f origin #^Vector3f tip
139 length]
140 (.setOrigin ray (.mult transform origin))
141 (.setDirection ray (.subtract
142 (.mult transform tip)
143 (.getOrigin ray)))
144 (.setLimit ray length)
145 ray)
148 (defn touch-kernel
149 "Constructs a function which will return tactile sensory data from
150 '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) nil
159 (fn [node]
160 (let [transform (.getWorldMatrix geo)]
161 (dorun
162 (map (fn [ray ref-origin ref-tip length]
163 (set-ray ray transform ref-origin ref-tip length))
164 current-rays ray-reference-origins
165 ray-reference-tips ray-lengths))
166 (vector
167 topology
168 (vec
169 (for [ray current-rays]
170 (do
171 (let [results (CollisionResults.)]
172 (.collideWith node ray results)
173 (let [touch-objects
174 (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 called
183 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 nil
190 (fn [node]
191 (let [sensor-origins
192 (map
193 #(map (partial local-to-world geo) %)
194 feeler-coords)
195 triangle-normals
196 (map (partial get-ray-direction geo)
197 tris)
198 rays
199 (flatten
200 (map (fn [origins norm]
201 (map #(doto (Ray. % norm)
202 (.setLimit limit)) origins))
203 sensor-origins triangle-normals))]
204 (vector
205 (touch-topology geo)
206 (vec
207 (for [ray rays]
208 (do
209 (let [results (CollisionResults.)]
210 (.collideWith node ray results)
211 (let [touch-objects
212 (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 of
220 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 (filter
224 (comp not nil?)
225 (map touch-kernel
226 (filter #(isa? (class %) Geometry)
227 (node-seq creature)))))
228 #+end_src
230 * Sensor Related Functions
232 These functions analyze the touch-sensor-profile image convert the
233 location of each touch sensor from pixel coordinates to UV-coordinates
234 and XYZ-coordinates.
236 #+name: sensors
237 #+begin_src clojure
238 (in-ns 'cortex.touch)
240 (defn feeler-pixel-coords
241 "Returns the coordinates of the feelers in pixel space in lists, one
242 list for each triangle, ordered in the same way as (triangles) and
243 (pixel-triangles)."
244 [#^Geometry geo image]
245 (map
246 (fn [pixel-triangle]
247 (filter
248 (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 [transforms
256 (map #(triangles->affine-transform
257 (->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 normals
270 (map
271 (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-triangle
286 "Locate the touch sensors in the triangle, returning a map of their
287 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-coords
296 (filter (comp (partial inside-triangle? cutout-triangle)
297 (fn [[u v]] (Vector3f. u v 0)))
298 (white-coordinates image bounds))
299 UV->geometry (triangle-transformation
300 cutout-triangle
301 (mesh-triangle mesh tri-index))
302 geometry-sensor-coords
303 (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-feelers
308 "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 (map
315 (partial sensors-in-triangle image mesh)
316 (range num-triangles))
317 (repeat (.getTriangleCount mesh) {:UV nil :geometry nil}))))
319 (defn-memo touch-topology
320 "Return a sequence of vectors of the form [x y] describing the
321 \"topology\" of the tactile sensors. Points that are close together
322 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-coordinates
327 "The location of the touch sensors in world-space coordinates."
328 [#^Geometry geo]
329 (vec (map :geometry (locate-feelers geo))))
330 #+end_src
335 * Visualizing Touch
336 #+name: visualization
337 #+begin_src clojure
338 (in-ns 'cortex.touch)
340 (defn touch->gray
341 "Convert a pair of [distance, max-distance] into a grayscale pixel"
342 [distance max-distance]
343 (gray
344 (- 255
345 (rem
346 (int
347 (* 255 (/ distance max-distance)))
348 256))))
350 (defn view-touch
351 "Creates a function which accepts a list of touch sensor-data and
352 displays each element to the screen."
353 []
354 (view-sense
355 (fn
356 [[coords sensor-data]]
357 (let [image (points->image coords)]
358 (dorun
359 (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_src
367 * Triangle Manipulation Functions
369 The rigid bodies which make up a creature have an underlying
370 =Geometry=, which is a =Mesh= plus a =Material= and other important
371 data involved with displaying the body.
373 A =Mesh= is composed of =Triangles=, and each =Triangle= has three
374 verticies which have coordinates in XYZ space and UV space.
376 Here, =(triangles)= gets all the triangles which compose a mesh, and
377 =(triangle-UV-coord)= returns the the UV coordinates of the verticies
378 of a triangle.
380 #+name: triangles-1
381 #+begin_src clojure
382 (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 ->vector3f
393 ([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 triangle
401 "Get the triangle specified by triangle-index from the mesh within
402 bounds."
403 [#^Geometry geo triangle-index]
404 (triangle-seq
405 (let [scratch (Triangle.)]
406 (.getTriangle (.getMesh geo) triangle-index scratch) scratch)))
408 (defn triangles
409 "Return a sequence of all the Triangles which compose a given
410 Geometry."
411 [#^Geometry geo]
412 (map (partial triangle geo) (range (.getTriangleCount (.getMesh geo)))))
414 (defn triangle-vertex-indices
415 "Get the triangle vertex indices of a given triangle from a given
416 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-coord
423 "Get the UV-coordinates of the vertex named by vertex-index"
424 [#^Mesh mesh vertex-index]
425 (let [UV-buffer
426 (.getData
427 (.getBuffer
428 mesh
429 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_src
449 * Triangle Affine Transforms
451 The position of each hair is stored in a 2D image in UV
452 coordinates. To place the hair in 3D space we must convert from UV
453 coordinates to XYZ coordinates. Each =Triangle= has coordinates in
454 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 the
456 cooresponding coordinate in the XYZ triangle.
458 #+name: triangles-3
459 #+begin_src clojure
460 (defn triangle->matrix4f
461 "Converts the triangle into a 4x4 matrix: The first three columns
462 contain the vertices of the triangle; the last contains the unit
463 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 (dorun
471 (for [row (range 4) col (range 3)]
472 (do
473 (.set mat col row (.get (vertices row)col))
474 (.set mat 3 row 1))))
475 mat))
477 (defn triangles->affine-transform
478 "Returns the affine transformation that converts each vertex in the
479 first triangle into the corresponding vertex in the second
480 triangle."
481 [#^Triangle tri-1 #^Triangle tri-2]
482 (.mult
483 (triangle->matrix4f tri-2)
484 (.invert (triangle->matrix4f tri-1))))
485 #+end_src
488 * Schrapnel Conversion Functions
490 It is convienent to treat a =Triangle= as a sequence of verticies, and
491 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion
492 functions make this easy. If these classes implemented =Iterable= then
493 this code would not be necessary. Hopefully they will in the future.
495 #+name: triangles-2
496 #+begin_src clojure
497 (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->triangle
510 "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_src
522 * Triangle Boundaries
524 For efficiency's sake I will divide the UV-image into small squares
525 which inscribe each UV-triangle, then extract the points which lie
526 inside the triangle and map them to 3D-space using
527 =(triangle-transform)= above. To do this I need a function,
528 =(inside-triangle?)=, which determines whether a point is inside a
529 triangle in 2D UV-space.
531 #+name: triangles-4
532 #+begin_src clojure
533 (defn convex-bounds
534 "Returns the smallest square containing the given vertices, as a
535 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 p
547 on the same side of the line that goes through p1 and p2 as ref is?"
548 [p1 p2 ref p]
549 (<=
550 0
551 (.dot
552 (.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 (and
561 (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_src
566 #+results: triangles-4
567 : #'cortex.touch/inside-triangle?
570 * Physics Collision Objects
572 The "hairs" are actually =Rays= which extend from a point on a
573 =Triangle= in the =Mesh= normal to the =Triangle's= surface.
575 #+name: rays
576 #+begin_src clojure
577 (defn get-ray-origin
578 "Return the origin which a Ray would have to have to be in the exact
579 center of a particular Triangle in the Geometry in World
580 Coordinates."
581 [geom tri]
582 (let [new (Vector3f.)]
583 (.calculateCenter tri)
584 (.localToWorld geom (.getCenter tri) new) new))
586 (defn get-ray-direction
587 "Return the direction which a Ray would have to have to be to point
588 normal to the Triangle, in coordinates relative to the center of the
589 Triangle."
590 [geom tri]
591 (let [n+c (Vector3f.)]
592 (.calculateNormal tri)
593 (.calculateCenter tri)
594 (.localToWorld
595 geom
596 (.add (.getCenter tri) (.getNormal tri)) n+c)
597 (.subtract n+c (get-ray-origin geom tri))))
598 #+end_src
599 * Headers
601 #+name: touch-header
602 #+begin_src clojure
603 (ns cortex.touch
604 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry
605 to be outfitted with touch sensors with density determined by a UV
606 image. In this way a Geometry can know what parts of itself are
607 touching nearby objects. Reads specially prepared blender files to
608 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_src
618 * Adding Touch to the Worm
620 #+name: test-touch
621 #+begin_src clojure
622 (ns cortex.test.touch
623 (: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-controls
635 (fn [world]
636 (light-up-everything world))
638 (fn [world tpf]
639 (touch-display (map #(% (.getRootNode world)) touch))))))
640 #+end_src
641 * Source Listing
642 * Next
645 * COMMENT Code Generation
646 #+begin_src clojure :tangle ../src/cortex/touch.clj
647 <<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_src
660 #+begin_src clojure :tangle ../src/cortex/test/touch.clj
661 <<test-touch>>
662 #+end_src