view org/body.org @ 318:2ffda8e9b2a5

update setup.org to reflect ned jMonkeyEngine version.
author Robert McIntyre <rlm@mit.edu>
date Tue, 28 Feb 2012 14:13:56 -0600
parents bb3f8a4af87f
children 702b5c78c2de
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 #+end_src
410 Creating joints is now a matter of applying =connect= to each joint
411 node.
413 #+name: joints-5
414 #+begin_src clojure
415 (defn joints!
416 "Connect the solid parts of the creature with physical joints. The
417 joints are taken from the \"joints\" node in the creature."
418 [#^Node creature]
419 (dorun
420 (map
421 (fn [joint]
422 (let [[obj-a obj-b] (joint-targets creature joint)]
423 (connect obj-a obj-b joint)))
424 (joints creature))))
425 #+end_src
427 ** Round 3
429 Now we can test the hand in all its glory.
431 #+name: test-3
432 #+begin_src clojure
433 (in-ns 'cortex.test.body)
435 (def debug-control
436 {"key-h" (fn [world val]
437 (if val (enable-debug world)))})
439 (defn test-hand-3
440 ([] (test-hand-3 false))
441 ([record?]
442 (world
443 (nodify
444 [(doto (hand)
445 (physical!)
446 (joints!))
447 (floor)])
448 (merge standard-debug-controls debug-control
449 gravity-control)
450 (comp
451 #(Capture/captureVideo
452 % (File. "/home/r/proj/cortex/render/body/3"))
453 #(do (set-gravity % Vector3f/ZERO) %)
454 setup)
455 no-op)))
456 #+end_src
458 =physical!= makes the hand solid, then =joints!= connects each
459 piece together.
461 #+begin_html
462 <div class="figure">
463 <center>
464 <video controls="controls" width="640">
465 <source src="../video/full-hand.ogg" type="video/ogg"
466 preload="none" poster="../images/aurellem-1280x480.png" />
467 </video>
468 <br> <a href="http://youtu.be/4affLfwSPP4"> YouTube </a>
469 </center>
470 <p>Now the hand is physical and has joints.</p>
471 </div>
472 #+end_html
474 The joints are visualized as green connections between each segment
475 for debug purposes. You can see that they correspond to the empty
476 nodes in the blender file.
478 * Wrap-Up!
480 It is convenient to combine =physical!= and =joints!= into one
481 function that completely creates the creature's physical body.
483 #+name: joints-6
484 #+begin_src clojure
485 (defn body!
486 "Endow the creature with a physical body connected with joints. The
487 particulars of the joints and the masses of each body part are
488 determined in blender."
489 [#^Node creature]
490 (physical! creature)
491 (joints! creature))
492 #+end_src
494 * The Worm
496 Going forward, I will use a model that is less complicated than the
497 hand. It has two segments and one joint, and I call it the worm. All
498 of the senses described in the following posts will be applied to this
499 worm.
501 #+name: test-4
502 #+begin_src clojure
503 (in-ns 'cortex.test.body)
505 (defn worm []
506 (load-blender-model
507 "Models/test-creature/worm.blend"))
509 (defn test-worm
510 ([] (test-worm false))
511 ([record?]
512 (let [timer (RatchetTimer. 60)]
513 (world
514 (nodify
515 [(doto (worm)
516 (body!))
517 (floor)])
518 (merge standard-debug-controls debug-control)
519 #(do
520 (speed-up %)
521 (light-up-everything %)
522 (.setTimer % timer)
523 (cortex.util/display-dilated-time % timer)
524 (if record?
525 (Capture/captureVideo
526 % (File. "/home/r/proj/cortex/render/body/4"))))
527 no-op))))
528 #+end_src
530 #+begin_html
531 <div class="figure">
532 <center>
533 <video controls="controls" width="640">
534 <source src="../video/worm-1.ogg" type="video/ogg"
535 preload="none" poster="../images/aurellem-1280x480.png" />
536 </video>
537 <br> <a href="http://youtu.be/rFVXI0T3iSE"> YouTube </a>
538 </center>
539 <p>This worm model will be the platform onto which future senses will
540 be grafted.</p>
541 </div>
542 #+end_html
544 * Headers
545 #+name: body-header
546 #+begin_src clojure
547 (ns cortex.body
548 "Assemble a physical creature using the definitions found in a
549 specially prepared blender file. Creates rigid bodies and joints so
550 that a creature can have a physical presence in the simulation."
551 {:author "Robert McIntyre"}
552 (:use (cortex world util sense))
553 (:import
554 (com.jme3.math Vector3f Quaternion Vector2f Matrix3f)
555 (com.jme3.bullet.joints
556 SixDofJoint Point2PointJoint HingeJoint ConeJoint)
557 com.jme3.bullet.control.RigidBodyControl
558 com.jme3.collision.CollisionResults
559 com.jme3.bounding.BoundingBox
560 com.jme3.scene.Node
561 com.jme3.scene.Geometry
562 com.jme3.bullet.collision.shapes.HullCollisionShape))
563 #+end_src
565 #+name: test-header
566 #+begin_src clojure
567 (ns cortex.test.body
568 (:use (cortex world util body))
569 (:import
570 (com.aurellem.capture Capture RatchetTimer)
571 (com.jme3.math Quaternion Vector3f ColorRGBA)
572 java.io.File))
573 #+end_src
575 * Source
576 - [[../src/cortex/body.clj][cortex.body]]
577 - [[../src/cortex/test/body.clj][cortex.test.body]]
578 - [[../assets/Models/test-creature/hand.blend][hand.blend]]
579 - [[../assets/Models/test-creature/palm.png][UV-map-1]]
580 - [[../assets/Models/test-creature/worm.blend][worm.blend]]
581 - [[../assets/Models/test-creature/retina-small.png][UV-map-1]]
582 - [[../assets/Models/test-creature/tip.png][UV-map-2]]
583 #+html: <ul> <li> <a href="../org/body.org">This org file</a> </li> </ul>
584 - [[http://hg.bortreb.com ][source-repository]]
586 * Next
587 The body I have made here exists without any senses or effectors. In
588 the [[./vision.org][next post]], I'll give the creature eyes.
590 * COMMENT Generate Source
591 #+begin_src clojure :tangle ../src/cortex/body.clj
592 <<body-header>>
593 <<body-1>>
594 <<joints-2>>
595 <<joints-3>>
596 <<joints-4>>
597 <<joints-5>>
598 <<joints-6>>
599 #+end_src
601 #+begin_src clojure :tangle ../src/cortex/test/body.clj
602 <<test-header>>
603 <<test-1>>
604 <<test-2>>
605 <<test-3>>
606 <<test-4>>
607 #+end_src