view org/touch.org @ 243:f33fec68f775

touch has been restored, with some very slight speed improvements, and now with much less code
author Robert McIntyre <rlm@mit.edu>
date Sun, 12 Feb 2012 14:14:57 -0700
parents a7f26a074071
children f23217324f72
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 feeler
83 =(touch-kernel)= generates the functions which implement the sense of
84 touch for a creature. These functions must do 6 things to obtain touch
85 data.
87 - Get the tactile profile image and scale paramaters which describe
88 the layout of feelers along the object's surface.
89 =(tactile-sensor-profile)=, =(tactile-scale)=
91 - Get the lengths of each feeler by analyzing the color of the
92 pixels in the tactile profile image.
93 NOT IMPLEMENTED YET
95 - Find the triangles which make up the mesh in pixel-space and in
96 world-space.
97 =(triangles)= =(pixel-triangles)=
99 - Find the coordinates of each pixel in pixel space. These
100 coordinates are used to make the touch-topology.
101 =(feeler-pixel-coords)=
103 - Find the coordinates of each pixel in world-space. These
104 coordinates are the origins of the feelers. =(feeler-origins)=
106 - Calculate the normals of the triangles in world space, and add
107 them to each of the origins of the feelers. These are the
108 normalized coordinates of the tips of the feelers.
109 For both of these, =(feeler-tips)=
111 - Generate some sort of topology for the sensors.
112 =(touch-topology)=
115 #+name: kernel
116 #+begin_src clojure
117 (in-ns 'cortex.touch)
119 (declare touch-topology feelers set-ray)
121 (defn set-ray [#^Ray ray #^Matrix4f transform #^Vector3f origin
122 #^Vector3f tip length]
123 ;; Doing everything locally recduces garbage collection by enough to
124 ;; be worth it.
125 (.mult transform origin (.getOrigin ray))
127 (.mult transform tip (.getDirection ray))
128 (.subtractLocal (.getDirection ray) (.getOrigin ray))
129 (.setLimit ray length))
131 (defn touch-kernel
132 "Constructs a function which will return tactile sensory data from
133 'geo when called from inside a running simulation"
134 [#^Geometry geo]
135 (if-let
136 [profile (tactile-sensor-profile geo)]
137 (let [ray-reference-origins (feeler-origins geo profile)
138 ray-reference-tips (feeler-tips geo profile)
139 ray-lengths (repeat 9000 0.1)
140 current-rays (map (fn [_] (Ray.)) ray-reference-origins)
141 topology (touch-topology geo profile)]
142 (fn [node]
143 (let [transform (.getWorldMatrix geo)]
144 (dorun
145 (map (fn [ray ref-origin ref-tip length]
146 (set-ray ray transform ref-origin ref-tip length))
147 current-rays ray-reference-origins
148 ray-reference-tips ray-lengths))
149 (vector
150 topology
151 (vec
152 (for [ray current-rays]
153 (do
154 (let [results (CollisionResults.)]
155 (.collideWith node ray results)
156 (let [touch-objects
157 (filter #(not (= geo (.getGeometry %)))
158 results)]
159 [(if (empty? touch-objects)
160 (.getLimit ray)
161 (.getDistance (first touch-objects)))
162 (.getLimit ray)])))))))))))
164 (defn touch!
165 "Endow the creature with the sense of touch. Returns a sequence of
166 functions, one for each body part with a tactile-sensor-proile,
167 each of which when called returns sensory data for that body part."
168 [#^Node creature]
169 (filter
170 (comp not nil?)
171 (map touch-kernel
172 (filter #(isa? (class %) Geometry)
173 (node-seq creature)))))
174 #+end_src
176 #+results: kernel
177 : #'cortex.touch/touch!
179 * Sensor Related Functions
181 These functions analyze the touch-sensor-profile image convert the
182 location of each touch sensor from pixel coordinates to UV-coordinates
183 and XYZ-coordinates.
185 #+name: sensors
186 #+begin_src clojure
187 (in-ns 'cortex.touch)
189 (defn feeler-pixel-coords
190 "Returns the coordinates of the feelers in pixel space in lists, one
191 list for each triangle, ordered in the same way as (triangles) and
192 (pixel-triangles)."
193 [#^Geometry geo image]
194 (map
195 (fn [pixel-triangle]
196 (filter
197 (fn [coord]
198 (inside-triangle? (->triangle pixel-triangle)
199 (->vector3f coord)))
200 (white-coordinates image (convex-bounds pixel-triangle))))
201 (pixel-triangles geo image)))
203 (defn feeler-world-coords [#^Geometry geo image]
204 (let [transforms
205 (map #(triangles->affine-transform
206 (->triangle %1) (->triangle %2))
207 (pixel-triangles geo image)
208 (triangles geo))]
209 (map (fn [transform coords]
210 (map #(.mult transform (->vector3f %)) coords))
211 transforms (feeler-pixel-coords geo image))))
213 (defn feeler-origins [#^Geometry geo image]
214 (reduce concat (feeler-world-coords geo image)))
216 (defn feeler-tips [#^Geometry geo image]
217 (let [world-coords (feeler-world-coords geo image)
218 normals
219 (map
220 (fn [triangle]
221 (.calculateNormal triangle)
222 (.clone (.getNormal triangle)))
223 (map ->triangle (triangles geo)))]
225 (mapcat (fn [origins normal]
226 (map #(.add % normal) origins))
227 world-coords normals)))
230 (defn touch-topology [#^Geometry geo image]
231 (collapse (reduce concat (feeler-pixel-coords geo image))))
232 #+end_src
234 * Visualizing Touch
235 #+name: visualization
236 #+begin_src clojure
237 (in-ns 'cortex.touch)
239 (defn touch->gray
240 "Convert a pair of [distance, max-distance] into a grayscale pixel"
241 [distance max-distance]
242 (gray
243 (- 255
244 (rem
245 (int
246 (* 255 (/ distance max-distance)))
247 256))))
249 (defn view-touch
250 "Creates a function which accepts a list of touch sensor-data and
251 displays each element to the screen."
252 []
253 (view-sense
254 (fn
255 [[coords sensor-data]]
256 (let [image (points->image coords)]
257 (dorun
258 (for [i (range (count coords))]
259 (.setRGB image ((coords i) 0) ((coords i) 1)
260 (apply touch->gray (sensor-data i)))))
261 image))))
262 #+end_src
266 * Triangle Manipulation Functions
268 The rigid bodies which make up a creature have an underlying
269 =Geometry=, which is a =Mesh= plus a =Material= and other important
270 data involved with displaying the body.
272 A =Mesh= is composed of =Triangles=, and each =Triangle= has three
273 verticies which have coordinates in XYZ space and UV space.
275 Here, =(triangles)= gets all the triangles which compose a mesh, and
276 =(triangle-UV-coord)= returns the the UV coordinates of the verticies
277 of a triangle.
279 #+name: triangles-1
280 #+begin_src clojure
281 (in-ns 'cortex.touch)
283 (defn vector3f-seq [#^Vector3f v]
284 [(.getX v) (.getY v) (.getZ v)])
286 (defn triangle-seq [#^Triangle tri]
287 [(vector3f-seq (.get1 tri))
288 (vector3f-seq (.get2 tri))
289 (vector3f-seq (.get3 tri))])
291 (defn ->vector3f
292 ([coords] (Vector3f. (nth coords 0 0)
293 (nth coords 1 0)
294 (nth coords 2 0))))
296 (defn ->triangle [points]
297 (apply #(Triangle. %1 %2 %3) (map ->vector3f points)))
299 (defn triangle
300 "Get the triangle specified by triangle-index from the mesh within
301 bounds."
302 [#^Geometry geo triangle-index]
303 (triangle-seq
304 (let [scratch (Triangle.)]
305 (.getTriangle (.getMesh geo) triangle-index scratch) scratch)))
307 (defn triangles
308 "Return a sequence of all the Triangles which compose a given
309 Geometry."
310 [#^Geometry geo]
311 (map (partial triangle geo) (range (.getTriangleCount (.getMesh geo)))))
313 (defn triangle-vertex-indices
314 "Get the triangle vertex indices of a given triangle from a given
315 mesh."
316 [#^Mesh mesh triangle-index]
317 (let [indices (int-array 3)]
318 (.getTriangle mesh triangle-index indices)
319 (vec indices)))
321 (defn vertex-UV-coord
322 "Get the UV-coordinates of the vertex named by vertex-index"
323 [#^Mesh mesh vertex-index]
324 (let [UV-buffer
325 (.getData
326 (.getBuffer
327 mesh
328 VertexBuffer$Type/TexCoord))]
329 [(.get UV-buffer (* vertex-index 2))
330 (.get UV-buffer (+ 1 (* vertex-index 2)))]))
332 (defn pixel-triangle [#^Geometry geo image index]
333 (let [mesh (.getMesh geo)
334 width (.getWidth image)
335 height (.getHeight image)]
336 (vec (map (fn [[u v]] (vector (* width u) (* height v)))
337 (map (partial vertex-UV-coord mesh)
338 (triangle-vertex-indices mesh index))))))
340 (defn pixel-triangles [#^Geometry geo image]
341 (let [height (.getHeight image)
342 width (.getWidth image)]
343 (map (partial pixel-triangle geo image)
344 (range (.getTriangleCount (.getMesh geo))))))
346 #+end_src
348 * Triangle Affine Transforms
350 The position of each hair is stored in a 2D image in UV
351 coordinates. To place the hair in 3D space we must convert from UV
352 coordinates to XYZ coordinates. Each =Triangle= has coordinates in
353 both UV-space and XYZ-space, which defines a unique [[http://mathworld.wolfram.com/AffineTransformation.html ][Affine Transform]]
354 for translating any coordinate within the UV triangle to the
355 cooresponding coordinate in the XYZ triangle.
357 #+name: triangles-3
358 #+begin_src clojure
359 (in-ns 'cortex.touch)
361 (defn triangle->matrix4f
362 "Converts the triangle into a 4x4 matrix: The first three columns
363 contain the vertices of the triangle; the last contains the unit
364 normal of the triangle. The bottom row is filled with 1s."
365 [#^Triangle t]
366 (let [mat (Matrix4f.)
367 [vert-1 vert-2 vert-3]
368 ((comp vec map) #(.get t %) (range 3))
369 unit-normal (do (.calculateNormal t)(.getNormal t))
370 vertices [vert-1 vert-2 vert-3 unit-normal]]
371 (dorun
372 (for [row (range 4) col (range 3)]
373 (do
374 (.set mat col row (.get (vertices row)col))
375 (.set mat 3 row 1))))
376 mat))
378 (defn triangles->affine-transform
379 "Returns the affine transformation that converts each vertex in the
380 first triangle into the corresponding vertex in the second
381 triangle."
382 [#^Triangle tri-1 #^Triangle tri-2]
383 (.mult
384 (triangle->matrix4f tri-2)
385 (.invert (triangle->matrix4f tri-1))))
386 #+end_src
389 * Schrapnel Conversion Functions
391 It is convienent to treat a =Triangle= as a sequence of verticies, and
392 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion
393 functions make this easy. If these classes implemented =Iterable= then
394 this code would not be necessary. Hopefully they will in the future.
397 * Triangle Boundaries
399 For efficiency's sake I will divide the UV-image into small squares
400 which inscribe each UV-triangle, then extract the points which lie
401 inside the triangle and map them to 3D-space using
402 =(triangle-transform)= above. To do this I need a function,
403 =(inside-triangle?)=, which determines whether a point is inside a
404 triangle in 2D UV-space.
406 #+name: triangles-4
407 #+begin_src clojure
408 (defn convex-bounds
409 "Returns the smallest square containing the given vertices, as a
410 vector of integers [left top width height]."
411 [verts]
412 (let [xs (map first verts)
413 ys (map second verts)
414 x0 (Math/floor (apply min xs))
415 y0 (Math/floor (apply min ys))
416 x1 (Math/ceil (apply max xs))
417 y1 (Math/ceil (apply max ys))]
418 [x0 y0 (- x1 x0) (- y1 y0)]))
420 (defn same-side?
421 "Given the points p1 and p2 and the reference point ref, is point p
422 on the same side of the line that goes through p1 and p2 as ref is?"
423 [p1 p2 ref p]
424 (<=
425 0
426 (.dot
427 (.cross (.subtract p2 p1) (.subtract p p1))
428 (.cross (.subtract p2 p1) (.subtract ref p1)))))
430 (defn inside-triangle?
431 "Is the point inside the triangle?"
432 {:author "Dylan Holmes"}
433 [#^Triangle tri #^Vector3f p]
434 (let [[vert-1 vert-2 vert-3] [(.get1 tri) (.get2 tri) (.get3 tri)]]
435 (and
436 (same-side? vert-1 vert-2 vert-3 p)
437 (same-side? vert-2 vert-3 vert-1 p)
438 (same-side? vert-3 vert-1 vert-2 p))))
439 #+end_src
441 * Physics Collision Objects
443 The "hairs" are actually =Rays= which extend from a point on a
444 =Triangle= in the =Mesh= normal to the =Triangle's= surface.
446 * Headers
448 #+name: touch-header
449 #+begin_src clojure
450 (ns cortex.touch
451 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry
452 to be outfitted with touch sensors with density determined by a UV
453 image. In this way a Geometry can know what parts of itself are
454 touching nearby objects. Reads specially prepared blender files to
455 construct this sense automatically."
456 {:author "Robert McIntyre"}
457 (:use (cortex world util sense))
458 (:use clojure.contrib.def)
459 (:import (com.jme3.scene Geometry Node Mesh))
460 (:import com.jme3.collision.CollisionResults)
461 (:import com.jme3.scene.VertexBuffer$Type)
462 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))
463 #+end_src
465 * Adding Touch to the Worm
467 #+name: test-touch
468 #+begin_src clojure
469 (ns cortex.test.touch
470 (:use (cortex world util sense body touch))
471 (:use cortex.test.body))
473 (cortex.import/mega-import-jme3)
475 (defn test-touch []
476 (let [the-worm (doto (worm) (body!))
477 touch (touch! the-worm)
478 touch-display (view-touch)]
479 (world (nodify [the-worm (floor)])
480 standard-debug-controls
482 (fn [world]
483 (light-up-everything world))
485 (fn [world tpf]
488 (dorun (map #(% (.getRootNode world)) touch))
491 ))))
492 #+end_src
493 * Source Listing
494 * Next
497 * COMMENT Code Generation
498 #+begin_src clojure :tangle ../src/cortex/touch.clj
499 <<touch-header>>
500 <<meta-data>>
501 <<triangles-1>>
502 <<triangles-3>>
503 <<triangles-4>>
504 <<sensors>>
505 <<kernel>>
506 <<visualization>>
507 #+end_src
510 #+begin_src clojure :tangle ../src/cortex/test/touch.clj
511 <<test-touch>>
512 #+end_src