view org/body.org @ 321:702b5c78c2de

gathered all the tests into (run-suite), which should make testing vastly easier.
author Robert McIntyre <rlm@mit.edu>
date Tue, 08 May 2012 08:22:19 -0500
parents bb3f8a4af87f
children 4f5a5d5f1613
line wrap: on
line source
1 #+title: Building a Body
2 #+author: Robert McIntyre
3 #+email: rlm@mit.edu
4 #+description: Simulating a body (movement, touch, proprioception) in jMonkeyEngine3.
5 #+SETUPFILE: ../../aurellem/org/setup.org
6 #+INCLUDE: ../../aurellem/org/level-0.org
8 * Design Constraints
10 I use [[www.blender.org/][blender]] to design bodies. The design of the bodies is
11 determined by the requirements of the AI that will use them. The
12 bodies must be easy for an AI to sense and control, and they must be
13 relatively simple for jMonkeyEngine to compute.
15 # I'm a secret test! :P
16 ** Bag of Bones
18 How to create such a body? One option I ultimately rejected is to use
19 blender's [[http://wiki.blender.org/index.php/Doc:2.6/Manual/Rigging/Armatures][armature]] system. The idea would have been to define a mesh
20 which describes the creature's entire body. To this you add an
21 skeleton which deforms this mesh. This technique is used extensively
22 to model humans and create realistic animations. It is hard to use for
23 my purposes because it is difficult to update the creature's Physics
24 Collision Mesh in tandem with its Geometric Mesh under the influence
25 of the armature. Without this the creature will not be able to grab
26 things in its environment, and it won't be able to tell where its
27 physical body is by using its eyes. Also, armatures do not specify
28 any rotational limits for a joint, making it hard to model elbows,
29 shoulders, etc.
31 ** EVE
33 Instead of using the human-like "deformable bag of bones" approach, I
34 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 held
40 together by invisible joint constraints. This is what I mean by
41 "eve-like". The main reason that I use eve-style bodies is so that
42 there will be correspondence between the AI's vision and the physical
43 presence of its body. Each individual section is simulated by a
44 separate rigid body that corresponds exactly with its visual
45 representation and does not change. Sections are connected by
46 invisible joints that are well supported in jMonkeyEngine. Bullet, the
47 physics backend for jMonkeyEngine, can efficiently simulate hundreds
48 of rigid bodies connected by joints. Sections do not have to stay as
49 one piece forever; they can be dynamically replaced with multiple
50 sections to simulate splitting in two. This could be used to simulate
51 retractable claws or EVE's hands, which are able to coalesce into one
52 object in the movie.
54 * Solidifying the Body
56 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-1
64 #+begin_src clojure
65 (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 (.setLocation
73 cam (Vector3f.
74 -6.9015837, 8.644911, 5.6043186))
75 (.setRotation
76 cam
77 (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-1
84 ([] (test-hand-1 false))
85 ([record?]
86 (world (hand)
87 standard-debug-controls
88 (fn [world]
89 (if record?
90 (Capture/captureVideo
91 world
92 (File. "/home/r/proj/cortex/render/body/1")))
93 (setup world)) no-op)))
94 #+end_src
97 #+begin_src clojure :results silent
98 (.start (cortex.test.body/test-one))
99 #+end_src
101 #+begin_html
102 <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 physical
111 presence in the simulation. </p>
112 </div>
113 #+end_html
115 You will notice that the hand has no physical presence -- it's a
116 hologram through which everything passes. Therefore, the first thing
117 to do is to make it solid. Blender has physics simulation on par with
118 jMonkeyEngine (they both use bullet as their physics backend), but it
119 can be difficult to translate between the two systems, so for now I
120 specify the mass of each object as meta-data in blender and construct
121 the physics shape based on the mesh in jMonkeyEngine.
123 #+name: body-1
124 #+begin_src clojure
125 (defn physical!
126 "Iterate through the nodes in creature and make them real physical
127 objects in the simulation."
128 [#^Node creature]
129 (dorun
130 (map
131 (fn [geom]
132 (let [physics-control
133 (RigidBodyControl.
134 (HullCollisionShape.
135 (.getMesh geom))
136 (if-let [mass (meta-data geom "mass")]
137 (do
138 ;;(println-repl
139 ;; "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_src
147 =physical!= iterates through a creature's node structure, creating
148 CollisionShapes for each geometry with the mass specified in that
149 geometry's meta-data.
151 #+name: test-2
152 #+begin_src clojure
153 (in-ns 'cortex.test.body)
155 (def gravity-control
156 {"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-2
165 ([] (test-hand-2 false))
166 ([record?]
167 (world
168 (nodify
169 [(doto (hand)
170 (physical!))
171 (floor)])
172 (merge standard-debug-controls gravity-control)
173 (fn [world]
174 (if record?
175 (Capture/captureVideo
176 world (File. "/home/r/proj/cortex/render/body/2")))
177 (set-gravity world Vector3f/ZERO)
178 (setup world))
179 no-op)))
180 #+end_src
182 #+begin_html
183 <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 hold
192 it together.</p>
193 </div>
194 #+end_html
196 Now that's some progress.
198 * Joints
200 Obviously, an AI is not going to be doing much while lying in pieces
201 on the floor. So, the next step to making a proper body is to connect
202 those pieces together with joints. jMonkeyEngine has a large array of
203 joints available via bullet, such as Point2Point, Cone, Hinge, and a
204 generic Six Degree of Freedom joint, with or without spring
205 restitution.
207 Although it should be possible to specify the joints using blender's
208 physics system, and then automatically import them with jMonkeyEngine,
209 the support isn't there yet, and there are a few problems with bullet
210 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 for
213 some senses. Each joint is specified by an empty node whose parent
214 has the name "joints". Their orientation and meta-data determine what
215 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 jMonkeyEngine
219 [[../images/hand-screenshot1.png]]
221 The empty node in the upper right, highlighted in yellow, is the
222 parent node of all the empties which represent joints. The following
223 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 Joints
231 The higher order function =sense-nodes= from =cortex.sense= simplifies
232 the first task.
234 #+name: joints-2
235 #+begin_src clojure
236 (def
237 ^{:doc "Return the children of the creature's \"joints\" node."
238 :arglists '([creature])}
239 joints
240 (sense-nodes "joints"))
241 #+end_src
243 ** Joint Targets and Orientation
245 This technique for finding a joint's targets is very similar to
246 =cortex.sense/closest-node=. A small cube, centered around the
247 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 coordinates
250 in the joint's reference frame. Since the objects must be physical,
251 the empty-node itself escapes detection. Because the objects must be
252 physical, =joint-targets= must be called /after/ =physical!= is
253 called.
255 #+name: joints-3
256 #+begin_src clojure
257 (defn joint-targets
258 "Return the two closest two objects to the joint object, ordered
259 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 (.collideWith
264 parts
265 (BoundingBox. (.getWorldTranslation joint)
266 radius radius radius) results)
267 (let [targets
268 (distinct
269 (map #(.getGeometry %) results))]
270 (if (>= (count targets) 2)
271 (sort-by
272 #(let [joint-ref-frame-position
273 (jme-to-blender
274 (.mult
275 (.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_src
283 ** Generating Joints
285 This section of code iterates through all the different ways of
286 specifying joints using blender meta-data and converts each one to the
287 appropriate jMonkeyEngine joint.
289 #+name: joints-4
290 #+begin_src clojure
291 (defmulti joint-dispatch
292 "Translate blender pseudo-joints into real JME joints."
293 (fn [constraints & _]
294 (:type constraints)))
296 (defmethod joint-dispatch :point
297 [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 the
300 ;; generic 6DOF joint instead of an actual Point2Point joint!
302 ;; should be able to do this:
303 (comment
304 (Point2PointJoint.
305 control-a
306 control-b
307 pivot-a
308 pivot-b))
310 ;; but instead we must do this:
311 ;;(println-repl "substituting 6DOF joint for POINT2POINT joint!")
312 (doto
313 (SixDofJoint.
314 control-a
315 control-b
316 pivot-a
317 pivot-b
318 false)
319 (.setLinearLowerLimit Vector3f/ZERO)
320 (.setLinearUpperLimit Vector3f/ZERO)))
322 (defmethod joint-dispatch :hinge
323 [constraints control-a control-b pivot-a pivot-b rotation]
324 ;;(println-repl "creating HINGE joint")
325 (let [axis
326 (if-let
327 [axis (:axis constraints)]
328 axis
329 Vector3f/UNIT_X)
330 [limit-1 limit-2] (:limit constraints)
331 hinge-axis
332 (.mult
333 rotation
334 (blender-to-jme axis))]
335 (doto
336 (HingeJoint.
337 control-a
338 control-b
339 pivot-a
340 pivot-b
341 hinge-axis
342 hinge-axis)
343 (.setLimit limit-1 limit-2))))
345 (defmethod joint-dispatch :cone
346 [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-repl
354 ;; "UNIT_X --> " (.mult rotation (Vector3f. 1 0 0)))
355 ;;(println-repl
356 ;; "UNIT_Y --> " (.mult rotation (Vector3f. 0 1 0)))
357 ;;(println-repl
358 ;; "UNIT_Z --> " (.mult rotation (Vector3f. 0 0 1)))
359 (doto
360 (ConeJoint.
361 control-a
362 control-b
363 pivot-a
364 pivot-b
365 rotation
366 rotation)
367 (.setLimit (float limit-xz)
368 (float limit-xy)
369 (float twist)))))
371 (defn connect
372 "Create a joint between 'obj-a and 'obj-b at the location of
373 '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 [constraints
392 (map-vals
393 eval
394 (read-string
395 (meta-data joint "joint")))]
396 ;; A side-effect of creating a joint registers
397 ;; it with both physics objects which in turn
398 ;; will register the joint with the physics system
399 ;; when the simulation is started.
400 (do
401 ;;(println-repl "creating joint between"
402 ;; (.getName obj-a) "and" (.getName obj-b))
403 (joint-dispatch constraints
404 control-a control-b
405 pivot-a pivot-b
406 joint-rotation))
407 ;;(println-repl "could not find joint meta-data!")
408 )))
409 #+end_src
411 Creating joints is now a matter of applying =connect= to each joint
412 node.
414 #+name: joints-5
415 #+begin_src clojure
416 (defn joints!
417 "Connect the solid parts of the creature with physical joints. The
418 joints are taken from the \"joints\" node in the creature."
419 [#^Node creature]
420 (dorun
421 (map
422 (fn [joint]
423 (let [[obj-a obj-b] (joint-targets creature joint)]
424 (connect obj-a obj-b joint)))
425 (joints creature))))
426 #+end_src
428 ** Round 3
430 Now we can test the hand in all its glory.
432 #+name: test-3
433 #+begin_src clojure
434 (in-ns 'cortex.test.body)
436 (def debug-control
437 {"key-h" (fn [world val]
438 (if val (enable-debug world)))})
440 (defn test-hand-3
441 ([] (test-hand-3 false))
442 ([record?]
443 (world
444 (nodify
445 [(doto (hand)
446 (physical!)
447 (joints!))
448 (floor)])
449 (merge standard-debug-controls debug-control
450 gravity-control)
451 (comp
452 #(Capture/captureVideo
453 % (File. "/home/r/proj/cortex/render/body/3"))
454 #(do (set-gravity % Vector3f/ZERO) %)
455 setup)
456 no-op)))
457 #+end_src
459 =physical!= makes the hand solid, then =joints!= connects each
460 piece together.
462 #+begin_html
463 <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_html
475 The joints are visualized as green connections between each segment
476 for debug purposes. You can see that they correspond to the empty
477 nodes in the blender file.
479 * Wrap-Up!
481 It is convenient to combine =physical!= and =joints!= into one
482 function that completely creates the creature's physical body.
484 #+name: joints-6
485 #+begin_src clojure
486 (defn body!
487 "Endow the creature with a physical body connected with joints. The
488 particulars of the joints and the masses of each body part are
489 determined in blender."
490 [#^Node creature]
491 (physical! creature)
492 (joints! creature))
493 #+end_src
495 * The Worm
497 Going forward, I will use a model that is less complicated than the
498 hand. It has two segments and one joint, and I call it the worm. All
499 of the senses described in the following posts will be applied to this
500 worm.
502 #+name: test-4
503 #+begin_src clojure
504 (in-ns 'cortex.test.body)
506 (defn worm []
507 (load-blender-model
508 "Models/test-creature/worm.blend"))
510 (defn test-worm
512 "Testing physical bodies:
513 You should see the the worm fall onto a table. You can fire
514 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 (world
523 (nodify
524 [(doto (worm)
525 (body!))
526 (floor)])
527 (merge standard-debug-controls debug-control)
528 #(do
529 (speed-up %)
530 (light-up-everything %)
531 (.setTimer % timer)
532 (cortex.util/display-dilated-time % timer)
533 (if record?
534 (Capture/captureVideo
535 % (File. "/home/r/proj/cortex/render/body/4"))))
536 no-op))))
537 #+end_src
539 #+results: test-4
540 : #'cortex.test.body/test-worm
542 #+begin_html
543 <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 will
552 be grafted.</p>
553 </div>
554 #+end_html
556 * Headers
557 #+name: body-header
558 #+begin_src clojure
559 (ns cortex.body
560 "Assemble a physical creature using the definitions found in a
561 specially prepared blender file. Creates rigid bodies and joints so
562 that a creature can have a physical presence in the simulation."
563 {:author "Robert McIntyre"}
564 (:use (cortex world util sense))
565 (:import
566 (com.jme3.math Vector3f Quaternion Vector2f Matrix3f)
567 (com.jme3.bullet.joints
568 SixDofJoint Point2PointJoint HingeJoint ConeJoint)
569 com.jme3.bullet.control.RigidBodyControl
570 com.jme3.collision.CollisionResults
571 com.jme3.bounding.BoundingBox
572 com.jme3.scene.Node
573 com.jme3.scene.Geometry
574 com.jme3.bullet.collision.shapes.HullCollisionShape))
575 #+end_src
577 #+name: test-header
578 #+begin_src clojure
579 (ns cortex.test.body
580 (:use (cortex world util body))
581 (:import
582 (com.aurellem.capture Capture RatchetTimer)
583 (com.jme3.math Quaternion Vector3f ColorRGBA)
584 java.io.File))
585 #+end_src
587 * Source
588 - [[../src/cortex/body.clj][cortex.body]]
589 - [[../src/cortex/test/body.clj][cortex.test.body]]
590 - [[../assets/Models/test-creature/hand.blend][hand.blend]]
591 - [[../assets/Models/test-creature/palm.png][UV-map-1]]
592 - [[../assets/Models/test-creature/worm.blend][worm.blend]]
593 - [[../assets/Models/test-creature/retina-small.png][UV-map-1]]
594 - [[../assets/Models/test-creature/tip.png][UV-map-2]]
595 #+html: <ul> <li> <a href="../org/body.org">This org file</a> </li> </ul>
596 - [[http://hg.bortreb.com ][source-repository]]
598 * Next
599 The body I have made here exists without any senses or effectors. In
600 the [[./vision.org][next post]], I'll give the creature eyes.
602 * COMMENT Generate Source
603 #+begin_src clojure :tangle ../src/cortex/body.clj
604 <<body-header>>
605 <<body-1>>
606 <<joints-2>>
607 <<joints-3>>
608 <<joints-4>>
609 <<joints-5>>
610 <<joints-6>>
611 #+end_src
613 #+begin_src clojure :tangle ../src/cortex/test/body.clj
614 <<test-header>>
615 <<test-1>>
616 <<test-2>>
617 <<test-3>>
618 <<test-4>>
619 #+end_src