Mercurial > cortex
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 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.org9 * Touch11 Touch is critical to navigation and spatial reasoning and as such I12 need a simulated version of it to give to my AI creatures.14 However, touch in my virtual can not exactly correspond to human touch15 because my creatures are made out of completely rigid segments that16 don't deform like human skin.18 Human skin has a wide array of touch sensors, each of which speciliaze19 in detecting different vibrational modes and pressures. These sensors20 can integrate a vast expanse of skin (i.e. your entire palm), or a21 tiny patch of skin at the tip of your finger. The hairs of the skin22 help detect objects before they even come into contact with the skin23 proper.25 Instead of measuring deformation or vibration, I surround each rigid26 part with a plenitude of hair-like objects which do not interact with27 the physical world. Physical objects can pass through them with no28 effect. The hairs are able to measure contact with other objects, and29 constantly report how much of their extent is covered. So, even though30 the creature's body parts do not deform, the hairs create a margin31 around those body parts which achieves a sense of touch which is a32 hybrid between a human's sense of deformation and sense from hairs.34 Implementing touch in jMonkeyEngine follows a different techinal route35 than vision and hearing. Those two senses piggybacked off36 jMonkeyEngine's 3D audio and video rendering subsystems. To simulate37 Touch, I use jMonkeyEngine's physics system to execute many small38 collision detections, one for each "hair".40 * Sensor Related Functions41 #+begin_src clojure42 (defn sensors-in-triangle43 "Locate the touch sensors in the triangle, returning a map of their44 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-coords53 (filter (comp (partial inside-triangle? cutout-triangle)54 (fn [[u v]] (Vector3f. u v 0)))55 (white-coordinates image bounds))56 UV->geometry (triangle-transformation57 cutout-triangle58 (mesh-triangle mesh tri-index))59 geometry-sensor-coords60 (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-feelers65 "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 (map72 (partial sensors-in-triangle image mesh)73 (range num-triangles))74 (repeat (.getTriangleCount mesh) {:UV nil :geometry nil}))))76 (defn-memo touch-topology77 "Return a sequence of vectors of the form [x y] describing the78 \"topology\" of the tactile sensors. Points that are close together79 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-coordinates84 "The location of the touch sensors in world-space coordinates."85 [#^Geometry geo]86 (vec (map :geometry (locate-feelers geo))))87 #+end_src89 * Triangle Manipulation Functions91 #+begin_src clojure92 (defn triangles93 "Return a sequence of all the Triangles which compose a given94 Geometry."95 [#^Geometry geom]96 (let97 [mesh (.getMesh geom)98 triangles (transient [])]99 (dorun100 (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-triangle109 "Get the triangle specified by triangle-index from the mesh within110 bounds."111 [#^Mesh mesh triangle-index]112 (let [scratch (Triangle.)]113 (.getTriangle mesh triangle-index scratch)114 scratch))116 (defn triangle-vertex-indices117 "Get the triangle vertex indices of a given triangle from a given118 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-coord125 "Get the UV-coordinates of the vertex named by vertex-index"126 [#^Mesh mesh vertex-index]127 (let [UV-buffer128 (.getData129 (.getBuffer130 mesh131 VertexBuffer$Type/TexCoord))]132 [(.get UV-buffer (* vertex-index 2))133 (.get UV-buffer (+ 1 (* vertex-index 2)))]))135 (defn triangle-UV-coord136 "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_src143 * Schrapnel Conversion Functions144 #+begin_src clojure145 (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->triangle164 "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_src175 * Triangle Affine Transforms177 #+begin_src clojure178 (defn triangle->matrix4f179 "Converts the triangle into a 4x4 matrix: The first three columns180 contain the vertices of the triangle; the last contains the unit181 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 (dorun189 (for [row (range 4) col (range 3)]190 (do191 (.set mat col row (.get (vertices row)col))192 (.set mat 3 row 1))))193 mat))195 (defn triangle-transformation196 "Returns the affine transformation that converts each vertex in the197 first triangle into the corresponding vertex in the second198 triangle."199 [#^Triangle tri-1 #^Triangle tri-2]200 (.mult201 (triangle->matrix4f tri-2)202 (.invert (triangle->matrix4f tri-1))))203 #+end_src205 * Blender Meta-Data207 #+begin_src clojure208 (defn tactile-sensor-profile209 "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_src216 * Physics Collision Objects217 #+begin_src clojure218 (defn get-ray-origin219 "Return the origin which a Ray would have to have to be in the exact220 center of a particular Triangle in the Geometry in World221 Coordinates."222 [geom tri]223 (let [new (Vector3f.)]224 (.calculateCenter tri)225 (.localToWorld geom (.getCenter tri) new) new))227 (defn get-ray-direction228 "Return the direction which a Ray would have to have to be to point229 normal to the Triangle, in coordinates relative to the center of the230 Triangle."231 [geom tri]232 (let [n+c (Vector3f.)]233 (.calculateNormal tri)234 (.calculateCenter tri)235 (.localToWorld236 geom237 (.add (.getCenter tri) (.getNormal tri)) n+c)238 (.subtract n+c (get-ray-origin geom tri))))239 #+end_src241 * Triangle Boundaries242 #+begin_src clojure243 (defn same-side?244 "Given the points p1 and p2 and the reference point ref, is point p245 on the same side of the line that goes through p1 and p2 as ref is?"246 [p1 p2 ref p]247 (<=248 0249 (.dot250 (.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 (and259 (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-bounds264 "Returns the smallest square containing the given vertices, as a265 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_src276 * Skin Creation278 #+begin_src clojure279 (defn touch-fn280 "Returns a function which returns tactile sensory data when called281 inside a running simulation."282 [#^Geometry geo]283 (let [feeler-coords (feeler-coordinates geo)284 tris (triangles geo)285 limit 0.1286 ;;results (CollisionResults.)287 ]288 (if (empty? (touch-topology geo))289 nil290 (fn [node]291 (let [sensor-origins292 (map293 #(map (partial local-to-world geo) %)294 feeler-coords)295 triangle-normals296 (map (partial get-ray-direction geo)297 tris)298 rays299 (flatten300 (map (fn [origins norm]301 (map #(doto (Ray. % norm)302 (.setLimit limit)) origins))303 sensor-origins triangle-normals))]304 (vector305 (touch-topology geo)306 (vec307 (for [ray rays]308 (do309 (let [results (CollisionResults.)]310 (.collideWith node ray results)311 (let [touch-objects312 (filter #(not (= geo (.getGeometry %)))313 results)]314 (- 255315 (if (empty? touch-objects) 255316 (rem317 (int318 (* 255 (/ (.getDistance319 (first touch-objects)) limit)))320 256))))))))))))))322 (defn touch!323 "Endow the creature with the sense of touch. Returns a sequence of324 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 (filter328 (comp not nil?)329 (map touch-fn330 (filter #(isa? (class %) Geometry)331 (node-seq creature)))))332 #+end_src334 * Visualizing Touch336 #+begin_src clojure337 (defn view-touch338 "Creates a function which accepts a list of touch sensor-data and339 displays each element to the screen."340 []341 (view-sense342 (fn343 [[coords sensor-data]]344 (let [image (points->image coords)]345 (dorun346 (for [i (range (count coords))]347 (.setRGB image ((coords i) 0) ((coords i) 1)348 (gray (sensor-data i)))))349 image))))350 #+end_src352 * Headers353 #+begin_src clojure354 (ns cortex.touch355 "Simulate the sense of touch in jMonkeyEngine3. Enables any Geometry356 to be outfitted with touch sensors with density determined by a UV357 image. In this way a Geometry can know what parts of itself are358 touching nearby objects. Reads specially prepared blender files to359 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_src369 ;; Every Mesh has many triangles, each with its own index.370 ;; Every vertex has its own index as well.372 * Source Listing373 * Next376 * COMMENT Code Generation377 #+begin_src clojure :tangle ../src/cortex/touch.clj378 <<skin-main>>379 #+end_src381 #+begin_src clojure :tangle ../src/cortex/test/touch.clj382 #+end_src