view org/touch.org @ 241:f2e583be8584

saving progress...
author Robert McIntyre <rlm@mit.edu>
date Sun, 12 Feb 2012 13:30:42 -0700
parents 6961377c4554
children a7f26a074071
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 touch-kernel
138 "Constructs a function which will return tactile sensory data from
139 'geo when called from inside a running simulation"
140 [#^Geometry geo]
141 (let [[ray-reference-origins
142 ray-reference-tips
143 ray-lengths] (feelers geo)
144 current-rays (map (fn [] (Ray.)) ray-reference-origins)
145 topology (touch-topology geo)]
146 (if (empty? ray-reference-origins) nil
147 (fn [node]
148 (let [transform (.getWorldMatrix geo)]
149 (dorun
150 (map (fn [ray ref-origin ref-tip length]
151 (set-ray ray transform ref-origin ref-tip length))
152 current-rays ray-reference-origins
153 ray-reference-tips ray-lengths))
154 (vector
155 topology
156 (vec
157 (for [ray current-rays]
158 (do
159 (let [results (CollisionResults.)]
160 (.collideWith node ray results)
161 (let [touch-objects
162 (filter #(not (= geo (.getGeometry %)))
163 results)]
164 [(if (empty? touch-objects)
165 (.getLimit ray)
166 (.getDistance (first touch-objects)))
167 (.getLimit ray)])))))))))))
169 (defn touch-kernel*
170 "Returns a function which returns tactile sensory data when called
171 inside a running simulation."
172 [#^Geometry geo]
173 (let [feeler-coords (feeler-coordinates geo)
174 tris (triangles geo)
175 limit (tactile-scale geo)]
176 (if (empty? (touch-topology geo))
177 nil
178 (fn [node]
179 (let [sensor-origins
180 (map
181 #(map (partial local-to-world geo) %)
182 feeler-coords)
183 triangle-normals
184 (map (partial get-ray-direction geo)
185 tris)
186 rays
187 (flatten
188 (map (fn [origins norm]
189 (map #(doto (Ray. % norm)
190 (.setLimit limit)) origins))
191 sensor-origins triangle-normals))]
192 (vector
193 (touch-topology geo)
194 (vec
195 (for [ray rays]
196 (do
197 (let [results (CollisionResults.)]
198 (.collideWith node ray results)
199 (let [touch-objects
200 (filter #(not (= geo (.getGeometry %)))
201 results)]
202 [(if (empty? touch-objects)
203 limit (.getDistance (first touch-objects)))
204 limit])))))))))))
206 (defn touch!
207 "Endow the creature with the sense of touch. Returns a sequence of
208 functions, one for each body part with a tactile-sensor-proile,
209 each of which when called returns sensory data for that body part."
210 [#^Node creature]
211 (filter
212 (comp not nil?)
213 (map touch-kernel
214 (filter #(isa? (class %) Geometry)
215 (node-seq creature)))))
216 #+end_src
218 * Sensor Related Functions
220 These functions analyze the touch-sensor-profile image convert the
221 location of each touch sensor from pixel coordinates to UV-coordinates
222 and XYZ-coordinates.
224 #+name: sensors
225 #+begin_src clojure
226 (in-ns 'cortex.touch)
228 (defn feeler-pixel-coords
229 "Returns the coordinates of the feelers in pixel space in lists, one
230 list for each triangle, ordered in the same way as (triangles) and
231 (pixel-triangles)."
232 [#^Geometry geo image]
233 (map
234 (fn [pixel-triangle]
235 (filter
236 (fn [coord]
237 (inside-triangle? (->triangle pixel-triangle)
238 (->vector3f coord)))
239 (white-coordinates image (convex-bounds pixel-triangle))))
240 (pixel-triangles geo image)))
242 (defn feeler-origins [#^Geometry geo image]
243 (let [transforms
244 (map #(triangles->affine-transform
245 (->triangle %1) (->triangle %2))
246 (pixel-triangles geo image)
247 (triangles geo))]
248 (mapcat (fn [transform coords]
249 (map #(.mult transform (->vector3f %)) coords))
250 transforms (feeler-pixel-coords geo image))))
252 (defn feeler-tips [#^Geometry geo image]
253 (let [origins (feeler-origins geo image)
254 normals
255 (map
256 (fn [triangle]
257 (.calculateNormal triangle)
258 (.clone (.getNormal triangle)))
259 (map ->triangle (triangles geo)))]
260 (map #(.add %1 %2) origins normals)))
262 (defn touch-topology [#^Geometry geo image]
263 (collapse (feeler-pixel-coords geo image)))
266 (defn sensors-in-triangle
267 "Locate the touch sensors in the triangle, returning a map of their
268 UV and geometry-relative coordinates."
269 [image mesh tri-index]
270 (let [width (.getWidth image)
271 height (.getHeight image)
272 UV-vertex-coords (triangle-UV-coord mesh width height tri-index)
273 bounds (convex-bounds UV-vertex-coords)
275 cutout-triangle (points->triangle UV-vertex-coords)
276 UV-sensor-coords
277 (filter (comp (partial inside-triangle? cutout-triangle)
278 (fn [[u v]] (Vector3f. u v 0)))
279 (white-coordinates image bounds))
280 UV->geometry (triangle-transformation
281 cutout-triangle
282 (mesh-triangle mesh tri-index))
283 geometry-sensor-coords
284 (map (fn [[u v]] (.mult UV->geometry (Vector3f. u v 0)))
285 UV-sensor-coords)]
286 {:UV UV-sensor-coords :geometry geometry-sensor-coords}))
288 (defn-memo locate-feelers
289 "Search the geometry's tactile UV profile for touch sensors,
290 returning their positions in geometry-relative coordinates."
291 [#^Geometry geo]
292 (let [mesh (.getMesh geo)
293 num-triangles (.getTriangleCount mesh)]
294 (if-let [image (tactile-sensor-profile geo)]
295 (map
296 (partial sensors-in-triangle image mesh)
297 (range num-triangles))
298 (repeat (.getTriangleCount mesh) {:UV nil :geometry nil}))))
300 (defn-memo touch-topology
301 "Return a sequence of vectors of the form [x y] describing the
302 \"topology\" of the tactile sensors. Points that are close together
303 in the touch-topology are generally close together in the simulation."
304 [#^Gemoetry geo]
305 (vec (collapse (reduce concat (map :UV (locate-feelers geo))))))
307 (defn-memo feeler-coordinates
308 "The location of the touch sensors in world-space coordinates."
309 [#^Geometry geo]
310 (vec (map :geometry (locate-feelers geo))))
311 #+end_src
316 * Visualizing Touch
317 #+name: visualization
318 #+begin_src clojure
319 (in-ns 'cortex.touch)
321 (defn touch->gray
322 "Convert a pair of [distance, max-distance] into a grayscale pixel"
323 [distance max-distance]
324 (gray
325 (- 255
326 (rem
327 (int
328 (* 255 (/ distance max-distance)))
329 256))))
331 (defn view-touch
332 "Creates a function which accepts a list of touch sensor-data and
333 displays each element to the screen."
334 []
335 (view-sense
336 (fn
337 [[coords sensor-data]]
338 (let [image (points->image coords)]
339 (dorun
340 (for [i (range (count coords))]
341 (.setRGB image ((coords i) 0) ((coords i) 1)
342 (apply touch->gray (sensor-data i)))))
343 image))))
344 #+end_src
348 * Triangle Manipulation Functions
350 The rigid bodies which make up a creature have an underlying
351 =Geometry=, which is a =Mesh= plus a =Material= and other important
352 data involved with displaying the body.
354 A =Mesh= is composed of =Triangles=, and each =Triangle= has three
355 verticies which have coordinates in XYZ space and UV space.
357 Here, =(triangles)= gets all the triangles which compose a mesh, and
358 =(triangle-UV-coord)= returns the the UV coordinates of the verticies
359 of a triangle.
361 #+name: triangles-1
362 #+begin_src clojure
363 (in-ns 'cortex.touch)
365 (defn vector3f-seq [#^Vector3f v]
366 [(.getX v) (.getY v) (.getZ v)])
368 (defn triangle-seq [#^Triangle tri]
369 [(vector3f-seq (.get1 tri))
370 (vector3f-seq (.get2 tri))
371 (vector3f-seq (.get3 tri))])
373 (defn ->vector3f
374 ([coords] (Vector3f. (nth coords 0 0)
375 (nth coords 1 0)
376 (nth coords 2 0))))
378 (defn ->triangle [points]
379 (apply #(Triangle. %1 %2 %3) (map ->vector3f points)))
381 (defn triangle
382 "Get the triangle specified by triangle-index from the mesh within
383 bounds."
384 [#^Geometry geo triangle-index]
385 (triangle-seq
386 (let [scratch (Triangle.)]
387 (.getTriangle (.getMesh geo) triangle-index scratch) scratch)))
389 (defn triangles
390 "Return a sequence of all the Triangles which compose a given
391 Geometry."
392 [#^Geometry geo]
393 (map (partial triangle geo) (range (.getTriangleCount (.getMesh geo)))))
395 (defn triangle-vertex-indices
396 "Get the triangle vertex indices of a given triangle from a given
397 mesh."
398 [#^Mesh mesh triangle-index]
399 (let [indices (int-array 3)]
400 (.getTriangle mesh triangle-index indices)
401 (vec indices)))
403 (defn vertex-UV-coord
404 "Get the UV-coordinates of the vertex named by vertex-index"
405 [#^Mesh mesh vertex-index]
406 (let [UV-buffer
407 (.getData
408 (.getBuffer
409 mesh
410 VertexBuffer$Type/TexCoord))]
411 [(.get UV-buffer (* vertex-index 2))
412 (.get UV-buffer (+ 1 (* vertex-index 2)))]))
414 (defn pixel-triangle [#^Geometry geo image index]
415 (let [mesh (.getMesh geo)
416 width (.getWidth image)
417 height (.getHeight image)]
418 (vec (map (fn [[u v]] (vector (* width u) (* height v)))
419 (map (partial vertex-UV-coord mesh)
420 (triangle-vertex-indices mesh index))))))
422 (defn pixel-triangles [#^Geometry geo image]
423 (let [height (.getHeight image)
424 width (.getWidth image)]
425 (map (partial pixel-triangle geo image)
426 (range (.getTriangleCount (.getMesh geo))))))
428 #+end_src
430 * Triangle Affine Transforms
432 The position of each hair is stored in a 2D image in UV
433 coordinates. To place the hair in 3D space we must convert from UV
434 coordinates to XYZ coordinates. Each =Triangle= has coordinates in
435 both UV-space and XYZ-space, which defines a unique [[http://mathworld.wolfram.com/AffineTransformation.html ][Affine Transform]]
436 for translating any coordinate within the UV triangle to the
437 cooresponding coordinate in the XYZ triangle.
439 #+name: triangles-3
440 #+begin_src clojure
441 (defn triangle->matrix4f
442 "Converts the triangle into a 4x4 matrix: The first three columns
443 contain the vertices of the triangle; the last contains the unit
444 normal of the triangle. The bottom row is filled with 1s."
445 [#^Triangle t]
446 (let [mat (Matrix4f.)
447 [vert-1 vert-2 vert-3]
448 ((comp vec map) #(.get t %) (range 3))
449 unit-normal (do (.calculateNormal t)(.getNormal t))
450 vertices [vert-1 vert-2 vert-3 unit-normal]]
451 (dorun
452 (for [row (range 4) col (range 3)]
453 (do
454 (.set mat col row (.get (vertices row)col))
455 (.set mat 3 row 1))))
456 mat))
458 (defn triangles->affine-transform
459 "Returns the affine transformation that converts each vertex in the
460 first triangle into the corresponding vertex in the second
461 triangle."
462 [#^Triangle tri-1 #^Triangle tri-2]
463 (.mult
464 (triangle->matrix4f tri-2)
465 (.invert (triangle->matrix4f tri-1))))
466 #+end_src
469 * Schrapnel Conversion Functions
471 It is convienent to treat a =Triangle= as a sequence of verticies, and
472 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion
473 functions make this easy. If these classes implemented =Iterable= then
474 this code would not be necessary. Hopefully they will in the future.
476 #+name: triangles-2
477 #+begin_src clojure
478 (defn point->vector2f [[u v]]
479 (Vector2f. u v))
481 (defn vector2f->vector3f [v]
482 (Vector3f. (.getX v) (.getY v) 0))
484 (defn map-triangle [f #^Triangle tri]
485 (Triangle.
486 (f 0 (.get1 tri))
487 (f 1 (.get2 tri))
488 (f 2 (.get3 tri))))
490 (defn points->triangle
491 "Convert a list of points into a triangle."
492 [points]
493 (apply #(Triangle. %1 %2 %3)
494 (map (fn [point]
495 (let [point (vec point)]
496 (Vector3f. (get point 0 0)
497 (get point 1 0)
498 (get point 2 0))))
499 (take 3 points))))
500 #+end_src
503 * Triangle Boundaries
505 For efficiency's sake I will divide the UV-image into small squares
506 which inscribe each UV-triangle, then extract the points which lie
507 inside the triangle and map them to 3D-space using
508 =(triangle-transform)= above. To do this I need a function,
509 =(inside-triangle?)=, which determines whether a point is inside a
510 triangle in 2D UV-space.
512 #+name: triangles-4
513 #+begin_src clojure
514 (defn convex-bounds
515 "Returns the smallest square containing the given vertices, as a
516 vector of integers [left top width height]."
517 [verts]
518 (let [xs (map first verts)
519 ys (map second verts)
520 x0 (Math/floor (apply min xs))
521 y0 (Math/floor (apply min ys))
522 x1 (Math/ceil (apply max xs))
523 y1 (Math/ceil (apply max ys))]
524 [x0 y0 (- x1 x0) (- y1 y0)]))
526 (defn same-side?
527 "Given the points p1 and p2 and the reference point ref, is point p
528 on the same side of the line that goes through p1 and p2 as ref is?"
529 [p1 p2 ref p]
530 (<=
531 0
532 (.dot
533 (.cross (.subtract p2 p1) (.subtract p p1))
534 (.cross (.subtract p2 p1) (.subtract ref p1)))))
536 (defn inside-triangle?
537 "Is the point inside the triangle?"
538 {:author "Dylan Holmes"}
539 [#^Triangle tri #^Vector3f p]
540 (let [[vert-1 vert-2 vert-3] [(.get1 tri) (.get2 tri) (.get3 tri)]]
541 (and
542 (same-side? vert-1 vert-2 vert-3 p)
543 (same-side? vert-2 vert-3 vert-1 p)
544 (same-side? vert-3 vert-1 vert-2 p))))
545 #+end_src
547 #+results: triangles-4
548 : #'cortex.touch/inside-triangle?
551 * Physics Collision Objects
553 The "hairs" are actually =Rays= which extend from a point on a
554 =Triangle= in the =Mesh= normal to the =Triangle's= surface.
556 #+name: rays
557 #+begin_src clojure
558 (defn get-ray-origin
559 "Return the origin which a Ray would have to have to be in the exact
560 center of a particular Triangle in the Geometry in World
561 Coordinates."
562 [geom tri]
563 (let [new (Vector3f.)]
564 (.calculateCenter tri)
565 (.localToWorld geom (.getCenter tri) new) new))
567 (defn get-ray-direction
568 "Return the direction which a Ray would have to have to be to point
569 normal to the Triangle, in coordinates relative to the center of the
570 Triangle."
571 [geom tri]
572 (let [n+c (Vector3f.)]
573 (.calculateNormal tri)
574 (.calculateCenter tri)
575 (.localToWorld
576 geom
577 (.add (.getCenter tri) (.getNormal tri)) n+c)
578 (.subtract n+c (get-ray-origin geom tri))))
579 #+end_src
580 * Headers
582 #+name: touch-header
583 #+begin_src clojure
584 (ns cortex.touch
585 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry
586 to be outfitted with touch sensors with density determined by a UV
587 image. In this way a Geometry can know what parts of itself are
588 touching nearby objects. Reads specially prepared blender files to
589 construct this sense automatically."
590 {:author "Robert McIntyre"}
591 (:use (cortex world util sense))
592 (:use clojure.contrib.def)
593 (:import (com.jme3.scene Geometry Node Mesh))
594 (:import com.jme3.collision.CollisionResults)
595 (:import com.jme3.scene.VertexBuffer$Type)
596 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))
597 #+end_src
599 * Adding Touch to the Worm
601 #+name: test-touch
602 #+begin_src clojure
603 (ns cortex.test.touch
604 (:use (cortex world util sense body touch))
605 (:use cortex.test.body))
607 (cortex.import/mega-import-jme3)
609 (defn test-touch []
610 (let [the-worm (doto (worm) (body!))
611 touch (touch! the-worm)
612 touch-display (view-touch)]
613 (world (nodify [the-worm (floor)])
614 standard-debug-controls
616 (fn [world]
617 (light-up-everything world))
619 (fn [world tpf]
620 (touch-display (map #(% (.getRootNode world)) touch))))))
621 #+end_src
622 * Source Listing
623 * Next
626 * COMMENT Code Generation
627 #+begin_src clojure :tangle ../src/cortex/touch.clj
628 <<touch-header>>
629 <<meta-data>>
630 <<triangles-1>>
631 <<triangles-2>>
632 <<triangles-3>>
633 <<triangles-4>>
634 <<sensors>>
635 <<rays>>
636 <<kernel>>
637 <<visualization>>
638 #+end_src
641 #+begin_src clojure :tangle ../src/cortex/test/touch.clj
642 <<test-touch>>
643 #+end_src