view org/touch.org @ 233:f27c9fd9134d

seperated out image generating code from touch-kernel
author Robert McIntyre <rlm@mit.edu>
date Sun, 12 Feb 2012 06:21:30 -0700
parents b7762699eeb5
children 712bd7e5b148
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=.
55 #+name: meta-data
56 #+begin_src clojure
57 (defn tactile-sensor-profile
58 "Return the touch-sensor distribution image in BufferedImage format,
59 or nil if it does not exist."
60 [#^Geometry obj]
61 (if-let [image-path (meta-data obj "touch")]
62 (load-image image-path)))
64 (defn tactile-scale
65 "Return the maximum length of a hair. All hairs are scalled between
66 0.0 and this length, depending on their color. Black is 0, and
67 white is maximum length, and everything in between is scalled
68 linearlly. Default scale is 0.01 jMonkeyEngine units."
69 [#^Geometry obj]
70 (if-let [scale (meta-data obj "scale")]
71 scale 0.1))
72 #+end_src
74 ** TODO add image showing example touch-uv map
75 ** TODO add metadata display for worm
77 * Skin Creation
78 #+name: kernel
79 #+begin_src clojure
80 (in-ns 'cortex.touch)
82 (defn touch-kernel
83 "Returns a function which returns tactile sensory data when called
84 inside a running simulation."
85 [#^Geometry geo]
86 (let [feeler-coords (feeler-coordinates geo)
87 tris (triangles geo)
88 limit (tactile-scale geo)]
89 (if (empty? (touch-topology geo))
90 nil
91 (fn [node]
92 (let [sensor-origins
93 (map
94 #(map (partial local-to-world geo) %)
95 feeler-coords)
96 triangle-normals
97 (map (partial get-ray-direction geo)
98 tris)
99 rays
100 (flatten
101 (map (fn [origins norm]
102 (map #(doto (Ray. % norm)
103 (.setLimit limit)) origins))
104 sensor-origins triangle-normals))]
105 (vector
106 (touch-topology geo)
107 (vec
108 (for [ray rays]
109 (do
110 (let [results (CollisionResults.)]
111 (.collideWith node ray results)
112 (let [touch-objects
113 (filter #(not (= geo (.getGeometry %)))
114 results)]
115 [(if (empty? touch-objects)
116 limit (.getDistance (first touch-objects)))
117 limit])))))))))))
119 (defn touch!
120 "Endow the creature with the sense of touch. Returns a sequence of
121 functions, one for each body part with a tactile-sensor-proile,
122 each of which when called returns sensory data for that body part."
123 [#^Node creature]
124 (filter
125 (comp not nil?)
126 (map touch-kernel
127 (filter #(isa? (class %) Geometry)
128 (node-seq creature)))))
129 #+end_src
131 * Visualizing Touch
132 #+name: visualization
133 #+begin_src clojure
134 (in-ns 'cortex.touch)
136 (defn touch->gray
137 "Convert a pair of [distance, max-distance] into a grayscale pixel"
138 [distance max-distance]
139 (gray
140 (- 255
141 (rem
142 (int
143 (* 255 (/ distance max-distance)))
144 256))))
146 (defn view-touch
147 "Creates a function which accepts a list of touch sensor-data and
148 displays each element to the screen."
149 []
150 (view-sense
151 (fn
152 [[coords sensor-data]]
153 (let [image (points->image coords)]
154 (dorun
155 (for [i (range (count coords))]
156 (.setRGB image ((coords i) 0) ((coords i) 1)
157 (apply touch->gray (sensor-data i)))))
158 image))))
159 #+end_src
163 * Triangle Manipulation Functions
165 The rigid bodies which make up a creature have an underlying
166 =Geometry=, which is a =Mesh= plus a =Material= and other important
167 data involved with displaying the body.
169 A =Mesh= is composed of =Triangles=, and each =Triangle= has three
170 verticies which have coordinates in XYZ space and UV space.
172 Here, =(triangles)= gets all the triangles which compose a mesh, and
173 =(triangle-UV-coord)= returns the the UV coordinates of the verticies
174 of a triangle.
176 #+name: triangles-1
177 #+begin_src clojure
178 (defn triangles
179 "Return a sequence of all the Triangles which compose a given
180 Geometry."
181 [#^Geometry geom]
182 (let
183 [mesh (.getMesh geom)
184 triangles (transient [])]
185 (dorun
186 (for [n (range (.getTriangleCount mesh))]
187 (let [tri (Triangle.)]
188 (.getTriangle mesh n tri)
189 ;; (.calculateNormal tri)
190 ;; (.calculateCenter tri)
191 (conj! triangles tri))))
192 (persistent! triangles)))
194 (defn mesh-triangle
195 "Get the triangle specified by triangle-index from the mesh within
196 bounds."
197 [#^Mesh mesh triangle-index]
198 (let [scratch (Triangle.)]
199 (.getTriangle mesh triangle-index scratch)
200 scratch))
202 (defn triangle-vertex-indices
203 "Get the triangle vertex indices of a given triangle from a given
204 mesh."
205 [#^Mesh mesh triangle-index]
206 (let [indices (int-array 3)]
207 (.getTriangle mesh triangle-index indices)
208 (vec indices)))
210 (defn vertex-UV-coord
211 "Get the UV-coordinates of the vertex named by vertex-index"
212 [#^Mesh mesh vertex-index]
213 (let [UV-buffer
214 (.getData
215 (.getBuffer
216 mesh
217 VertexBuffer$Type/TexCoord))]
218 [(.get UV-buffer (* vertex-index 2))
219 (.get UV-buffer (+ 1 (* vertex-index 2)))]))
221 (defn triangle-UV-coord
222 "Get the UV-cooridnates of the triangle's verticies."
223 [#^Mesh mesh width height triangle-index]
224 (map (fn [[u v]] (vector (* width u) (* height v)))
225 (map (partial vertex-UV-coord mesh)
226 (triangle-vertex-indices mesh triangle-index))))
227 #+end_src
229 * Schrapnel Conversion Functions
231 It is convienent to treat a =Triangle= as a sequence of verticies, and
232 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion
233 functions make this easy. If these classes implemented =Iterable= then
234 this code would not be necessary. Hopefully they will in the future.
236 #+name: triangles-2
237 #+begin_src clojure
238 (defn triangle-seq [#^Triangle tri]
239 [(.get1 tri) (.get2 tri) (.get3 tri)])
241 (defn vector3f-seq [#^Vector3f v]
242 [(.getX v) (.getY v) (.getZ v)])
244 (defn point->vector2f [[u v]]
245 (Vector2f. u v))
247 (defn vector2f->vector3f [v]
248 (Vector3f. (.getX v) (.getY v) 0))
250 (defn map-triangle [f #^Triangle tri]
251 (Triangle.
252 (f 0 (.get1 tri))
253 (f 1 (.get2 tri))
254 (f 2 (.get3 tri))))
256 (defn points->triangle
257 "Convert a list of points into a triangle."
258 [points]
259 (apply #(Triangle. %1 %2 %3)
260 (map (fn [point]
261 (let [point (vec point)]
262 (Vector3f. (get point 0 0)
263 (get point 1 0)
264 (get point 2 0))))
265 (take 3 points))))
266 #+end_src
268 * Triangle Affine Transforms
270 The position of each hair is stored in a 2D image in UV
271 coordinates. To place the hair in 3D space we must convert from UV
272 coordinates to XYZ coordinates. Each =Triangle= has coordinates in
273 both UV-space and XYZ-space, which defines a unique [[http://mathworld.wolfram.com/AffineTransformation.html ][Affine Transform]]
274 for translating any coordinate within the UV triangle to the
275 cooresponding coordinate in the XYZ triangle.
277 #+name: triangles-3
278 #+begin_src clojure
279 (defn triangle->matrix4f
280 "Converts the triangle into a 4x4 matrix: The first three columns
281 contain the vertices of the triangle; the last contains the unit
282 normal of the triangle. The bottom row is filled with 1s."
283 [#^Triangle t]
284 (let [mat (Matrix4f.)
285 [vert-1 vert-2 vert-3]
286 ((comp vec map) #(.get t %) (range 3))
287 unit-normal (do (.calculateNormal t)(.getNormal t))
288 vertices [vert-1 vert-2 vert-3 unit-normal]]
289 (dorun
290 (for [row (range 4) col (range 3)]
291 (do
292 (.set mat col row (.get (vertices row)col))
293 (.set mat 3 row 1))))
294 mat))
296 (defn triangle-transformation
297 "Returns the affine transformation that converts each vertex in the
298 first triangle into the corresponding vertex in the second
299 triangle."
300 [#^Triangle tri-1 #^Triangle tri-2]
301 (.mult
302 (triangle->matrix4f tri-2)
303 (.invert (triangle->matrix4f tri-1))))
304 #+end_src
306 * Triangle Boundaries
308 For efficiency's sake I will divide the UV-image into small squares
309 which inscribe each UV-triangle, then extract the points which lie
310 inside the triangle and map them to 3D-space using
311 =(triangle-transform)= above. To do this I need a function,
312 =(inside-triangle?)=, which determines whether a point is inside a
313 triangle in 2D UV-space.
315 #+name: triangles-4
316 #+begin_src clojure
317 (defn convex-bounds
318 "Returns the smallest square containing the given vertices, as a
319 vector of integers [left top width height]."
320 [uv-verts]
321 (let [xs (map first uv-verts)
322 ys (map second uv-verts)
323 x0 (Math/floor (apply min xs))
324 y0 (Math/floor (apply min ys))
325 x1 (Math/ceil (apply max xs))
326 y1 (Math/ceil (apply max ys))]
327 [x0 y0 (- x1 x0) (- y1 y0)]))
329 (defn same-side?
330 "Given the points p1 and p2 and the reference point ref, is point p
331 on the same side of the line that goes through p1 and p2 as ref is?"
332 [p1 p2 ref p]
333 (<=
334 0
335 (.dot
336 (.cross (.subtract p2 p1) (.subtract p p1))
337 (.cross (.subtract p2 p1) (.subtract ref p1)))))
339 (defn inside-triangle?
340 "Is the point inside the triangle?"
341 {:author "Dylan Holmes"}
342 [#^Triangle tri #^Vector3f p]
343 (let [[vert-1 vert-2 vert-3] (triangle-seq tri)]
344 (and
345 (same-side? vert-1 vert-2 vert-3 p)
346 (same-side? vert-2 vert-3 vert-1 p)
347 (same-side? vert-3 vert-1 vert-2 p))))
348 #+end_src
352 * Sensor Related Functions
354 These functions analyze the touch-sensor-profile image convert the
355 location of each touch sensor from pixel coordinates to UV-coordinates
356 and XYZ-coordinates.
358 #+name: sensors
359 #+begin_src clojure
360 (defn sensors-in-triangle
361 "Locate the touch sensors in the triangle, returning a map of their
362 UV and geometry-relative coordinates."
363 [image mesh tri-index]
364 (let [width (.getWidth image)
365 height (.getHeight image)
366 UV-vertex-coords (triangle-UV-coord mesh width height tri-index)
367 bounds (convex-bounds UV-vertex-coords)
369 cutout-triangle (points->triangle UV-vertex-coords)
370 UV-sensor-coords
371 (filter (comp (partial inside-triangle? cutout-triangle)
372 (fn [[u v]] (Vector3f. u v 0)))
373 (white-coordinates image bounds))
374 UV->geometry (triangle-transformation
375 cutout-triangle
376 (mesh-triangle mesh tri-index))
377 geometry-sensor-coords
378 (map (fn [[u v]] (.mult UV->geometry (Vector3f. u v 0)))
379 UV-sensor-coords)]
380 {:UV UV-sensor-coords :geometry geometry-sensor-coords}))
382 (defn-memo locate-feelers
383 "Search the geometry's tactile UV profile for touch sensors,
384 returning their positions in geometry-relative coordinates."
385 [#^Geometry geo]
386 (let [mesh (.getMesh geo)
387 num-triangles (.getTriangleCount mesh)]
388 (if-let [image (tactile-sensor-profile geo)]
389 (map
390 (partial sensors-in-triangle image mesh)
391 (range num-triangles))
392 (repeat (.getTriangleCount mesh) {:UV nil :geometry nil}))))
394 (defn-memo touch-topology
395 "Return a sequence of vectors of the form [x y] describing the
396 \"topology\" of the tactile sensors. Points that are close together
397 in the touch-topology are generally close together in the simulation."
398 [#^Gemoetry geo]
399 (vec (collapse (reduce concat (map :UV (locate-feelers geo))))))
401 (defn-memo feeler-coordinates
402 "The location of the touch sensors in world-space coordinates."
403 [#^Geometry geo]
404 (vec (map :geometry (locate-feelers geo))))
405 #+end_src
407 * Physics Collision Objects
409 The "hairs" are actually rays which extend from a point on a
410 =Triangle= in the =Mesh= normal to the =Triangle's= surface.
412 #+name: rays
413 #+begin_src clojure
414 (defn get-ray-origin
415 "Return the origin which a Ray would have to have to be in the exact
416 center of a particular Triangle in the Geometry in World
417 Coordinates."
418 [geom tri]
419 (let [new (Vector3f.)]
420 (.calculateCenter tri)
421 (.localToWorld geom (.getCenter tri) new) new))
423 (defn get-ray-direction
424 "Return the direction which a Ray would have to have to be to point
425 normal to the Triangle, in coordinates relative to the center of the
426 Triangle."
427 [geom tri]
428 (let [n+c (Vector3f.)]
429 (.calculateNormal tri)
430 (.calculateCenter tri)
431 (.localToWorld
432 geom
433 (.add (.getCenter tri) (.getNormal tri)) n+c)
434 (.subtract n+c (get-ray-origin geom tri))))
435 #+end_src
439 * Headers
441 #+name: touch-header
442 #+begin_src clojure
443 (ns cortex.touch
444 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry
445 to be outfitted with touch sensors with density determined by a UV
446 image. In this way a Geometry can know what parts of itself are
447 touching nearby objects. Reads specially prepared blender files to
448 construct this sense automatically."
449 {:author "Robert McIntyre"}
450 (:use (cortex world util sense))
451 (:use clojure.contrib.def)
452 (:import (com.jme3.scene Geometry Node Mesh))
453 (:import com.jme3.collision.CollisionResults)
454 (:import com.jme3.scene.VertexBuffer$Type)
455 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))
456 #+end_src
458 * Adding Touch to the Worm
460 #+name: test-touch
461 #+begin_src clojure
462 (ns cortex.test.touch
463 (:use (cortex world util sense body touch))
464 (:use cortex.test.body))
466 (cortex.import/mega-import-jme3)
468 (defn test-touch []
469 (let [the-worm (doto (worm) (body!))
470 touch (touch! the-worm)
471 touch-display (view-touch)]
472 (world (nodify [the-worm (floor)])
473 standard-debug-controls
475 (fn [world]
476 (light-up-everything world))
478 (fn [world tpf]
479 (touch-display (map #(% (.getRootNode world)) touch))))))
480 #+end_src
482 * Source Listing
483 * Next
486 * COMMENT Code Generation
487 #+begin_src clojure :tangle ../src/cortex/touch.clj
488 <<touch-header>>
489 <<meta-data>>
490 <<triangles-1>>
491 <<triangles-2>>
492 <<triangles-3>>
493 <<triangles-4>>
494 <<sensors>>
495 <<rays>>
496 <<kernel>>
497 <<visualization>>
498 #+end_src
501 #+begin_src clojure :tangle ../src/cortex/test/touch.clj
502 <<test-touch>>
503 #+end_src