view org/touch.org @ 244:f23217324f72

changed semantics of feeler lengths
author Robert McIntyre <rlm@mit.edu>
date Sun, 12 Feb 2012 14:29:09 -0700
parents f33fec68f775
children 102ac596cc3f
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.
43 * Defining Touch Meta-Data in Blender
45 Each geometry can have a single UV map which describes the position
46 and length of the "hairs" which will constitute its sense of
47 touch. This image path is stored under the "touch" key. The image
48 itself is grayscale, with black meaning a hair length of 0 (no hair is
49 present) and white meaning a hair length of =scale=, which is a float
50 stored under the key "scale". If the pixel is gray then the resultant
51 hair length is linearly interpolated between 0 and =scale=. I call
52 these "hairs" /feelers/.
54 #+name: meta-data
55 #+begin_src clojure
56 (defn tactile-sensor-profile
57 "Return the touch-sensor distribution image in BufferedImage format,
58 or nil if it does not exist."
59 [#^Geometry obj]
60 (if-let [image-path (meta-data obj "touch")]
61 (load-image image-path)))
63 (defn tactile-scale
64 "Return the maximum length of a hair. All hairs are scalled between
65 0.0 and this length, depending on their color. Black is 0, and
66 white is maximum length, and everything in between is scalled
67 linearlly. Default scale is 0.01 jMonkeyEngine units."
68 [#^Geometry obj]
69 (if-let [scale (meta-data obj "scale")]
70 scale 0.1))
71 #+end_src
73 ** TODO add image showing example touch-uv map
74 ** TODO add metadata display for worm
77 * Skin Creation
78 * TODO get the actual lengths for each feeler
81 =(touch-kernel)= generates the functions which implement the sense of
82 touch for a creature. These functions must do 6 things to obtain touch
83 data.
85 - Get the tactile profile image and scale paramaters which describe
86 the layout of feelers along the object's surface.
87 =(tactile-sensor-profile)=, =(tactile-scale)=
89 - Get the lengths of each feeler by analyzing the color of the
90 pixels in the tactile profile image.
91 NOT IMPLEMENTED YET
93 - Find the triangles which make up the mesh in pixel-space and in
94 world-space.
95 =(triangles)= =(pixel-triangles)=
97 - Find the coordinates of each pixel in pixel space. These
98 coordinates are used to make the touch-topology.
99 =(feeler-pixel-coords)=
101 - Find the coordinates of each pixel in world-space. These
102 coordinates are the origins of the feelers. =(feeler-origins)=
104 - Calculate the normals of the triangles in world space, and add
105 them to each of the origins of the feelers. These are the
106 normalized coordinates of the tips of the feelers.
107 For both of these, =(feeler-tips)=
109 - Generate some sort of topology for the sensors.
110 =(touch-topology)=
113 #+name: kernel
114 #+begin_src clojure
115 (in-ns 'cortex.touch)
117 (declare touch-topology feelers set-ray)
119 (defn set-ray [#^Ray ray #^Matrix4f transform
120 #^Vector3f origin #^Vector3f tip]
121 ;; Doing everything locally recduces garbage collection by enough to
122 ;; be worth it.
123 (.mult transform origin (.getOrigin ray))
125 (.mult transform tip (.getDirection ray))
126 (.subtractLocal (.getDirection ray) (.getOrigin ray)))
128 (defn touch-kernel
129 "Constructs a function which will return tactile sensory data from
130 'geo when called from inside a running simulation"
131 [#^Geometry geo]
132 (if-let
133 [profile (tactile-sensor-profile geo)]
134 (let [ray-reference-origins (feeler-origins geo profile)
135 ray-reference-tips (feeler-tips geo profile)
136 ray-length (tactile-scale geo)
137 current-rays (map (fn [_] (Ray.)) ray-reference-origins)
138 topology (touch-topology geo profile)]
139 (dorun (map #(.setLimit % ray-length) current-rays))
140 (fn [node]
141 (let [transform (.getWorldMatrix geo)]
142 (dorun
143 (map (fn [ray ref-origin ref-tip]
144 (set-ray ray transform ref-origin ref-tip))
145 current-rays ray-reference-origins
146 ray-reference-tips))
147 (vector
148 topology
149 (vec
150 (for [ray current-rays]
151 (do
152 (let [results (CollisionResults.)]
153 (.collideWith node ray results)
154 (let [touch-objects
155 (filter #(not (= geo (.getGeometry %)))
156 results)]
157 [(if (empty? touch-objects)
158 (.getLimit ray)
159 (.getDistance (first touch-objects)))
160 (.getLimit ray)])))))))))))
162 (defn touch!
163 "Endow the creature with the sense of touch. Returns a sequence of
164 functions, one for each body part with a tactile-sensor-proile,
165 each of which when called returns sensory data for that body part."
166 [#^Node creature]
167 (filter
168 (comp not nil?)
169 (map touch-kernel
170 (filter #(isa? (class %) Geometry)
171 (node-seq creature)))))
172 #+end_src
174 #+results: kernel
175 : #'cortex.touch/touch!
177 * Sensor Related Functions
179 These functions analyze the touch-sensor-profile image convert the
180 location of each touch sensor from pixel coordinates to UV-coordinates
181 and XYZ-coordinates.
183 #+name: sensors
184 #+begin_src clojure
185 (in-ns 'cortex.touch)
187 (defn feeler-pixel-coords
188 "Returns the coordinates of the feelers in pixel space in lists, one
189 list for each triangle, ordered in the same way as (triangles) and
190 (pixel-triangles)."
191 [#^Geometry geo image]
192 (map
193 (fn [pixel-triangle]
194 (filter
195 (fn [coord]
196 (inside-triangle? (->triangle pixel-triangle)
197 (->vector3f coord)))
198 (white-coordinates image (convex-bounds pixel-triangle))))
199 (pixel-triangles geo image)))
201 (defn feeler-world-coords [#^Geometry geo image]
202 (let [transforms
203 (map #(triangles->affine-transform
204 (->triangle %1) (->triangle %2))
205 (pixel-triangles geo image)
206 (triangles geo))]
207 (map (fn [transform coords]
208 (map #(.mult transform (->vector3f %)) coords))
209 transforms (feeler-pixel-coords geo image))))
211 (defn feeler-origins [#^Geometry geo image]
212 (reduce concat (feeler-world-coords geo image)))
214 (defn feeler-tips [#^Geometry geo image]
215 (let [world-coords (feeler-world-coords geo image)
216 normals
217 (map
218 (fn [triangle]
219 (.calculateNormal triangle)
220 (.clone (.getNormal triangle)))
221 (map ->triangle (triangles geo)))]
223 (mapcat (fn [origins normal]
224 (map #(.add % normal) origins))
225 world-coords normals)))
228 (defn touch-topology [#^Geometry geo image]
229 (collapse (reduce concat (feeler-pixel-coords geo image))))
230 #+end_src
232 * Visualizing Touch
233 #+name: visualization
234 #+begin_src clojure
235 (in-ns 'cortex.touch)
237 (defn touch->gray
238 "Convert a pair of [distance, max-distance] into a grayscale pixel"
239 [distance max-distance]
240 (gray
241 (- 255
242 (rem
243 (int
244 (* 255 (/ distance max-distance)))
245 256))))
247 (defn view-touch
248 "Creates a function which accepts a list of touch sensor-data and
249 displays each element to the screen."
250 []
251 (view-sense
252 (fn
253 [[coords sensor-data]]
254 (let [image (points->image coords)]
255 (dorun
256 (for [i (range (count coords))]
257 (.setRGB image ((coords i) 0) ((coords i) 1)
258 (apply touch->gray (sensor-data i)))))
259 image))))
260 #+end_src
264 * Triangle Manipulation Functions
266 The rigid bodies which make up a creature have an underlying
267 =Geometry=, which is a =Mesh= plus a =Material= and other important
268 data involved with displaying the body.
270 A =Mesh= is composed of =Triangles=, and each =Triangle= has three
271 verticies which have coordinates in XYZ space and UV space.
273 Here, =(triangles)= gets all the triangles which compose a mesh, and
274 =(triangle-UV-coord)= returns the the UV coordinates of the verticies
275 of a triangle.
277 #+name: triangles-1
278 #+begin_src clojure
279 (in-ns 'cortex.touch)
281 (defn vector3f-seq [#^Vector3f v]
282 [(.getX v) (.getY v) (.getZ v)])
284 (defn triangle-seq [#^Triangle tri]
285 [(vector3f-seq (.get1 tri))
286 (vector3f-seq (.get2 tri))
287 (vector3f-seq (.get3 tri))])
289 (defn ->vector3f
290 ([coords] (Vector3f. (nth coords 0 0)
291 (nth coords 1 0)
292 (nth coords 2 0))))
294 (defn ->triangle [points]
295 (apply #(Triangle. %1 %2 %3) (map ->vector3f points)))
297 (defn triangle
298 "Get the triangle specified by triangle-index from the mesh within
299 bounds."
300 [#^Geometry geo triangle-index]
301 (triangle-seq
302 (let [scratch (Triangle.)]
303 (.getTriangle (.getMesh geo) triangle-index scratch) scratch)))
305 (defn triangles
306 "Return a sequence of all the Triangles which compose a given
307 Geometry."
308 [#^Geometry geo]
309 (map (partial triangle geo) (range (.getTriangleCount (.getMesh geo)))))
311 (defn triangle-vertex-indices
312 "Get the triangle vertex indices of a given triangle from a given
313 mesh."
314 [#^Mesh mesh triangle-index]
315 (let [indices (int-array 3)]
316 (.getTriangle mesh triangle-index indices)
317 (vec indices)))
319 (defn vertex-UV-coord
320 "Get the UV-coordinates of the vertex named by vertex-index"
321 [#^Mesh mesh vertex-index]
322 (let [UV-buffer
323 (.getData
324 (.getBuffer
325 mesh
326 VertexBuffer$Type/TexCoord))]
327 [(.get UV-buffer (* vertex-index 2))
328 (.get UV-buffer (+ 1 (* vertex-index 2)))]))
330 (defn pixel-triangle [#^Geometry geo image index]
331 (let [mesh (.getMesh geo)
332 width (.getWidth image)
333 height (.getHeight image)]
334 (vec (map (fn [[u v]] (vector (* width u) (* height v)))
335 (map (partial vertex-UV-coord mesh)
336 (triangle-vertex-indices mesh index))))))
338 (defn pixel-triangles [#^Geometry geo image]
339 (let [height (.getHeight image)
340 width (.getWidth image)]
341 (map (partial pixel-triangle geo image)
342 (range (.getTriangleCount (.getMesh geo))))))
344 #+end_src
346 * Triangle Affine Transforms
348 The position of each hair is stored in a 2D image in UV
349 coordinates. To place the hair in 3D space we must convert from UV
350 coordinates to XYZ coordinates. Each =Triangle= has coordinates in
351 both UV-space and XYZ-space, which defines a unique [[http://mathworld.wolfram.com/AffineTransformation.html ][Affine Transform]]
352 for translating any coordinate within the UV triangle to the
353 cooresponding coordinate in the XYZ triangle.
355 #+name: triangles-3
356 #+begin_src clojure
357 (in-ns 'cortex.touch)
359 (defn triangle->matrix4f
360 "Converts the triangle into a 4x4 matrix: The first three columns
361 contain the vertices of the triangle; the last contains the unit
362 normal of the triangle. The bottom row is filled with 1s."
363 [#^Triangle t]
364 (let [mat (Matrix4f.)
365 [vert-1 vert-2 vert-3]
366 ((comp vec map) #(.get t %) (range 3))
367 unit-normal (do (.calculateNormal t)(.getNormal t))
368 vertices [vert-1 vert-2 vert-3 unit-normal]]
369 (dorun
370 (for [row (range 4) col (range 3)]
371 (do
372 (.set mat col row (.get (vertices row)col))
373 (.set mat 3 row 1))))
374 mat))
376 (defn triangles->affine-transform
377 "Returns the affine transformation that converts each vertex in the
378 first triangle into the corresponding vertex in the second
379 triangle."
380 [#^Triangle tri-1 #^Triangle tri-2]
381 (.mult
382 (triangle->matrix4f tri-2)
383 (.invert (triangle->matrix4f tri-1))))
384 #+end_src
387 * Schrapnel Conversion Functions
389 It is convienent to treat a =Triangle= as a sequence of verticies, and
390 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion
391 functions make this easy. If these classes implemented =Iterable= then
392 this code would not be necessary. Hopefully they will in the future.
395 * Triangle Boundaries
397 For efficiency's sake I will divide the UV-image into small squares
398 which inscribe each UV-triangle, then extract the points which lie
399 inside the triangle and map them to 3D-space using
400 =(triangle-transform)= above. To do this I need a function,
401 =(inside-triangle?)=, which determines whether a point is inside a
402 triangle in 2D UV-space.
404 #+name: triangles-4
405 #+begin_src clojure
406 (defn convex-bounds
407 "Returns the smallest square containing the given vertices, as a
408 vector of integers [left top width height]."
409 [verts]
410 (let [xs (map first verts)
411 ys (map second verts)
412 x0 (Math/floor (apply min xs))
413 y0 (Math/floor (apply min ys))
414 x1 (Math/ceil (apply max xs))
415 y1 (Math/ceil (apply max ys))]
416 [x0 y0 (- x1 x0) (- y1 y0)]))
418 (defn same-side?
419 "Given the points p1 and p2 and the reference point ref, is point p
420 on the same side of the line that goes through p1 and p2 as ref is?"
421 [p1 p2 ref p]
422 (<=
423 0
424 (.dot
425 (.cross (.subtract p2 p1) (.subtract p p1))
426 (.cross (.subtract p2 p1) (.subtract ref p1)))))
428 (defn inside-triangle?
429 "Is the point inside the triangle?"
430 {:author "Dylan Holmes"}
431 [#^Triangle tri #^Vector3f p]
432 (let [[vert-1 vert-2 vert-3] [(.get1 tri) (.get2 tri) (.get3 tri)]]
433 (and
434 (same-side? vert-1 vert-2 vert-3 p)
435 (same-side? vert-2 vert-3 vert-1 p)
436 (same-side? vert-3 vert-1 vert-2 p))))
437 #+end_src
439 * Physics Collision Objects
441 The "hairs" are actually =Rays= which extend from a point on a
442 =Triangle= in the =Mesh= normal to the =Triangle's= surface.
444 * Headers
446 #+name: touch-header
447 #+begin_src clojure
448 (ns cortex.touch
449 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry
450 to be outfitted with touch sensors with density determined by a UV
451 image. In this way a Geometry can know what parts of itself are
452 touching nearby objects. Reads specially prepared blender files to
453 construct this sense automatically."
454 {:author "Robert McIntyre"}
455 (:use (cortex world util sense))
456 (:use clojure.contrib.def)
457 (:import (com.jme3.scene Geometry Node Mesh))
458 (:import com.jme3.collision.CollisionResults)
459 (:import com.jme3.scene.VertexBuffer$Type)
460 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))
461 #+end_src
463 * Adding Touch to the Worm
465 #+name: test-touch
466 #+begin_src clojure
467 (ns cortex.test.touch
468 (:use (cortex world util sense body touch))
469 (:use cortex.test.body))
471 (cortex.import/mega-import-jme3)
473 (defn test-touch []
474 (let [the-worm (doto (worm) (body!))
475 touch (touch! the-worm)
476 touch-display (view-touch)]
477 (world (nodify [the-worm (floor)])
478 standard-debug-controls
480 (fn [world]
481 (speed-up world)
482 (light-up-everything world))
484 (fn [world tpf]
485 (touch-display (map #(% (.getRootNode world)) touch))
486 ))))
487 #+end_src
488 * Source Listing
489 * Next
492 * COMMENT Code Generation
493 #+begin_src clojure :tangle ../src/cortex/touch.clj
494 <<touch-header>>
495 <<meta-data>>
496 <<triangles-1>>
497 <<triangles-3>>
498 <<triangles-4>>
499 <<sensors>>
500 <<kernel>>
501 <<visualization>>
502 #+end_src
505 #+begin_src clojure :tangle ../src/cortex/test/touch.clj
506 <<test-touch>>
507 #+end_src