Mercurial > cortex
view org/body.org @ 276:54ec231dec4c
I changed Capture Video, then merged with Robert.
author | Dylan Holmes <ocsenave@gmail.com> |
---|---|
date | Wed, 15 Feb 2012 01:16:54 -0600 |
parents | c39b8b29a79e |
children | 23aadf376e9d |
line wrap: on
line source
1 #+title: Building a Body2 #+author: Robert McIntyre3 #+email: rlm@mit.edu4 #+description: Simulating a body (movement, touch, propioception) 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. Withouth 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 specify28 any 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 jMonkyeEngine. 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 coalece 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-one []84 (world (hand)85 standard-debug-controls86 (comp87 #(Capture/captureVideo88 % (File. "/home/r/proj/cortex/render/body/1"))89 setup)90 no-op))91 #+end_src94 #+begin_src clojure :results silent95 (.start (cortex.test.body/test-one))96 #+end_src98 #+begin_html99 <div class="figure">100 <center>101 <video controls="controls" width="640">102 <source src="../video/ghost-hand.ogg" type="video/ogg"103 preload="none" poster="../images/aurellem-1280x480.png" />104 </video>105 </center>106 <p>The hand model directly loaded from blender. It has no physical107 presense in the simulation. </p>108 </div>109 #+end_html111 You will notice that the hand has no physical presence -- it's a112 hologram through which everything passes. Therefore, the first thing113 to do is to make it solid. Blender has physics simulation on par with114 jMonkeyEngine (they both use bullet as their physics backend), but it115 can be difficult to translate between the two systems, so for now I116 specify the mass of each object as meta-data in blender and construct117 the physics shape based on the mesh in jMonkeyEngine.119 #+name: body-1120 #+begin_src clojure121 (defn physical!122 "Iterate through the nodes in creature and make them real physical123 objects in the simulation."124 [#^Node creature]125 (dorun126 (map127 (fn [geom]128 (let [physics-control129 (RigidBodyControl.130 (HullCollisionShape.131 (.getMesh geom))132 (if-let [mass (meta-data geom "mass")]133 (do134 (println-repl135 "setting" (.getName geom) "mass to" (float mass))136 (float mass))137 (float 1)))]138 (.addControl geom physics-control)))139 (filter #(isa? (class %) Geometry )140 (node-seq creature)))))141 #+end_src143 =physical!)= iterates through a creature's node structure, creating144 CollisionShapes for each geometry with the mass specified in that145 geometry's meta-data.147 #+name: test-2148 #+begin_src clojure149 (in-ns 'cortex.test.body)151 (def gravity-control152 {"key-g" (fn [world _]153 (set-gravity world (Vector3f. 0 -9.81 0)))154 "key-u" (fn [world _] (set-gravity world Vector3f/ZERO))})157 (defn floor []158 (box 10 3 10 :position (Vector3f. 0 -10 0)159 :color ColorRGBA/Gray :mass 0))161 (defn test-two []162 (world (nodify163 [(doto (hand)164 (physical!))165 (floor)])166 (merge standard-debug-controls gravity-control)167 (comp168 #(Capture/captureVideo169 % (File. "/home/r/proj/cortex/render/body/2"))170 #(do (set-gravity % Vector3f/ZERO) %)171 setup)172 no-op))173 #+end_src175 #+begin_html176 <div class="figure">177 <center>178 <video controls="controls" width="640">179 <source src="../video/crumbly-hand.ogg" type="video/ogg"180 preload="none" poster="../images/aurellem-1280x480.png" />181 </video>182 </center>183 <p>The hand now has a physical presence, but there is nothing to hold184 it together.</p>185 </div>186 #+end_html188 Now that's some progress.190 * Joints192 Obviously, an AI is not going to be doing much while lying in pieces193 on the floor. So, the next step to making a proper body is to connect194 those pieces together with joints. jMonkeyEngine has a large array of195 joints available via bullet, such as Point2Point, Cone, Hinge, and a196 generic Six Degree of Freedom joint, with or without spring197 restitution.199 Although it should be possible to specify the joints using blender's200 physics system, and then automatically import them with jMonkeyEngine,201 the support isn't there yet, and there are a few problems with bullet202 itself that need to be solved before it can happen.204 So, I will use the same system for specifying joints as I will do for205 some senses. Each joint is specified by an empty node whose parent206 has the name "joints". Their orientation and meta-data determine what207 joint is created.209 #+attr_html: width="755"210 #+caption: Joints hack in blender. Each empty node here will be transformed into a joint in jMonkeyEngine211 [[../images/hand-screenshot1.png]]213 The empty node in the upper right, highlighted in yellow, is the214 parent node of all the emptys which represent joints. The following215 functions must do three things to translate these into real joints:217 - Find the children of the "joints" node.218 - Determine the two spatials the joint it meant to connect.219 - Create the joint based on the meta-data of the empty node.221 ** Finding the Joints223 The higher order function =sense-nodes= from =cortex.sense= simplifies224 the first task.226 #+name: joints-2227 #+begin_src clojure228 (defvar229 ^{:arglists '([creature])}230 joints231 (sense-nodes "joints")232 "Return the children of the creature's \"joints\" node.")233 #+end_src235 ** Joint Targets and Orientation237 This technique for finding a joint's targets is very similiar to238 =cortex.sense/closest-node=. A small cube, centered around the239 empty-node, grows exponentially until it intersects two /physical/240 objects. The objects are ordered according to the joint's rotation,241 with the first one being the object that has more negative coordinates242 in the joint's reference frame. Since the objects must be physical,243 the empty-node itself escapes detection. Because the objects must be244 physical, =joint-targets= must be called /after/ =physical!= is245 called.247 #+name: joints-3248 #+begin_src clojure249 (defn joint-targets250 "Return the two closest two objects to the joint object, ordered251 from bottom to top according to the joint's rotation."252 [#^Node parts #^Node joint]253 (loop [radius (float 0.01)]254 (let [results (CollisionResults.)]255 (.collideWith256 parts257 (BoundingBox. (.getWorldTranslation joint)258 radius radius radius) results)259 (let [targets260 (distinct261 (map #(.getGeometry %) results))]262 (if (>= (count targets) 2)263 (sort-by264 #(let [joint-ref-frame-position265 (jme-to-blender266 (.mult267 (.inverse (.getWorldRotation joint))268 (.subtract (.getWorldTranslation %)269 (.getWorldTranslation joint))))]270 (.dot (Vector3f. 1 1 1) joint-ref-frame-position))271 (take 2 targets))272 (recur (float (* radius 2))))))))273 #+end_src275 ** Generating Joints277 This section of code iterates through all the different ways of278 specifying joints using blender meta-data and converts each one to the279 appropriate jMonkyeEngine joint.281 #+name: joints-4282 #+begin_src clojure283 (defmulti joint-dispatch284 "Translate blender pseudo-joints into real JME joints."285 (fn [constraints & _]286 (:type constraints)))288 (defmethod joint-dispatch :point289 [constraints control-a control-b pivot-a pivot-b rotation]290 (println-repl "creating POINT2POINT joint")291 ;; bullet's point2point joints are BROKEN, so we must use the292 ;; generic 6DOF joint instead of an actual Point2Point joint!294 ;; should be able to do this:295 (comment296 (Point2PointJoint.297 control-a298 control-b299 pivot-a300 pivot-b))302 ;; but instead we must do this:303 (println-repl "substuting 6DOF joint for POINT2POINT joint!")304 (doto305 (SixDofJoint.306 control-a307 control-b308 pivot-a309 pivot-b310 false)311 (.setLinearLowerLimit Vector3f/ZERO)312 (.setLinearUpperLimit Vector3f/ZERO)))314 (defmethod joint-dispatch :hinge315 [constraints control-a control-b pivot-a pivot-b rotation]316 (println-repl "creating HINGE joint")317 (let [axis318 (if-let319 [axis (:axis constraints)]320 axis321 Vector3f/UNIT_X)322 [limit-1 limit-2] (:limit constraints)323 hinge-axis324 (.mult325 rotation326 (blender-to-jme axis))]327 (doto328 (HingeJoint.329 control-a330 control-b331 pivot-a332 pivot-b333 hinge-axis334 hinge-axis)335 (.setLimit limit-1 limit-2))))337 (defmethod joint-dispatch :cone338 [constraints control-a control-b pivot-a pivot-b rotation]339 (let [limit-xz (:limit-xz constraints)340 limit-xy (:limit-xy constraints)341 twist (:twist constraints)]343 (println-repl "creating CONE joint")344 (println-repl rotation)345 (println-repl346 "UNIT_X --> " (.mult rotation (Vector3f. 1 0 0)))347 (println-repl348 "UNIT_Y --> " (.mult rotation (Vector3f. 0 1 0)))349 (println-repl350 "UNIT_Z --> " (.mult rotation (Vector3f. 0 0 1)))351 (doto352 (ConeJoint.353 control-a354 control-b355 pivot-a356 pivot-b357 rotation358 rotation)359 (.setLimit (float limit-xz)360 (float limit-xy)361 (float twist)))))363 (defn connect364 "Create a joint between 'obj-a and 'obj-b at the location of365 'joint. The type of joint is determined by the metadata on 'joint.367 Here are some examples:368 {:type :point}369 {:type :hinge :limit [0 (/ Math/PI 2)] :axis (Vector3f. 0 1 0)}370 (:axis defaults to (Vector3f. 1 0 0) if not provided for hinge joints)372 {:type :cone :limit-xz 0]373 :limit-xy 0]374 :twist 0]} (use XZY rotation mode in blender!)"375 [#^Node obj-a #^Node obj-b #^Node joint]376 (let [control-a (.getControl obj-a RigidBodyControl)377 control-b (.getControl obj-b RigidBodyControl)378 joint-center (.getWorldTranslation joint)379 joint-rotation (.toRotationMatrix (.getWorldRotation joint))380 pivot-a (world-to-local obj-a joint-center)381 pivot-b (world-to-local obj-b joint-center)]383 (if-let [constraints384 (map-vals385 eval386 (read-string387 (meta-data joint "joint")))]388 ;; A side-effect of creating a joint registers389 ;; it with both physics objects which in turn390 ;; will register the joint with the physics system391 ;; when the simulation is started.392 (do393 (println-repl "creating joint between"394 (.getName obj-a) "and" (.getName obj-b))395 (joint-dispatch constraints396 control-a control-b397 pivot-a pivot-b398 joint-rotation))399 (println-repl "could not find joint meta-data!"))))400 #+end_src402 Creating joints is now a matter of applying =connect= to each joint403 node.405 #+name: joints-5406 #+begin_src clojure407 (defn joints!408 "Connect the solid parts of the creature with physical joints. The409 joints are taken from the \"joints\" node in the creature."410 [#^Node creature]411 (dorun412 (map413 (fn [joint]414 (let [[obj-a obj-b] (joint-targets creature joint)]415 (connect obj-a obj-b joint)))416 (joints creature))))417 #+end_src419 ** Round 3421 Now we can test the hand in all its glory.423 #+name: test-3424 #+begin_src clojure425 (in-ns 'cortex.test.body)427 (def debug-control428 {"key-h" (fn [world val]429 (if val (enable-debug world)))})431 (defn test-three []432 (world (nodify433 [(doto (hand)434 (physical!)435 (joints!))436 (floor)])437 (merge standard-debug-controls debug-control438 gravity-control)439 (comp440 #(Capture/captureVideo441 % (File. "/home/r/proj/cortex/render/body/3"))442 #(do (set-gravity % Vector3f/ZERO) %)443 setup)444 no-op))445 #+end_src447 =physical!= makes the hand solid, then =joints!= connects each448 piece together.450 #+begin_html451 <div class="figure">452 <center>453 <video controls="controls" width="640">454 <source src="../video/full-hand.ogg" type="video/ogg"455 preload="none" poster="../images/aurellem-1280x480.png" />456 </video>457 </center>458 <p>Now the hand is physical and has joints.</p>459 </div>460 #+end_html462 The joints are visualized as green connections between each segment463 for debug purposes. You can see that they correspond to the empty464 nodes in the blender file.466 * Wrap-Up!468 It is convienent to combine =physical!= and =joints!= into one469 function that completely creates the creature's physical body.471 #+name: joints-6472 #+begin_src clojure473 (defn body!474 "Endow the creature with a physical body connected with joints. The475 particulars of the joints and the masses of each pody part are476 determined in blender."477 [#^Node creature]478 (physical! creature)479 (joints! creature))480 #+end_src482 * The Worm484 Going forward, I will use a model that is less complicated than the485 hand. It has two segments and one joint, and I call it the worm. All486 of the senses described in the following posts will be applied to this487 worm.489 #+name: test-4490 #+begin_src clojure491 (in-ns 'cortex.test.body)493 (defn worm []494 (load-blender-model495 "Models/test-creature/worm.blend"))497 (defn worm-1 []498 (let [timer (RatchetTimer. 60)]499 (world500 (nodify501 [(doto (worm)502 (body!))503 (floor)])504 (merge standard-debug-controls debug-control)505 #(do506 (speed-up %)507 (light-up-everything %)508 (.setTimer % timer)509 (cortex.util/display-dialated-time % timer)510 (Capture/captureVideo511 % (File. "/home/r/proj/cortex/render/body/4")))512 no-op)))513 #+end_src515 #+begin_html516 <div class="figure">517 <center>518 <video controls="controls" width="640">519 <source src="../video/worm-1.ogg" type="video/ogg"520 preload="none" poster="../images/aurellem-1280x480.png" />521 </video>522 </center>523 <p>This worm model will be the platform onto which future senses will524 be grafted.</p>525 </div>526 #+end_html528 * Headers529 #+name: body-header530 #+begin_src clojure531 (ns cortex.body532 "Assemble a physical creature using the definitions found in a533 specially prepared blender file. Creates rigid bodies and joints so534 that a creature can have a physical presense in the simulation."535 {:author "Robert McIntyre"}536 (:use (cortex world util sense))537 (:use clojure.contrib.def)538 (:import539 (com.jme3.math Vector3f Quaternion Vector2f Matrix3f)540 (com.jme3.bullet.joints541 SixDofJoint Point2PointJoint HingeJoint ConeJoint)542 com.jme3.bullet.control.RigidBodyControl543 com.jme3.collision.CollisionResults544 com.jme3.bounding.BoundingBox545 com.jme3.scene.Node546 com.jme3.scene.Geometry547 com.jme3.bullet.collision.shapes.HullCollisionShape))548 #+end_src550 #+name: test-header551 #+begin_src clojure552 (ns cortex.test.body553 (:use (cortex world util body))554 (:import555 (com.aurellem.capture Capture RatchetTimer)556 (com.jme3.math Quaternion Vector3f ColorRGBA)557 java.io.File))558 #+end_src560 * Source561 - [[../src/cortex/body.clj][cortex.body]]562 - [[../src/cortex/test/body.clj][cortex.test.body]]563 - [[../assets/Models/test-creature/hand.blend][hand.blend]]564 - [[../assets/Models/test-creature/palm.png][UV-map-1]]565 - [[../assets/Models/test-creature/worm.blend][worm.blend]]566 - [[../assets/Models/test-creature/retina-small.png][UV-map-1]]567 - [[../assets/Models/test-creature/tip.png][UV-map-2]]568 #+html: <ul> <li> <a href="../org/body.org">This org file</a> </li> </ul>569 - [[http://hg.bortreb.com ][source-repository]]571 * Next572 The body I have made here exists without any senses or effectors. In573 the [[./vision.org][next post]], I'll give the creature eyes.575 * COMMENT Generate Source576 #+begin_src clojure :tangle ../src/cortex/body.clj577 <<body-header>>578 <<body-1>>579 <<joints-2>>580 <<joints-3>>581 <<joints-4>>582 <<joints-5>>583 <<joints-6>>584 #+end_src586 #+begin_src clojure :tangle ../src/cortex/test/body.clj587 <<test-header>>588 <<test-1>>589 <<test-2>>590 <<test-3>>591 <<test-4>>592 #+end_src