view org/touch.org @ 246:63da037ce1c5

added image
author Robert McIntyre <rlm@mit.edu>
date Sun, 12 Feb 2012 14:40:58 -0700
parents 102ac596cc3f
children 4e220c8fb1ed
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 which do not interact with
27 the physical world. Physical objects can pass through them with no
28 effect. The hairs are able to measure contact with other objects, and
29 constantly report how much of their extent is covered. So, even though
30 the creature's body parts do not deform, the hairs create a margin
31 around those body parts which achieves a sense of touch which is a
32 hybrid between a human's sense of deformation and sense from hairs.
34 Implementing touch in jMonkeyEngine follows a different techinal route
35 than vision and hearing. Those two senses piggybacked off
36 jMonkeyEngine's 3D audio and video rendering subsystems. To simulate
37 Touch, I use jMonkeyEngine's physics system to execute many small
38 collision detections, one for each "hair". The placement of the
39 "hairs" is determined by a UV-mapped image which shows where each hair
40 should be on the 3D surface of the body.
42 * Defining Touch Meta-Data in Blender
44 Each geometry can have a single UV map which describes the position of
45 the "hairs" which will constitute its sense of touch. This image path
46 is stored under the "touch" key. The image itself is black and white,
47 with black meaning a hair length of 0 (no hair is present) and white
48 meaning a hair length of =scale=, which is a float stored under the
49 key "scale". I call these "hairs" /feelers/.
51 #+name: meta-data
52 #+begin_src clojure
53 (defn tactile-sensor-profile
54 "Return the touch-sensor distribution image in BufferedImage format,
55 or nil if it does not exist."
56 [#^Geometry obj]
57 (if-let [image-path (meta-data obj "touch")]
58 (load-image image-path)))
60 (defn tactile-scale
61 "Return the maximum length of a hair. All hairs are scalled between
62 0.0 and this length, depending on their color. Black is 0, and
63 white is maximum length, and everything in between is scalled
64 linearlly. Default scale is 0.01 jMonkeyEngine units."
65 [#^Geometry obj]
66 (if-let [scale (meta-data obj "scale")]
67 scale 0.1))
68 #+end_src
70 Here is an example of a UV-map which specifies the position of touch
71 sensors along the surface of the worm.
73 #+attr_html: width=755
74 #+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).
75 [[../images/finger-UV.png]]
77 * Skin Creation
79 =(touch-kernel)= generates the functions which implement the sense of
80 touch for a creature. These functions must do 6 things to obtain touch
81 data.
83 - Get the tactile profile image and scale paramaters which describe
84 the layout of feelers along the object's surface.
85 =(tactile-sensor-profile)=, =(tactile-scale)=
87 - Find the triangles which make up the mesh in pixel-space and in
88 world-space.
89 =(triangles)= =(pixel-triangles)=
91 - Find the coordinates of each pixel in pixel space. These
92 coordinates are used to make the touch-topology.
93 =(feeler-pixel-coords)=
95 - Find the coordinates of each pixel in world-space. These
96 coordinates are the 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.
101 For both of these, =(feeler-tips)=
103 - Generate some sort of topology for the sensors.
104 =(touch-topology)=
107 #+name: kernel
108 #+begin_src clojure
109 (in-ns 'cortex.touch)
111 (defn set-ray [#^Ray ray #^Matrix4f transform
112 #^Vector3f origin #^Vector3f tip]
113 ;; Doing everything locally recduces garbage collection by enough to
114 ;; be worth it.
115 (.mult transform origin (.getOrigin ray))
117 (.mult transform tip (.getDirection ray))
118 (.subtractLocal (.getDirection ray) (.getOrigin ray)))
120 (defn touch-kernel
121 "Constructs a function which will return tactile sensory data from
122 'geo when called from inside a running simulation"
123 [#^Geometry geo]
124 (if-let
125 [profile (tactile-sensor-profile geo)]
126 (let [ray-reference-origins (feeler-origins geo profile)
127 ray-reference-tips (feeler-tips geo profile)
128 ray-length (tactile-scale geo)
129 current-rays (map (fn [_] (Ray.)) ray-reference-origins)
130 topology (touch-topology geo profile)]
131 (dorun (map #(.setLimit % ray-length) current-rays))
132 (fn [node]
133 (let [transform (.getWorldMatrix geo)]
134 (dorun
135 (map (fn [ray ref-origin ref-tip]
136 (set-ray ray transform ref-origin ref-tip))
137 current-rays ray-reference-origins
138 ray-reference-tips))
139 (vector
140 topology
141 (vec
142 (for [ray current-rays]
143 (do
144 (let [results (CollisionResults.)]
145 (.collideWith node ray results)
146 (let [touch-objects
147 (filter #(not (= geo (.getGeometry %)))
148 results)]
149 [(if (empty? touch-objects)
150 (.getLimit ray)
151 (.getDistance (first touch-objects)))
152 (.getLimit ray)])))))))))))
154 (defn touch!
155 "Endow the creature with the sense of touch. Returns a sequence of
156 functions, one for each body part with a tactile-sensor-proile,
157 each of which when called returns sensory data for that body part."
158 [#^Node creature]
159 (filter
160 (comp not nil?)
161 (map touch-kernel
162 (filter #(isa? (class %) Geometry)
163 (node-seq creature)))))
164 #+end_src
166 * Sensor Related Functions
168 These functions analyze the touch-sensor-profile image convert the
169 location of each touch sensor from pixel coordinates to UV-coordinates
170 and XYZ-coordinates.
172 #+name: sensors
173 #+begin_src clojure
174 (in-ns 'cortex.touch)
176 (defn feeler-pixel-coords
177 "Returns the coordinates of the feelers in pixel space in lists, one
178 list for each triangle, ordered in the same way as (triangles) and
179 (pixel-triangles)."
180 [#^Geometry geo image]
181 (map
182 (fn [pixel-triangle]
183 (filter
184 (fn [coord]
185 (inside-triangle? (->triangle pixel-triangle)
186 (->vector3f coord)))
187 (white-coordinates image (convex-bounds pixel-triangle))))
188 (pixel-triangles geo image)))
190 (defn feeler-world-coords [#^Geometry geo image]
191 (let [transforms
192 (map #(triangles->affine-transform
193 (->triangle %1) (->triangle %2))
194 (pixel-triangles geo image)
195 (triangles geo))]
196 (map (fn [transform coords]
197 (map #(.mult transform (->vector3f %)) coords))
198 transforms (feeler-pixel-coords geo image))))
200 (defn feeler-origins [#^Geometry geo image]
201 (reduce concat (feeler-world-coords geo image)))
203 (defn feeler-tips [#^Geometry geo image]
204 (let [world-coords (feeler-world-coords geo image)
205 normals
206 (map
207 (fn [triangle]
208 (.calculateNormal triangle)
209 (.clone (.getNormal triangle)))
210 (map ->triangle (triangles geo)))]
212 (mapcat (fn [origins normal]
213 (map #(.add % normal) origins))
214 world-coords normals)))
216 (defn touch-topology [#^Geometry geo image]
217 (collapse (reduce concat (feeler-pixel-coords geo image))))
218 #+end_src
220 * Visualizing Touch
221 #+name: visualization
222 #+begin_src clojure
223 (in-ns 'cortex.touch)
225 (defn touch->gray
226 "Convert a pair of [distance, max-distance] into a grayscale pixel."
227 [distance max-distance]
228 (gray (- 255 (rem (int (* 255 (/ distance max-distance))) 256))))
230 (defn view-touch
231 "Creates a function which accepts a list of touch sensor-data and
232 displays each element to the screen."
233 []
234 (view-sense
235 (fn [[coords sensor-data]]
236 (let [image (points->image coords)]
237 (dorun
238 (for [i (range (count coords))]
239 (.setRGB image ((coords i) 0) ((coords i) 1)
240 (apply touch->gray (sensor-data i))))) image))))
241 #+end_src
245 * Triangle Manipulation Functions
247 The rigid bodies which make up a creature have an underlying
248 =Geometry=, which is a =Mesh= plus a =Material= and other important
249 data involved with displaying the body.
251 A =Mesh= is composed of =Triangles=, and each =Triangle= has three
252 verticies which have coordinates in XYZ space and UV space.
254 Here, =(triangles)= gets all the triangles which compose a mesh, and
255 =(triangle-UV-coord)= returns the the UV coordinates of the verticies
256 of a triangle.
258 #+name: triangles-1
259 #+begin_src clojure
260 (in-ns 'cortex.touch)
262 (defn vector3f-seq [#^Vector3f v]
263 [(.getX v) (.getY v) (.getZ v)])
265 (defn triangle-seq [#^Triangle tri]
266 [(vector3f-seq (.get1 tri))
267 (vector3f-seq (.get2 tri))
268 (vector3f-seq (.get3 tri))])
270 (defn ->vector3f
271 ([coords] (Vector3f. (nth coords 0 0)
272 (nth coords 1 0)
273 (nth coords 2 0))))
275 (defn ->triangle [points]
276 (apply #(Triangle. %1 %2 %3) (map ->vector3f points)))
278 (defn triangle
279 "Get the triangle specified by triangle-index from the mesh."
280 [#^Geometry geo triangle-index]
281 (triangle-seq
282 (let [scratch (Triangle.)]
283 (.getTriangle (.getMesh geo) triangle-index scratch) scratch)))
285 (defn triangles
286 "Return a sequence of all the Triangles which compose a given
287 Geometry."
288 [#^Geometry geo]
289 (map (partial triangle geo) (range (.getTriangleCount (.getMesh geo)))))
291 (defn triangle-vertex-indices
292 "Get the triangle vertex indices of a given triangle from a given
293 mesh."
294 [#^Mesh mesh triangle-index]
295 (let [indices (int-array 3)]
296 (.getTriangle mesh triangle-index indices)
297 (vec indices)))
299 (defn vertex-UV-coord
300 "Get the UV-coordinates of the vertex named by vertex-index"
301 [#^Mesh mesh vertex-index]
302 (let [UV-buffer
303 (.getData
304 (.getBuffer
305 mesh
306 VertexBuffer$Type/TexCoord))]
307 [(.get UV-buffer (* vertex-index 2))
308 (.get UV-buffer (+ 1 (* vertex-index 2)))]))
310 (defn pixel-triangle [#^Geometry geo image index]
311 (let [mesh (.getMesh geo)
312 width (.getWidth image)
313 height (.getHeight image)]
314 (vec (map (fn [[u v]] (vector (* width u) (* height v)))
315 (map (partial vertex-UV-coord mesh)
316 (triangle-vertex-indices mesh index))))))
318 (defn pixel-triangles [#^Geometry geo image]
319 (let [height (.getHeight image)
320 width (.getWidth image)]
321 (map (partial pixel-triangle geo image)
322 (range (.getTriangleCount (.getMesh geo))))))
324 #+end_src
326 * Triangle Affine Transforms
328 The position of each hair is stored in a 2D image in UV
329 coordinates. To place the hair in 3D space we must convert from UV
330 coordinates to XYZ coordinates. Each =Triangle= has coordinates in
331 both UV-space and XYZ-space, which defines a unique [[http://mathworld.wolfram.com/AffineTransformation.html ][Affine Transform]]
332 for translating any coordinate within the UV triangle to the
333 cooresponding coordinate in the XYZ triangle.
335 #+name: triangles-3
336 #+begin_src clojure
337 (in-ns 'cortex.touch)
339 (defn triangle->matrix4f
340 "Converts the triangle into a 4x4 matrix: The first three columns
341 contain the vertices of the triangle; the last contains the unit
342 normal of the triangle. The bottom row is filled with 1s."
343 [#^Triangle t]
344 (let [mat (Matrix4f.)
345 [vert-1 vert-2 vert-3]
346 ((comp vec map) #(.get t %) (range 3))
347 unit-normal (do (.calculateNormal t)(.getNormal t))
348 vertices [vert-1 vert-2 vert-3 unit-normal]]
349 (dorun
350 (for [row (range 4) col (range 3)]
351 (do
352 (.set mat col row (.get (vertices row)col))
353 (.set mat 3 row 1)))) mat))
355 (defn triangles->affine-transform
356 "Returns the affine transformation that converts each vertex in the
357 first triangle into the corresponding vertex in the second
358 triangle."
359 [#^Triangle tri-1 #^Triangle tri-2]
360 (.mult
361 (triangle->matrix4f tri-2)
362 (.invert (triangle->matrix4f tri-1))))
363 #+end_src
366 * Schrapnel Conversion Functions
368 It is convienent to treat a =Triangle= as a sequence of verticies, and
369 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion
370 functions make this easy. If these classes implemented =Iterable= then
371 this code would not be necessary. Hopefully they will in the future.
373 * Triangle Boundaries
375 For efficiency's sake I will divide the UV-image into small squares
376 which inscribe each UV-triangle, then extract the points which lie
377 inside the triangle and map them to 3D-space using
378 =(triangle-transform)= above. To do this I need a function,
379 =(inside-triangle?)=, which determines whether a point is inside a
380 triangle in 2D UV-space.
382 #+name: triangles-4
383 #+begin_src clojure
384 (defn convex-bounds
385 "Returns the smallest square containing the given vertices, as a
386 vector of integers [left top width height]."
387 [verts]
388 (let [xs (map first verts)
389 ys (map second verts)
390 x0 (Math/floor (apply min xs))
391 y0 (Math/floor (apply min ys))
392 x1 (Math/ceil (apply max xs))
393 y1 (Math/ceil (apply max ys))]
394 [x0 y0 (- x1 x0) (- y1 y0)]))
396 (defn same-side?
397 "Given the points p1 and p2 and the reference point ref, is point p
398 on the same side of the line that goes through p1 and p2 as ref is?"
399 [p1 p2 ref p]
400 (<=
401 0
402 (.dot
403 (.cross (.subtract p2 p1) (.subtract p p1))
404 (.cross (.subtract p2 p1) (.subtract ref p1)))))
406 (defn inside-triangle?
407 "Is the point inside the triangle?"
408 {:author "Dylan Holmes"}
409 [#^Triangle tri #^Vector3f p]
410 (let [[vert-1 vert-2 vert-3] [(.get1 tri) (.get2 tri) (.get3 tri)]]
411 (and
412 (same-side? vert-1 vert-2 vert-3 p)
413 (same-side? vert-2 vert-3 vert-1 p)
414 (same-side? vert-3 vert-1 vert-2 p))))
415 #+end_src
417 * Physics Collision Objects
419 The "hairs" are actually =Rays= which extend from a point on a
420 =Triangle= in the =Mesh= normal to the =Triangle's= surface.
422 * Headers
424 #+name: touch-header
425 #+begin_src clojure
426 (ns cortex.touch
427 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry
428 to be outfitted with touch sensors with density determined by a UV
429 image. In this way a Geometry can know what parts of itself are
430 touching nearby objects. Reads specially prepared blender files to
431 construct this sense automatically."
432 {:author "Robert McIntyre"}
433 (:use (cortex world util sense))
434 (:use clojure.contrib.def)
435 (:import (com.jme3.scene Geometry Node Mesh))
436 (:import com.jme3.collision.CollisionResults)
437 (:import com.jme3.scene.VertexBuffer$Type)
438 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))
439 #+end_src
441 * Adding Touch to the Worm
443 #+name: test-touch
444 #+begin_src clojure
445 (ns cortex.test.touch
446 (:use (cortex world util sense body touch))
447 (:use cortex.test.body))
449 (cortex.import/mega-import-jme3)
451 (defn test-touch []
452 (let [the-worm (doto (worm) (body!))
453 touch (touch! the-worm)
454 touch-display (view-touch)]
455 (world (nodify [the-worm (floor)])
456 standard-debug-controls
458 (fn [world]
459 (speed-up world)
460 (light-up-everything world))
462 (fn [world tpf]
463 (touch-display
464 (map #(% (.getRootNode world)) touch))))))
465 #+end_src
466 * Source Listing
467 * Next
470 * COMMENT Code Generation
471 #+begin_src clojure :tangle ../src/cortex/touch.clj
472 <<touch-header>>
473 <<meta-data>>
474 <<triangles-1>>
475 <<triangles-3>>
476 <<triangles-4>>
477 <<sensors>>
478 <<kernel>>
479 <<visualization>>
480 #+end_src
483 #+begin_src clojure :tangle ../src/cortex/test/touch.clj
484 <<test-touch>>
485 #+end_src