view org/touch.org @ 231:e29dd0024a9e

reorganized touch
author Robert McIntyre <rlm@mit.edu>
date Sat, 11 Feb 2012 19:32:21 -0700
parents f9b7d674aed8
children b7762699eeb5
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)))
63 #+end_src
66 ** TODO add image showing example touch-uv map
67 ** TODO add metadata display for worm
69 * Triangle Manipulation Functions
71 The rigid bodies which make up a creature have an underlying
72 =Geometry=, which is a =Mesh= plus a =Material= and other important
73 data involved with displaying the body.
75 A =Mesh= is composed of =Triangles=, and each =Triangle= has three
76 verticies which have coordinates in XYZ space and UV space.
78 Here, =(triangles)= gets all the triangles which compose a mesh, and
79 =(triangle-UV-coord)= returns the the UV coordinates of the verticies
80 of a triangle.
82 #+name: triangles-1
83 #+begin_src clojure
84 (defn triangles
85 "Return a sequence of all the Triangles which compose a given
86 Geometry."
87 [#^Geometry geom]
88 (let
89 [mesh (.getMesh geom)
90 triangles (transient [])]
91 (dorun
92 (for [n (range (.getTriangleCount mesh))]
93 (let [tri (Triangle.)]
94 (.getTriangle mesh n tri)
95 ;; (.calculateNormal tri)
96 ;; (.calculateCenter tri)
97 (conj! triangles tri))))
98 (persistent! triangles)))
100 (defn mesh-triangle
101 "Get the triangle specified by triangle-index from the mesh within
102 bounds."
103 [#^Mesh mesh triangle-index]
104 (let [scratch (Triangle.)]
105 (.getTriangle mesh triangle-index scratch)
106 scratch))
108 (defn triangle-vertex-indices
109 "Get the triangle vertex indices of a given triangle from a given
110 mesh."
111 [#^Mesh mesh triangle-index]
112 (let [indices (int-array 3)]
113 (.getTriangle mesh triangle-index indices)
114 (vec indices)))
116 (defn vertex-UV-coord
117 "Get the UV-coordinates of the vertex named by vertex-index"
118 [#^Mesh mesh vertex-index]
119 (let [UV-buffer
120 (.getData
121 (.getBuffer
122 mesh
123 VertexBuffer$Type/TexCoord))]
124 [(.get UV-buffer (* vertex-index 2))
125 (.get UV-buffer (+ 1 (* vertex-index 2)))]))
127 (defn triangle-UV-coord
128 "Get the UV-cooridnates of the triangle's verticies."
129 [#^Mesh mesh width height triangle-index]
130 (map (fn [[u v]] (vector (* width u) (* height v)))
131 (map (partial vertex-UV-coord mesh)
132 (triangle-vertex-indices mesh triangle-index))))
133 #+end_src
135 * Schrapnel Conversion Functions
137 It is convienent to treat a =Triangle= as a sequence of verticies, and
138 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion
139 functions make this easy. If these classes implemented =Iterable= then
140 this code would not be necessary. Hopefully they will in the future.
142 #+name: triangles-2
143 #+begin_src clojure
144 (defn triangle-seq [#^Triangle tri]
145 [(.get1 tri) (.get2 tri) (.get3 tri)])
147 (defn vector3f-seq [#^Vector3f v]
148 [(.getX v) (.getY v) (.getZ v)])
150 (defn point->vector2f [[u v]]
151 (Vector2f. u v))
153 (defn vector2f->vector3f [v]
154 (Vector3f. (.getX v) (.getY v) 0))
156 (defn map-triangle [f #^Triangle tri]
157 (Triangle.
158 (f 0 (.get1 tri))
159 (f 1 (.get2 tri))
160 (f 2 (.get3 tri))))
162 (defn points->triangle
163 "Convert a list of points into a triangle."
164 [points]
165 (apply #(Triangle. %1 %2 %3)
166 (map (fn [point]
167 (let [point (vec point)]
168 (Vector3f. (get point 0 0)
169 (get point 1 0)
170 (get point 2 0))))
171 (take 3 points))))
172 #+end_src
174 * Triangle Affine Transforms
176 The position of each hair is stored in a 2D image in UV
177 coordinates. To place the hair in 3D space we must convert from UV
178 coordinates to XYZ coordinates. Each =Triangle= has coordinates in
179 both UV-space and XYZ-space, which defines a unique [[http://mathworld.wolfram.com/AffineTransformation.html ][Affine Transform]]
180 for translating any coordinate within the UV triangle to the
181 cooresponding coordinate in the XYZ triangle.
183 #+name: triangles-3
184 #+begin_src clojure
185 (defn triangle->matrix4f
186 "Converts the triangle into a 4x4 matrix: The first three columns
187 contain the vertices of the triangle; the last contains the unit
188 normal of the triangle. The bottom row is filled with 1s."
189 [#^Triangle t]
190 (let [mat (Matrix4f.)
191 [vert-1 vert-2 vert-3]
192 ((comp vec map) #(.get t %) (range 3))
193 unit-normal (do (.calculateNormal t)(.getNormal t))
194 vertices [vert-1 vert-2 vert-3 unit-normal]]
195 (dorun
196 (for [row (range 4) col (range 3)]
197 (do
198 (.set mat col row (.get (vertices row)col))
199 (.set mat 3 row 1))))
200 mat))
202 (defn triangle-transformation
203 "Returns the affine transformation that converts each vertex in the
204 first triangle into the corresponding vertex in the second
205 triangle."
206 [#^Triangle tri-1 #^Triangle tri-2]
207 (.mult
208 (triangle->matrix4f tri-2)
209 (.invert (triangle->matrix4f tri-1))))
210 #+end_src
212 * Triangle Boundaries
214 For efficiency's sake I will divide the UV-image into small squares
215 which inscribe each UV-triangle, then extract the points which lie
216 inside the triangle and map them to 3D-space using
217 =(triangle-transform)= above. To do this I need a function,
218 =(inside-triangle?)=, which determines whether a point is inside a
219 triangle in 2D UV-space.
221 #+name: triangles-4
222 #+begin_src clojure
223 (defn convex-bounds
224 "Returns the smallest square containing the given vertices, as a
225 vector of integers [left top width height]."
226 [uv-verts]
227 (let [xs (map first uv-verts)
228 ys (map second uv-verts)
229 x0 (Math/floor (apply min xs))
230 y0 (Math/floor (apply min ys))
231 x1 (Math/ceil (apply max xs))
232 y1 (Math/ceil (apply max ys))]
233 [x0 y0 (- x1 x0) (- y1 y0)]))
235 (defn same-side?
236 "Given the points p1 and p2 and the reference point ref, is point p
237 on the same side of the line that goes through p1 and p2 as ref is?"
238 [p1 p2 ref p]
239 (<=
240 0
241 (.dot
242 (.cross (.subtract p2 p1) (.subtract p p1))
243 (.cross (.subtract p2 p1) (.subtract ref p1)))))
245 (defn inside-triangle?
246 "Is the point inside the triangle?"
247 {:author "Dylan Holmes"}
248 [#^Triangle tri #^Vector3f p]
249 (let [[vert-1 vert-2 vert-3] (triangle-seq tri)]
250 (and
251 (same-side? vert-1 vert-2 vert-3 p)
252 (same-side? vert-2 vert-3 vert-1 p)
253 (same-side? vert-3 vert-1 vert-2 p))))
254 #+end_src
258 * Sensor Related Functions
260 These functions analyze the touch-sensor-profile image convert the
261 location of each touch sensor from pixel coordinates to UV-coordinates
262 and XYZ-coordinates.
264 #+name: sensors
265 #+begin_src clojure
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
313 * Physics Collision Objects
315 The "hairs" are actually rays which extend from a point on a
316 =Triangle= in the =Mesh= normal to the =Triangle's= surface.
318 #+name: rays
319 #+begin_src clojure
320 (defn get-ray-origin
321 "Return the origin which a Ray would have to have to be in the exact
322 center of a particular Triangle in the Geometry in World
323 Coordinates."
324 [geom tri]
325 (let [new (Vector3f.)]
326 (.calculateCenter tri)
327 (.localToWorld geom (.getCenter tri) new) new))
329 (defn get-ray-direction
330 "Return the direction which a Ray would have to have to be to point
331 normal to the Triangle, in coordinates relative to the center of the
332 Triangle."
333 [geom tri]
334 (let [n+c (Vector3f.)]
335 (.calculateNormal tri)
336 (.calculateCenter tri)
337 (.localToWorld
338 geom
339 (.add (.getCenter tri) (.getNormal tri)) n+c)
340 (.subtract n+c (get-ray-origin geom tri))))
341 #+end_src
344 * Skin Creation
345 #+name: kernel
346 #+begin_src clojure
347 (defn touch-fn
348 "Returns a function which returns tactile sensory data when called
349 inside a running simulation."
350 [#^Geometry geo]
351 (let [feeler-coords (feeler-coordinates geo)
352 tris (triangles geo)
353 limit 0.1
354 ;;results (CollisionResults.)
355 ]
356 (if (empty? (touch-topology geo))
357 nil
358 (fn [node]
359 (let [sensor-origins
360 (map
361 #(map (partial local-to-world geo) %)
362 feeler-coords)
363 triangle-normals
364 (map (partial get-ray-direction geo)
365 tris)
366 rays
367 (flatten
368 (map (fn [origins norm]
369 (map #(doto (Ray. % norm)
370 (.setLimit limit)) origins))
371 sensor-origins triangle-normals))]
372 (vector
373 (touch-topology geo)
374 (vec
375 (for [ray rays]
376 (do
377 (let [results (CollisionResults.)]
378 (.collideWith node ray results)
379 (let [touch-objects
380 (filter #(not (= geo (.getGeometry %)))
381 results)]
382 (- 255
383 (if (empty? touch-objects) 255
384 (rem
385 (int
386 (* 255 (/ (.getDistance
387 (first touch-objects)) limit)))
388 256))))))))))))))
390 (defn touch!
391 "Endow the creature with the sense of touch. Returns a sequence of
392 functions, one for each body part with a tactile-sensor-proile,
393 each of which when called returns sensory data for that body part."
394 [#^Node creature]
395 (filter
396 (comp not nil?)
397 (map touch-fn
398 (filter #(isa? (class %) Geometry)
399 (node-seq creature)))))
400 #+end_src
402 * Visualizing Touch
403 #+name: visualization
404 #+begin_src clojure
405 (defn view-touch
406 "Creates a function which accepts a list of touch sensor-data and
407 displays each element to the screen."
408 []
409 (view-sense
410 (fn
411 [[coords sensor-data]]
412 (let [image (points->image coords)]
413 (dorun
414 (for [i (range (count coords))]
415 (.setRGB image ((coords i) 0) ((coords i) 1)
416 (gray (sensor-data i)))))
417 image))))
418 #+end_src
420 * Headers
422 #+name: touch-header
423 #+begin_src clojure
424 (ns cortex.touch
425 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry
426 to be outfitted with touch sensors with density determined by a UV
427 image. In this way a Geometry can know what parts of itself are
428 touching nearby objects. Reads specially prepared blender files to
429 construct this sense automatically."
430 {:author "Robert McIntyre"}
431 (:use (cortex world util sense))
432 (:use clojure.contrib.def)
433 (:import (com.jme3.scene Geometry Node Mesh))
434 (:import com.jme3.collision.CollisionResults)
435 (:import com.jme3.scene.VertexBuffer$Type)
436 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))
437 #+end_src
440 * Source Listing
441 * Next
444 * COMMENT Code Generation
445 #+begin_src clojure :tangle ../src/cortex/touch.clj
446 <<touch-header>>
447 <<meta-data>>
448 <<triangles-1>>
449 <<triangles-2>>
450 <<triangles-3>>
451 <<triangles-4>>
452 <<sensors>>
453 <<rays>>
454 <<kernel>>
455 <<visualization>>
456 #+end_src
458 #+begin_src clojure :tangle ../src/cortex/test/touch.clj
459 #+end_src