view org/touch.org @ 228:0589c35f04f2

wrote intro for touch.org
author Robert McIntyre <rlm@mit.edu>
date Sat, 11 Feb 2012 18:42:27 -0700
parents 2a7f57e7efdb
children 6f1be9525e40
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".
40 * Sensor Related Functions
41 #+begin_src clojure
42 (defn sensors-in-triangle
43 "Locate the touch sensors in the triangle, returning a map of their
44 UV and geometry-relative coordinates."
45 [image mesh tri-index]
46 (let [width (.getWidth image)
47 height (.getHeight image)
48 UV-vertex-coords (triangle-UV-coord mesh width height tri-index)
49 bounds (convex-bounds UV-vertex-coords)
51 cutout-triangle (points->triangle UV-vertex-coords)
52 UV-sensor-coords
53 (filter (comp (partial inside-triangle? cutout-triangle)
54 (fn [[u v]] (Vector3f. u v 0)))
55 (white-coordinates image bounds))
56 UV->geometry (triangle-transformation
57 cutout-triangle
58 (mesh-triangle mesh tri-index))
59 geometry-sensor-coords
60 (map (fn [[u v]] (.mult UV->geometry (Vector3f. u v 0)))
61 UV-sensor-coords)]
62 {:UV UV-sensor-coords :geometry geometry-sensor-coords}))
64 (defn-memo locate-feelers
65 "Search the geometry's tactile UV profile for touch sensors,
66 returning their positions in geometry-relative coordinates."
67 [#^Geometry geo]
68 (let [mesh (.getMesh geo)
69 num-triangles (.getTriangleCount mesh)]
70 (if-let [image (tactile-sensor-profile geo)]
71 (map
72 (partial sensors-in-triangle image mesh)
73 (range num-triangles))
74 (repeat (.getTriangleCount mesh) {:UV nil :geometry nil}))))
76 (defn-memo touch-topology
77 "Return a sequence of vectors of the form [x y] describing the
78 \"topology\" of the tactile sensors. Points that are close together
79 in the touch-topology are generally close together in the simulation."
80 [#^Gemoetry geo]
81 (vec (collapse (reduce concat (map :UV (locate-feelers geo))))))
83 (defn-memo feeler-coordinates
84 "The location of the touch sensors in world-space coordinates."
85 [#^Geometry geo]
86 (vec (map :geometry (locate-feelers geo))))
87 #+end_src
89 * Triangle Manipulation Functions
91 #+begin_src clojure
92 (defn triangles
93 "Return a sequence of all the Triangles which compose a given
94 Geometry."
95 [#^Geometry geom]
96 (let
97 [mesh (.getMesh geom)
98 triangles (transient [])]
99 (dorun
100 (for [n (range (.getTriangleCount mesh))]
101 (let [tri (Triangle.)]
102 (.getTriangle mesh n tri)
103 ;; (.calculateNormal tri)
104 ;; (.calculateCenter tri)
105 (conj! triangles tri))))
106 (persistent! triangles)))
108 (defn mesh-triangle
109 "Get the triangle specified by triangle-index from the mesh within
110 bounds."
111 [#^Mesh mesh triangle-index]
112 (let [scratch (Triangle.)]
113 (.getTriangle mesh triangle-index scratch)
114 scratch))
116 (defn triangle-vertex-indices
117 "Get the triangle vertex indices of a given triangle from a given
118 mesh."
119 [#^Mesh mesh triangle-index]
120 (let [indices (int-array 3)]
121 (.getTriangle mesh triangle-index indices)
122 (vec indices)))
124 (defn vertex-UV-coord
125 "Get the UV-coordinates of the vertex named by vertex-index"
126 [#^Mesh mesh vertex-index]
127 (let [UV-buffer
128 (.getData
129 (.getBuffer
130 mesh
131 VertexBuffer$Type/TexCoord))]
132 [(.get UV-buffer (* vertex-index 2))
133 (.get UV-buffer (+ 1 (* vertex-index 2)))]))
135 (defn triangle-UV-coord
136 "Get the UV-cooridnates of the triangle's verticies."
137 [#^Mesh mesh width height triangle-index]
138 (map (fn [[u v]] (vector (* width u) (* height v)))
139 (map (partial vertex-UV-coord mesh)
140 (triangle-vertex-indices mesh triangle-index))))
141 #+end_src
143 * Schrapnel Conversion Functions
144 #+begin_src clojure
145 (defn triangle-seq [#^Triangle tri]
146 [(.get1 tri) (.get2 tri) (.get3 tri)])
148 (defn vector3f-seq [#^Vector3f v]
149 [(.getX v) (.getY v) (.getZ v)])
151 (defn point->vector2f [[u v]]
152 (Vector2f. u v))
154 (defn vector2f->vector3f [v]
155 (Vector3f. (.getX v) (.getY v) 0))
157 (defn map-triangle [f #^Triangle tri]
158 (Triangle.
159 (f 0 (.get1 tri))
160 (f 1 (.get2 tri))
161 (f 2 (.get3 tri))))
163 (defn points->triangle
164 "Convert a list of points into a triangle."
165 [points]
166 (apply #(Triangle. %1 %2 %3)
167 (map (fn [point]
168 (let [point (vec point)]
169 (Vector3f. (get point 0 0)
170 (get point 1 0)
171 (get point 2 0))))
172 (take 3 points))))
173 #+end_src
175 * Triangle Affine Transforms
177 #+begin_src clojure
178 (defn triangle->matrix4f
179 "Converts the triangle into a 4x4 matrix: The first three columns
180 contain the vertices of the triangle; the last contains the unit
181 normal of the triangle. The bottom row is filled with 1s."
182 [#^Triangle t]
183 (let [mat (Matrix4f.)
184 [vert-1 vert-2 vert-3]
185 ((comp vec map) #(.get t %) (range 3))
186 unit-normal (do (.calculateNormal t)(.getNormal t))
187 vertices [vert-1 vert-2 vert-3 unit-normal]]
188 (dorun
189 (for [row (range 4) col (range 3)]
190 (do
191 (.set mat col row (.get (vertices row)col))
192 (.set mat 3 row 1))))
193 mat))
195 (defn triangle-transformation
196 "Returns the affine transformation that converts each vertex in the
197 first triangle into the corresponding vertex in the second
198 triangle."
199 [#^Triangle tri-1 #^Triangle tri-2]
200 (.mult
201 (triangle->matrix4f tri-2)
202 (.invert (triangle->matrix4f tri-1))))
203 #+end_src
205 * Blender Meta-Data
207 #+begin_src clojure
208 (defn tactile-sensor-profile
209 "Return the touch-sensor distribution image in BufferedImage format,
210 or nil if it does not exist."
211 [#^Geometry obj]
212 (if-let [image-path (meta-data obj "touch")]
213 (load-image image-path)))
214 #+end_src
216 * Physics Collision Objects
217 #+begin_src clojure
218 (defn get-ray-origin
219 "Return the origin which a Ray would have to have to be in the exact
220 center of a particular Triangle in the Geometry in World
221 Coordinates."
222 [geom tri]
223 (let [new (Vector3f.)]
224 (.calculateCenter tri)
225 (.localToWorld geom (.getCenter tri) new) new))
227 (defn get-ray-direction
228 "Return the direction which a Ray would have to have to be to point
229 normal to the Triangle, in coordinates relative to the center of the
230 Triangle."
231 [geom tri]
232 (let [n+c (Vector3f.)]
233 (.calculateNormal tri)
234 (.calculateCenter tri)
235 (.localToWorld
236 geom
237 (.add (.getCenter tri) (.getNormal tri)) n+c)
238 (.subtract n+c (get-ray-origin geom tri))))
239 #+end_src
241 * Triangle Boundaries
242 #+begin_src clojure
243 (defn same-side?
244 "Given the points p1 and p2 and the reference point ref, is point p
245 on the same side of the line that goes through p1 and p2 as ref is?"
246 [p1 p2 ref p]
247 (<=
248 0
249 (.dot
250 (.cross (.subtract p2 p1) (.subtract p p1))
251 (.cross (.subtract p2 p1) (.subtract ref p1)))))
253 (defn inside-triangle?
254 "Is the point inside the triangle?"
255 {:author "Dylan Holmes"}
256 [#^Triangle tri #^Vector3f p]
257 (let [[vert-1 vert-2 vert-3] (triangle-seq tri)]
258 (and
259 (same-side? vert-1 vert-2 vert-3 p)
260 (same-side? vert-2 vert-3 vert-1 p)
261 (same-side? vert-3 vert-1 vert-2 p))))
263 (defn convex-bounds
264 "Returns the smallest square containing the given vertices, as a
265 vector of integers [left top width height]."
266 [uv-verts]
267 (let [xs (map first uv-verts)
268 ys (map second uv-verts)
269 x0 (Math/floor (apply min xs))
270 y0 (Math/floor (apply min ys))
271 x1 (Math/ceil (apply max xs))
272 y1 (Math/ceil (apply max ys))]
273 [x0 y0 (- x1 x0) (- y1 y0)]))
274 #+end_src
276 * Skin Creation
278 #+begin_src clojure
279 (defn touch-fn
280 "Returns a function which returns tactile sensory data when called
281 inside a running simulation."
282 [#^Geometry geo]
283 (let [feeler-coords (feeler-coordinates geo)
284 tris (triangles geo)
285 limit 0.1
286 ;;results (CollisionResults.)
287 ]
288 (if (empty? (touch-topology geo))
289 nil
290 (fn [node]
291 (let [sensor-origins
292 (map
293 #(map (partial local-to-world geo) %)
294 feeler-coords)
295 triangle-normals
296 (map (partial get-ray-direction geo)
297 tris)
298 rays
299 (flatten
300 (map (fn [origins norm]
301 (map #(doto (Ray. % norm)
302 (.setLimit limit)) origins))
303 sensor-origins triangle-normals))]
304 (vector
305 (touch-topology geo)
306 (vec
307 (for [ray rays]
308 (do
309 (let [results (CollisionResults.)]
310 (.collideWith node ray results)
311 (let [touch-objects
312 (filter #(not (= geo (.getGeometry %)))
313 results)]
314 (- 255
315 (if (empty? touch-objects) 255
316 (rem
317 (int
318 (* 255 (/ (.getDistance
319 (first touch-objects)) limit)))
320 256))))))))))))))
322 (defn touch!
323 "Endow the creature with the sense of touch. Returns a sequence of
324 functions, one for each body part with a tactile-sensor-proile,
325 each of which when called returns sensory data for that body part."
326 [#^Node creature]
327 (filter
328 (comp not nil?)
329 (map touch-fn
330 (filter #(isa? (class %) Geometry)
331 (node-seq creature)))))
332 #+end_src
334 * Visualizing Touch
336 #+begin_src clojure
337 (defn view-touch
338 "Creates a function which accepts a list of touch sensor-data and
339 displays each element to the screen."
340 []
341 (view-sense
342 (fn
343 [[coords sensor-data]]
344 (let [image (points->image coords)]
345 (dorun
346 (for [i (range (count coords))]
347 (.setRGB image ((coords i) 0) ((coords i) 1)
348 (gray (sensor-data i)))))
349 image))))
350 #+end_src
352 * Headers
353 #+begin_src clojure
354 (ns cortex.touch
355 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry
356 to be outfitted with touch sensors with density determined by a UV
357 image. In this way a Geometry can know what parts of itself are
358 touching nearby objects. Reads specially prepared blender files to
359 construct this sense automatically."
360 {:author "Robert McIntyre"}
361 (:use (cortex world util sense))
362 (:use clojure.contrib.def)
363 (:import (com.jme3.scene Geometry Node Mesh))
364 (:import com.jme3.collision.CollisionResults)
365 (:import com.jme3.scene.VertexBuffer$Type)
366 (:import (com.jme3.math Triangle Vector3f Vector2f Ray Matrix4f)))
367 #+end_src
369 ;; Every Mesh has many triangles, each with its own index.
370 ;; Every vertex has its own index as well.
372 * Source Listing
373 * Next
376 * COMMENT Code Generation
377 #+begin_src clojure :tangle ../src/cortex/touch.clj
378 <<skin-main>>
379 #+end_src
381 #+begin_src clojure :tangle ../src/cortex/test/touch.clj
382 #+end_src