Mercurial > cortex
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 Touch2 #+author: Robert McIntyre3 #+email: rlm@mit.edu4 #+description: Simulated touch for AI research using JMonkeyEngine and clojure.5 #+keywords: simulation, tactile sense, jMonkeyEngine3, clojure6 #+SETUPFILE: ../../aurellem/org/setup.org7 #+INCLUDE: ../../aurellem/org/level-0.org11 * Touch13 Touch is critical to navigation and spatial reasoning and as such I14 need a simulated version of it to give to my AI creatures.16 However, touch in my virtual can not exactly correspond to human touch17 because my creatures are made out of completely rigid segments that18 don't deform like human skin.20 Human skin has a wide array of touch sensors, each of which speciliaze21 in detecting different vibrational modes and pressures. These sensors22 can integrate a vast expanse of skin (i.e. your entire palm), or a23 tiny patch of skin at the tip of your finger. The hairs of the skin24 help detect objects before they even come into contact with the skin25 proper.27 Instead of measuring deformation or vibration, I surround each rigid28 part with a plenitude of hair-like objects which do not interact with29 the physical world. Physical objects can pass through them with no30 effect. The hairs are able to measure contact with other objects, and31 constantly report how much of their extent is covered. So, even though32 the creature's body parts do not deform, the hairs create a margin33 around those body parts which achieves a sense of touch which is a34 hybrid between a human's sense of deformation and sense from hairs.36 Implementing touch in jMonkeyEngine follows a different techinal route37 than vision and hearing. Those two senses piggybacked off38 jMonkeyEngine's 3D audio and video rendering subsystems. To simulate39 Touch, I use jMonkeyEngine's physics system to execute many small40 collision detections, one for each "hair". The placement of the41 "hairs" is determined by a UV-mapped image which shows where each hair42 should be on the 3D surface of the body.45 * Defining Touch Meta-Data in Blender47 Each geometry can have a single UV map which describes the position48 and length of the "hairs" which will constitute its sense of49 touch. This image path is stored under the "touch" key. The image50 itself is grayscale, with black meaning a hair length of 0 (no hair is51 present) and white meaning a hair length of =scale=, which is a float52 stored under the key "scale". If the pixel is gray then the resultant53 hair length is linearly interpolated between 0 and =scale=.55 #+name: meta-data56 #+begin_src clojure57 (defn tactile-sensor-profile58 "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_src66 ** TODO add image showing example touch-uv map67 ** TODO add metadata display for worm69 * Triangle Manipulation Functions71 The rigid bodies which make up a creature have an underlying72 =Geometry=, which is a =Mesh= plus a =Material= and other important73 data involved with displaying the body.75 A =Mesh= is composed of =Triangles=, and each =Triangle= has three76 verticies which have coordinates in XYZ space and UV space.78 Here, =(triangles)= gets all the triangles which compose a mesh, and79 =(triangle-UV-coord)= returns the the UV coordinates of the verticies80 of a triangle.82 #+name: triangles-183 #+begin_src clojure84 (defn triangles85 "Return a sequence of all the Triangles which compose a given86 Geometry."87 [#^Geometry geom]88 (let89 [mesh (.getMesh geom)90 triangles (transient [])]91 (dorun92 (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-triangle101 "Get the triangle specified by triangle-index from the mesh within102 bounds."103 [#^Mesh mesh triangle-index]104 (let [scratch (Triangle.)]105 (.getTriangle mesh triangle-index scratch)106 scratch))108 (defn triangle-vertex-indices109 "Get the triangle vertex indices of a given triangle from a given110 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-coord117 "Get the UV-coordinates of the vertex named by vertex-index"118 [#^Mesh mesh vertex-index]119 (let [UV-buffer120 (.getData121 (.getBuffer122 mesh123 VertexBuffer$Type/TexCoord))]124 [(.get UV-buffer (* vertex-index 2))125 (.get UV-buffer (+ 1 (* vertex-index 2)))]))127 (defn triangle-UV-coord128 "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_src135 * Schrapnel Conversion Functions137 It is convienent to treat a =Triangle= as a sequence of verticies, and138 a =Vector2f= and =Vector3f= as a sequence of floats. These conversion139 functions make this easy. If these classes implemented =Iterable= then140 this code would not be necessary. Hopefully they will in the future.142 #+name: triangles-2143 #+begin_src clojure144 (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->triangle163 "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_src174 * Triangle Affine Transforms176 The position of each hair is stored in a 2D image in UV177 coordinates. To place the hair in 3D space we must convert from UV178 coordinates to XYZ coordinates. Each =Triangle= has coordinates in179 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 the181 cooresponding coordinate in the XYZ triangle.183 #+name: triangles-3184 #+begin_src clojure185 (defn triangle->matrix4f186 "Converts the triangle into a 4x4 matrix: The first three columns187 contain the vertices of the triangle; the last contains the unit188 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 (dorun196 (for [row (range 4) col (range 3)]197 (do198 (.set mat col row (.get (vertices row)col))199 (.set mat 3 row 1))))200 mat))202 (defn triangle-transformation203 "Returns the affine transformation that converts each vertex in the204 first triangle into the corresponding vertex in the second205 triangle."206 [#^Triangle tri-1 #^Triangle tri-2]207 (.mult208 (triangle->matrix4f tri-2)209 (.invert (triangle->matrix4f tri-1))))210 #+end_src212 * Triangle Boundaries214 For efficiency's sake I will divide the UV-image into small squares215 which inscribe each UV-triangle, then extract the points which lie216 inside the triangle and map them to 3D-space using217 =(triangle-transform)= above. To do this I need a function,218 =(inside-triangle?)=, which determines whether a point is inside a219 triangle in 2D UV-space.221 #+name: triangles-4222 #+begin_src clojure223 (defn convex-bounds224 "Returns the smallest square containing the given vertices, as a225 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 p237 on the same side of the line that goes through p1 and p2 as ref is?"238 [p1 p2 ref p]239 (<=240 0241 (.dot242 (.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 (and251 (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_src258 * Sensor Related Functions260 These functions analyze the touch-sensor-profile image convert the261 location of each touch sensor from pixel coordinates to UV-coordinates262 and XYZ-coordinates.264 #+name: sensors265 #+begin_src clojure266 (defn sensors-in-triangle267 "Locate the touch sensors in the triangle, returning a map of their268 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-coords277 (filter (comp (partial inside-triangle? cutout-triangle)278 (fn [[u v]] (Vector3f. u v 0)))279 (white-coordinates image bounds))280 UV->geometry (triangle-transformation281 cutout-triangle282 (mesh-triangle mesh tri-index))283 geometry-sensor-coords284 (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-feelers289 "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 (map296 (partial sensors-in-triangle image mesh)297 (range num-triangles))298 (repeat (.getTriangleCount mesh) {:UV nil :geometry nil}))))300 (defn-memo touch-topology301 "Return a sequence of vectors of the form [x y] describing the302 \"topology\" of the tactile sensors. Points that are close together303 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-coordinates308 "The location of the touch sensors in world-space coordinates."309 [#^Geometry geo]310 (vec (map :geometry (locate-feelers geo))))311 #+end_src313 * Physics Collision Objects315 The "hairs" are actually rays which extend from a point on a316 =Triangle= in the =Mesh= normal to the =Triangle's= surface.318 #+name: rays319 #+begin_src clojure320 (defn get-ray-origin321 "Return the origin which a Ray would have to have to be in the exact322 center of a particular Triangle in the Geometry in World323 Coordinates."324 [geom tri]325 (let [new (Vector3f.)]326 (.calculateCenter tri)327 (.localToWorld geom (.getCenter tri) new) new))329 (defn get-ray-direction330 "Return the direction which a Ray would have to have to be to point331 normal to the Triangle, in coordinates relative to the center of the332 Triangle."333 [geom tri]334 (let [n+c (Vector3f.)]335 (.calculateNormal tri)336 (.calculateCenter tri)337 (.localToWorld338 geom339 (.add (.getCenter tri) (.getNormal tri)) n+c)340 (.subtract n+c (get-ray-origin geom tri))))341 #+end_src344 * Skin Creation345 #+name: kernel346 #+begin_src clojure347 (defn touch-fn348 "Returns a function which returns tactile sensory data when called349 inside a running simulation."350 [#^Geometry geo]351 (let [feeler-coords (feeler-coordinates geo)352 tris (triangles geo)353 limit 0.1354 ;;results (CollisionResults.)355 ]356 (if (empty? (touch-topology geo))357 nil358 (fn [node]359 (let [sensor-origins360 (map361 #(map (partial local-to-world geo) %)362 feeler-coords)363 triangle-normals364 (map (partial get-ray-direction geo)365 tris)366 rays367 (flatten368 (map (fn [origins norm]369 (map #(doto (Ray. % norm)370 (.setLimit limit)) origins))371 sensor-origins triangle-normals))]372 (vector373 (touch-topology geo)374 (vec375 (for [ray rays]376 (do377 (let [results (CollisionResults.)]378 (.collideWith node ray results)379 (let [touch-objects380 (filter #(not (= geo (.getGeometry %)))381 results)]382 (- 255383 (if (empty? touch-objects) 255384 (rem385 (int386 (* 255 (/ (.getDistance387 (first touch-objects)) limit)))388 256))))))))))))))390 (defn touch!391 "Endow the creature with the sense of touch. Returns a sequence of392 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 (filter396 (comp not nil?)397 (map touch-fn398 (filter #(isa? (class %) Geometry)399 (node-seq creature)))))400 #+end_src402 * Visualizing Touch403 #+name: visualization404 #+begin_src clojure405 (defn view-touch406 "Creates a function which accepts a list of touch sensor-data and407 displays each element to the screen."408 []409 (view-sense410 (fn411 [[coords sensor-data]]412 (let [image (points->image coords)]413 (dorun414 (for [i (range (count coords))]415 (.setRGB image ((coords i) 0) ((coords i) 1)416 (gray (sensor-data i)))))417 image))))418 #+end_src420 * Headers422 #+name: touch-header423 #+begin_src clojure424 (ns cortex.touch425 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry426 to be outfitted with touch sensors with density determined by a UV427 image. In this way a Geometry can know what parts of itself are428 touching nearby objects. Reads specially prepared blender files to429 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_src440 * Source Listing441 * Next444 * COMMENT Code Generation445 #+begin_src clojure :tangle ../src/cortex/touch.clj446 <<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_src458 #+begin_src clojure :tangle ../src/cortex/test/touch.clj459 #+end_src