Mercurial > cortex
view org/body.org @ 441:c20de2267d39
completeing first third of first chapter.
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Mon, 24 Mar 2014 20:59:35 -0400 |
parents | 4c37d39a3cf6 |
children | 42ddfe406c0a |
line wrap: on
line source
1 #+title: Building a Body2 #+author: Robert McIntyre3 #+email: rlm@mit.edu4 #+description: Simulating a body (movement, touch, proprioception) in jMonkeyEngine3.5 #+SETUPFILE: ../../aurellem/org/setup.org6 #+INCLUDE: ../../aurellem/org/level-0.org8 * Design Constraints10 I use [[www.blender.org/][blender]] to design bodies. The design of the bodies is11 determined by the requirements of the AI that will use them. The12 bodies must be easy for an AI to sense and control, and they must be13 relatively simple for jMonkeyEngine to compute.15 # I'm a secret test! :P16 ** Bag of Bones18 How to create such a body? One option I ultimately rejected is to use19 blender's [[http://wiki.blender.org/index.php/Doc:2.6/Manual/Rigging/Armatures][armature]] system. The idea would have been to define a mesh20 which describes the creature's entire body. To this you add an21 skeleton which deforms this mesh. This technique is used extensively22 to model humans and create realistic animations. It is hard to use for23 my purposes because it is difficult to update the creature's Physics24 Collision Mesh in tandem with its Geometric Mesh under the influence25 of the armature. Without this the creature will not be able to grab26 things in its environment, and it won't be able to tell where its27 physical body is by using its eyes. Also, armatures do not specify any28 rotational limits for a joint, making it hard to model elbows,29 shoulders, etc.31 ** EVE33 Instead of using the human-like "deformable bag of bones" approach, I34 decided to base my body plans on the robot EVE from the movie wall-E.36 #+caption: EVE from the movie WALL-E. This body plan turns out to be much better suited to my purposes than a more human-like one.37 [[../images/Eve.jpg]]39 EVE's body is composed of several rigid components that are held40 together by invisible joint constraints. This is what I mean by41 "eve-like". The main reason that I use eve-style bodies is so that42 there will be correspondence between the AI's vision and the physical43 presence of its body. Each individual section is simulated by a44 separate rigid body that corresponds exactly with its visual45 representation and does not change. Sections are connected by46 invisible joints that are well supported in jMonkeyEngine. Bullet, the47 physics backend for jMonkeyEngine, can efficiently simulate hundreds48 of rigid bodies connected by joints. Sections do not have to stay as49 one piece forever; they can be dynamically replaced with multiple50 sections to simulate splitting in two. This could be used to simulate51 retractable claws or EVE's hands, which are able to coalesce into one52 object in the movie.54 * Solidifying the Body56 Here is a hand designed eve-style in blender.58 #+attr_html: width="755"59 [[../images/hand-screenshot0.png]]61 If we load it directly into jMonkeyEngine, we get this:63 #+name: test-164 #+begin_src clojure65 (def hand-path "Models/test-creature/hand.blend")67 (defn hand [] (load-blender-model hand-path))69 (defn setup [world]70 (let [cam (.getCamera world)]71 (println-repl cam)72 (.setLocation73 cam (Vector3f.74 -6.9015837, 8.644911, 5.6043186))75 (.setRotation76 cam77 (Quaternion.78 0.14046453, 0.85894054, -0.34301838, 0.3533118)))79 (light-up-everything world)80 (.setTimer world (RatchetTimer. 60))81 world)83 (defn test-hand-184 ([] (test-hand-1 false))85 ([record?]86 (world (hand)87 standard-debug-controls88 (fn [world]89 (if record?90 (Capture/captureVideo91 world92 (File. "/home/r/proj/cortex/render/body/1")))93 (setup world)) no-op)))94 #+end_src97 #+begin_src clojure :results silent98 (.start (cortex.test.body/test-one))99 #+end_src101 #+begin_html102 <div class="figure">103 <center>104 <video controls="controls" width="640">105 <source src="../video/ghost-hand.ogg" type="video/ogg"106 preload="none" poster="../images/aurellem-1280x480.png" />107 </video>108 <br> <a href="http://youtu.be/9LZpwTIhjzE"> YouTube </a>109 </center>110 <p>The hand model directly loaded from blender. It has no physical111 presence in the simulation. </p>112 </div>113 #+end_html115 You will notice that the hand has no physical presence -- it's a116 hologram through which everything passes. Therefore, the first thing117 to do is to make it solid. Blender has physics simulation on par with118 jMonkeyEngine (they both use bullet as their physics backend), but it119 can be difficult to translate between the two systems, so for now I120 specify the mass of each object as meta-data in blender and construct121 the physics shape based on the mesh in jMonkeyEngine.123 #+name: body-1124 #+begin_src clojure125 (defn physical!126 "Iterate through the nodes in creature and make them real physical127 objects in the simulation."128 [#^Node creature]129 (dorun130 (map131 (fn [geom]132 (let [physics-control133 (RigidBodyControl.134 (HullCollisionShape.135 (.getMesh geom))136 (if-let [mass (meta-data geom "mass")]137 (do138 ;;(println-repl139 ;; "setting" (.getName geom) "mass to" (float mass))140 (float mass))141 (float 1)))]142 (.addControl geom physics-control)))143 (filter #(isa? (class %) Geometry )144 (node-seq creature)))))145 #+end_src147 =physical!= iterates through a creature's node structure, creating148 CollisionShapes for each geometry with the mass specified in that149 geometry's meta-data.151 #+name: test-2152 #+begin_src clojure153 (in-ns 'cortex.test.body)155 (def gravity-control156 {"key-g" (fn [world _]157 (set-gravity world (Vector3f. 0 -9.81 0)))158 "key-u" (fn [world _] (set-gravity world Vector3f/ZERO))})160 (defn floor []161 (box 10 3 10 :position (Vector3f. 0 -10 0)162 :color ColorRGBA/Gray :mass 0))164 (defn test-hand-2165 ([] (test-hand-2 false))166 ([record?]167 (world168 (nodify169 [(doto (hand)170 (physical!))171 (floor)])172 (merge standard-debug-controls gravity-control)173 (fn [world]174 (if record?175 (Capture/captureVideo176 world (File. "/home/r/proj/cortex/render/body/2")))177 (set-gravity world Vector3f/ZERO)178 (setup world))179 no-op)))180 #+end_src182 #+begin_html183 <div class="figure">184 <center>185 <video controls="controls" width="640">186 <source src="../video/crumbly-hand.ogg" type="video/ogg"187 preload="none" poster="../images/aurellem-1280x480.png" />188 </video>189 <br> <a href="http://youtu.be/GEA1SACwpPg"> YouTube </a>190 </center>191 <p>The hand now has a physical presence, but there is nothing to hold192 it together.</p>193 </div>194 #+end_html196 Now that's some progress.198 * Joints200 Obviously, an AI is not going to be doing much while lying in pieces201 on the floor. So, the next step to making a proper body is to connect202 those pieces together with joints. jMonkeyEngine has a large array of203 joints available via bullet, such as Point2Point, Cone, Hinge, and a204 generic Six Degree of Freedom joint, with or without spring205 restitution.207 Although it should be possible to specify the joints using blender's208 physics system, and then automatically import them with jMonkeyEngine,209 the support isn't there yet, and there are a few problems with bullet210 itself that need to be solved before it can happen.212 So, I will use the same system for specifying joints as I will do for213 some senses. Each joint is specified by an empty node whose parent214 has the name "joints". Their orientation and meta-data determine what215 joint is created.217 #+attr_html: width="755"218 #+caption: Joints hack in blender. Each empty node here will be transformed into a joint in jMonkeyEngine219 [[../images/hand-screenshot1.png]]221 The empty node in the upper right, highlighted in yellow, is the222 parent node of all the empties which represent joints. The following223 functions must do three things to translate these into real joints:225 - Find the children of the "joints" node.226 - Determine the two spatials the joint it meant to connect.227 - Create the joint based on the meta-data of the empty node.229 ** Finding the Joints231 The higher order function =sense-nodes= from =cortex.sense= simplifies232 the first task.234 #+name: joints-2235 #+begin_src clojure236 (def237 ^{:doc "Return the children of the creature's \"joints\" node."238 :arglists '([creature])}239 joints240 (sense-nodes "joints"))241 #+end_src243 ** Joint Targets and Orientation245 This technique for finding a joint's targets is very similar to246 =cortex.sense/closest-node=. A small cube, centered around the247 empty-node, grows exponentially until it intersects two /physical/248 objects. The objects are ordered according to the joint's rotation,249 with the first one being the object that has more negative coordinates250 in the joint's reference frame. Since the objects must be physical,251 the empty-node itself escapes detection. Because the objects must be252 physical, =joint-targets= must be called /after/ =physical!= is253 called.255 #+name: joints-3256 #+begin_src clojure257 (defn joint-targets258 "Return the two closest two objects to the joint object, ordered259 from bottom to top according to the joint's rotation."260 [#^Node parts #^Node joint]261 (loop [radius (float 0.01)]262 (let [results (CollisionResults.)]263 (.collideWith264 parts265 (BoundingBox. (.getWorldTranslation joint)266 radius radius radius) results)267 (let [targets268 (distinct269 (map #(.getGeometry %) results))]270 (if (>= (count targets) 2)271 (sort-by272 #(let [joint-ref-frame-position273 (jme-to-blender274 (.mult275 (.inverse (.getWorldRotation joint))276 (.subtract (.getWorldTranslation %)277 (.getWorldTranslation joint))))]278 (.dot (Vector3f. 1 1 1) joint-ref-frame-position))279 (take 2 targets))280 (recur (float (* radius 2))))))))281 #+end_src283 ** Generating Joints285 This section of code iterates through all the different ways of286 specifying joints using blender meta-data and converts each one to the287 appropriate jMonkeyEngine joint.289 #+name: joints-4290 #+begin_src clojure291 (defmulti joint-dispatch292 "Translate blender pseudo-joints into real JME joints."293 (fn [constraints & _]294 (:type constraints)))296 (defmethod joint-dispatch :point297 [constraints control-a control-b pivot-a pivot-b rotation]298 ;;(println-repl "creating POINT2POINT joint")299 ;; bullet's point2point joints are BROKEN, so we must use the300 ;; generic 6DOF joint instead of an actual Point2Point joint!302 ;; should be able to do this:303 (comment304 (Point2PointJoint.305 control-a306 control-b307 pivot-a308 pivot-b))310 ;; but instead we must do this:311 ;;(println-repl "substituting 6DOF joint for POINT2POINT joint!")312 (doto313 (SixDofJoint.314 control-a315 control-b316 pivot-a317 pivot-b318 false)319 (.setLinearLowerLimit Vector3f/ZERO)320 (.setLinearUpperLimit Vector3f/ZERO)))322 (defmethod joint-dispatch :hinge323 [constraints control-a control-b pivot-a pivot-b rotation]324 ;;(println-repl "creating HINGE joint")325 (let [axis326 (if-let327 [axis (:axis constraints)]328 axis329 Vector3f/UNIT_X)330 [limit-1 limit-2] (:limit constraints)331 hinge-axis332 (.mult333 rotation334 (blender-to-jme axis))]335 (doto336 (HingeJoint.337 control-a338 control-b339 pivot-a340 pivot-b341 hinge-axis342 hinge-axis)343 (.setLimit limit-1 limit-2))))345 (defmethod joint-dispatch :cone346 [constraints control-a control-b pivot-a pivot-b rotation]347 (let [limit-xz (:limit-xz constraints)348 limit-xy (:limit-xy constraints)349 twist (:twist constraints)]351 ;;(println-repl "creating CONE joint")352 ;;(println-repl rotation)353 ;;(println-repl354 ;; "UNIT_X --> " (.mult rotation (Vector3f. 1 0 0)))355 ;;(println-repl356 ;; "UNIT_Y --> " (.mult rotation (Vector3f. 0 1 0)))357 ;;(println-repl358 ;; "UNIT_Z --> " (.mult rotation (Vector3f. 0 0 1)))359 (doto360 (ConeJoint.361 control-a362 control-b363 pivot-a364 pivot-b365 rotation366 rotation)367 (.setLimit (float limit-xz)368 (float limit-xy)369 (float twist)))))371 (defn connect372 "Create a joint between 'obj-a and 'obj-b at the location of373 'joint. The type of joint is determined by the metadata on 'joint.375 Here are some examples:376 {:type :point}377 {:type :hinge :limit [0 (/ Math/PI 2)] :axis (Vector3f. 0 1 0)}378 (:axis defaults to (Vector3f. 1 0 0) if not provided for hinge joints)380 {:type :cone :limit-xz 0]381 :limit-xy 0]382 :twist 0]} (use XZY rotation mode in blender!)"383 [#^Node obj-a #^Node obj-b #^Node joint]384 (let [control-a (.getControl obj-a RigidBodyControl)385 control-b (.getControl obj-b RigidBodyControl)386 joint-center (.getWorldTranslation joint)387 joint-rotation (.toRotationMatrix (.getWorldRotation joint))388 pivot-a (world-to-local obj-a joint-center)389 pivot-b (world-to-local obj-b joint-center)]391 (if-let [constraints392 (map-vals393 eval394 (read-string395 (meta-data joint "joint")))]396 ;; A side-effect of creating a joint registers397 ;; it with both physics objects which in turn398 ;; will register the joint with the physics system399 ;; when the simulation is started.400 (do401 ;;(println-repl "creating joint between"402 ;; (.getName obj-a) "and" (.getName obj-b))403 (joint-dispatch constraints404 control-a control-b405 pivot-a pivot-b406 joint-rotation))407 ;;(println-repl "could not find joint meta-data!")408 )))409 #+end_src411 Creating joints is now a matter of applying =connect= to each joint412 node.414 #+name: joints-5415 #+begin_src clojure416 (defn joints!417 "Connect the solid parts of the creature with physical joints. The418 joints are taken from the \"joints\" node in the creature."419 [#^Node creature]420 (dorun421 (map422 (fn [joint]423 (let [[obj-a obj-b] (joint-targets creature joint)]424 (connect obj-a obj-b joint)))425 (joints creature))))426 #+end_src428 ** Round 3430 Now we can test the hand in all its glory.432 #+name: test-3433 #+begin_src clojure434 (in-ns 'cortex.test.body)436 (def debug-control437 {"key-h" (fn [world val]438 (if val (enable-debug world)))})440 (defn test-hand-3441 ([] (test-hand-3 false))442 ([record?]443 (world444 (nodify445 [(doto (hand)446 (physical!)447 (joints!))448 (floor)])449 (merge standard-debug-controls debug-control450 gravity-control)451 (comp452 #(Capture/captureVideo453 % (File. "/home/r/proj/cortex/render/body/3"))454 #(do (set-gravity % Vector3f/ZERO) %)455 setup)456 no-op)))457 #+end_src459 =physical!= makes the hand solid, then =joints!= connects each460 piece together.462 #+begin_html463 <div class="figure">464 <center>465 <video controls="controls" width="640">466 <source src="../video/full-hand.ogg" type="video/ogg"467 preload="none" poster="../images/aurellem-1280x480.png" />468 </video>469 <br> <a href="http://youtu.be/4affLfwSPP4"> YouTube </a>470 </center>471 <p>Now the hand is physical and has joints.</p>472 </div>473 #+end_html475 The joints are visualized as green connections between each segment476 for debug purposes. You can see that they correspond to the empty477 nodes in the blender file.479 * Wrap-Up!481 It is convenient to combine =physical!= and =joints!= into one482 function that completely creates the creature's physical body.484 #+name: joints-6485 #+begin_src clojure486 (defn body!487 "Endow the creature with a physical body connected with joints. The488 particulars of the joints and the masses of each body part are489 determined in blender."490 [#^Node creature]491 (physical! creature)492 (joints! creature))493 #+end_src495 * The Worm497 Going forward, I will use a model that is less complicated than the498 hand. It has two segments and one joint, and I call it the worm. All499 of the senses described in the following posts will be applied to this500 worm.502 #+name: test-4503 #+begin_src clojure504 (in-ns 'cortex.test.body)506 (defn worm []507 (load-blender-model508 "Models/test-creature/worm.blend"))510 (defn test-worm512 "Testing physical bodies:513 You should see the the worm fall onto a table. You can fire514 physical balls at it and the worm should move upon being struck.516 Keys:517 <space> : fire cannon ball."519 ([] (test-worm false))520 ([record?]521 (let [timer (RatchetTimer. 60)]522 (world523 (nodify524 [(doto (worm)525 (body!))526 (floor)])527 (merge standard-debug-controls debug-control)528 #(do529 (speed-up %)530 (light-up-everything %)531 (.setTimer % timer)532 (cortex.util/display-dilated-time % timer)533 (if record?534 (Capture/captureVideo535 % (File. "/home/r/proj/cortex/render/body/4"))))536 no-op))))537 #+end_src539 #+results: test-4540 : #'cortex.test.body/test-worm542 #+begin_html543 <div class="figure">544 <center>545 <video controls="controls" width="640">546 <source src="../video/worm-1.ogg" type="video/ogg"547 preload="none" poster="../images/aurellem-1280x480.png" />548 </video>549 <br> <a href="http://youtu.be/rFVXI0T3iSE"> YouTube </a>550 </center>551 <p>This worm model will be the platform onto which future senses will552 be grafted.</p>553 </div>554 #+end_html556 * Headers557 #+name: body-header558 #+begin_src clojure559 (ns cortex.body560 "Assemble a physical creature using the definitions found in a561 specially prepared blender file. Creates rigid bodies and joints so562 that a creature can have a physical presence in the simulation."563 {:author "Robert McIntyre"}564 (:use (cortex world util sense))565 (:import566 (com.jme3.math Vector3f Quaternion Vector2f Matrix3f)567 (com.jme3.bullet.joints568 SixDofJoint Point2PointJoint HingeJoint ConeJoint)569 com.jme3.bullet.control.RigidBodyControl570 com.jme3.collision.CollisionResults571 com.jme3.bounding.BoundingBox572 com.jme3.scene.Node573 com.jme3.scene.Geometry574 com.jme3.bullet.collision.shapes.HullCollisionShape))575 #+end_src577 #+name: test-header578 #+begin_src clojure579 (ns cortex.test.body580 (:use (cortex world util body))581 (:import582 (com.aurellem.capture Capture RatchetTimer IsoTimer)583 (com.jme3.math Quaternion Vector3f ColorRGBA)584 java.io.File))585 #+end_src587 #+results: test-header588 : java.io.File590 * Source591 - [[../src/cortex/body.clj][cortex.body]]592 - [[../src/cortex/test/body.clj][cortex.test.body]]593 - [[../assets/Models/test-creature/hand.blend][hand.blend]]594 - [[../assets/Models/test-creature/palm.png][UV-map-1]]595 - [[../assets/Models/test-creature/worm.blend][worm.blend]]596 - [[../assets/Models/test-creature/retina-small.png][UV-map-1]]597 - [[../assets/Models/test-creature/tip.png][UV-map-2]]598 #+html: <ul> <li> <a href="../org/body.org">This org file</a> </li> </ul>599 - [[http://hg.bortreb.com ][source-repository]]601 * Next602 The body I have made here exists without any senses or effectors. In603 the [[./vision.org][next post]], I'll give the creature eyes.605 * COMMENT Generate Source606 #+begin_src clojure :tangle ../src/cortex/body.clj607 <<body-header>>608 <<body-1>>609 <<joints-2>>610 <<joints-3>>611 <<joints-4>>612 <<joints-5>>613 <<joints-6>>614 #+end_src616 #+begin_src clojure :tangle ../src/cortex/test/body.clj617 <<test-header>>618 <<test-1>>619 <<test-2>>620 <<test-3>>621 <<test-4>>622 #+end_src