Mercurial > cortex
view org/body.org @ 63:7f2653ad3199
cleaning
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Tue, 29 Nov 2011 02:46:46 -0700 |
parents | 2b9d81017cb7 |
children | ab1fee4280c3 |
line wrap: on
line source
1 #+title: The BODY!!!2 #+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 * COMMENT Body10 #+srcname: body-main11 #+begin_src clojure12 (ns cortex.body13 (use (cortex world util import)))15 (use 'clojure.contrib.def)16 (cortex.import/mega-import-jme3)17 (rlm.rlm-commands/help)19 (defn load-blender-model20 "Load a .blend file using an asset folder relative path."21 [^String model]22 (.loadModel23 (doto (asset-manager)24 (.registerLoader BlenderModelLoader (into-array String ["blend"])))25 model))27 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;29 ;;;;;;;;;;;; eve-style bodies ;;;;;;;;31 (defn worm-segments32 "Create multiple evenly spaced box segments. They're fabulous!"33 [segment-length num-segments interstitial-space radius]34 (letfn [(nth-segment35 [n]36 (box segment-length radius radius :mass 0.137 :position38 (Vector3f.39 (* 2 n (+ interstitial-space segment-length)) 0 0)40 :name (str "worm-segment" n)41 :color (ColorRGBA/randomColor)))]42 (map nth-segment (range num-segments))))44 (defn connect-at-midpoint45 "Connect two physics objects with a Point2Point joint constraint at46 the point equidistant from both objects' centers."47 [segmentA segmentB]48 (let [centerA (.getWorldTranslation segmentA)49 centerB (.getWorldTranslation segmentB)50 midpoint (.mult (.add centerA centerB) (float 0.5))51 pivotA (.subtract midpoint centerA)52 pivotB (.subtract midpoint centerB)54 ;; A side-effect of creating a joint registers55 ;; it with both physics objects which in turn56 ;; will register the joint with the physics system57 ;; when the simulation is started.58 joint (Point2PointJoint.59 (.getControl segmentA RigidBodyControl)60 (.getControl segmentB RigidBodyControl)61 pivotA62 pivotB)]63 segmentB))65 (defn point-worm []66 (let [segments (worm-segments 0.2 5 0.1 0.1)]67 (dorun (map (partial apply connect-at-midpoint)68 (partition 2 1 segments)))69 (nodify "worm" segments)))71 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;72 ;;;;;;;;; Proprioception ;;;;;;;;;;;;;73 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;75 (declare76 ;; generate an arbitray (but stable) orthogonal vector77 ;; to a given vector.78 some-orthogonal80 ;; determine the amount of rotation a quaternion will81 ;; cause about a given axis82 project-quaternion84 ;; proprioception for a single joint85 joint-proprioception87 ;; create a function that provides proprioceptive information88 ;; about an entire body.89 proprioception)91 (defn some-orthogonal92 "Generate an arbitray (but stable) orthogonal vector to a given93 vector."94 [vector]95 (let [x (.getX vector)96 y (.getY vector)97 z (.getZ vector)]98 (cond99 (not= x (float 0)) (Vector3f. (- z) 0 x)100 (not= y (float 0)) (Vector3f. 0 (- z) y)101 (not= z (float 0)) (Vector3f. 0 (- z) y)102 true Vector3f/ZERO)))104 (defn project-quaternion105 "From http://stackoverflow.com/questions/3684269/106 component-of-a-quaternion-rotation-around-an-axis.108 Determine the amount of rotation a quaternion will109 cause about a given axis."110 [#^Quaternion q #^Vector3f axis]111 (let [basis-1 (orthogonal-vect axis)112 basis-2 (.cross axis basis-1)113 rotated (.mult q basis-1)114 alpha (.dot basis-1 (.project rotated basis-1))115 beta (.dot basis-2 (.project rotated basis-2))]116 (Math/atan2 beta alpha)))118 (defn joint-proprioception119 "Relative position information for a two-part system connected by a120 joint. Gives the pitch, yaw, and roll of the 'B' object relative to121 the 'A' object, as determined by the joint."122 [joint]123 (let [object-a (.getUserObject (.getBodyA joint))124 object-b (.getUserObject (.getBodyB joint))125 arm-a126 (.normalize127 (.subtract128 (.localToWorld object-a (.getPivotA joint) nil)129 (.getWorldTranslation object-a)))130 rotate-a131 (doto (Matrix3f.)132 (.fromStartEndVectors arm-a Vector3f/UNIT_X))133 arm-b134 (.mult135 rotate-a136 (.normalize137 (.subtract138 (.localToWorld object-b (.getPivotB joint) nil)139 (.getWorldTranslation object-b))))140 pitch141 (.angleBetween142 (.normalize (Vector2f. (.getX arm-b) (.getY arm-b)))143 (Vector2f. 1 0))144 yaw145 (.angleBetween146 (.normalize (Vector2f. (.getX arm-b) (.getZ arm-b)))147 (Vector2f. 1 0))149 roll150 (rot-about-axis151 (.mult152 (.getLocalRotation object-b)153 (doto (Quaternion.)154 (.fromRotationMatrix rotate-a)))155 arm-b)]156 [pitch yaw roll]))158 (defn proprioception159 "Create a function that provides proprioceptive information about an160 entire body."161 [body]162 ;; extract the body's joints163 (let [joints164 (distinct165 (reduce166 concat167 (map #(.getJoints %)168 (keep169 #(.getControl % RigidBodyControl)170 (node-seq body)))))]171 (fn []172 (map joint-proprioception joints))))175 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;176 ;;;;;;;;; Mortor Control ;;;;;;;;;;;;;177 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;180 ;; surprisingly enough, terristerial creatures only move by using181 ;; torque applied about their joints. There's not a single straight182 ;; line of force in the human body at all! (A straight line of force183 ;; would correspond to some sort of jet or rocket propulseion.)185 (defn vector-motor-control186 "Create a function that accepts a sequence of Vector3f objects that187 describe the torque to be applied to each part of the body."188 [body]189 (let [nodes (node-seq body)190 controls (keep #(.getControl % RigidBodyControl) nodes)]191 (fn [torques]192 (map #(.applyTorque %1 %2)193 controls torques))))195 ;; note -- might want to add a lower dimensional, discrete version of196 ;; this if it proves usefull from a x-modal clustering perspective.198 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;202 (defn worm-pattern [time]203 [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0205 0 0 0 0 0 0 0 0 0 0 0207 (* 20 (Math/sin (* Math/PI 2 (/ (rem time 300 ) 300))))209 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0210 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0211 0 0 0 0 0 0 0 0 0 0 0 0 0 0213 ])215 (defn worm-pattern [time]216 (let [angle (* Math/PI (/ 4 20))217 direction (Vector3f. 0 (Math/sin angle) (Math/cos angle))]218 [Vector3f/ZERO219 (.mult220 direction221 (float (* 2 (Math/sin (* Math/PI 2 (/ (rem time 300 ) 300))))))222 Vector3f/ZERO223 Vector3f/ZERO224 Vector3f/ZERO]))226 (defn test-worm-control227 []228 (let [worm (point-worm)229 time (atom 0)230 worm-motor-map (vector-motor-control worm)]231 (world232 (nodify [worm233 (box 10 0.5 10 :position (Vector3f. 0 -5 0) :mass 0234 :color ColorRGBA/Gray)])235 standard-debug-controls236 (fn [world]237 (enable-debug world)238 (light-up-everything world)239 (comment240 (com.aurellem.capture.Capture/captureVideo241 world242 (file-str "/home/r/proj/cortex/tmp/moving-worm")))243 )245 (fn [_ _]246 (swap! time inc)247 ;;(Thread/sleep 200)248 (dorun (worm-motor-map249 (worm-pattern @time)))))))254 (defn test-prop255 "see how torque works."256 []257 (let [hand (box 1 0.2 0.2 :position (Vector3f. 0 2 0)258 :mass 0 :color ColorRGBA/Green)259 finger (box 1 0.2 0.2 :position (Vector3f. 2.4 2 0)260 :mass 1 :color (ColorRGBA. 0.20 0.40 0.99 1.0))261 floor (box 10 0.5 10 :position (Vector3f. 0 -5 0)262 :mass 0 :color ColorRGBA/Gray)264 move-up? (atom false)265 move-down? (atom false)266 move-left? (atom false)267 move-right? (atom false)268 roll-left? (atom false)269 roll-right? (atom false)270 control (.getControl finger RigidBodyControl)271 joint272 (doto273 (Point2PointJoint.274 (.getControl hand RigidBodyControl)275 control276 (Vector3f. 1.2 0 0)277 (Vector3f. -1.2 0 0 ))278 (.setCollisionBetweenLinkedBodys false))279 time (atom 0)280 ]281 (world282 (nodify [hand finger floor])283 (merge standard-debug-controls284 {"key-r" (fn [_ pressed?] (reset! move-up? pressed?))285 "key-t" (fn [_ pressed?] (reset! move-down? pressed?))286 "key-f" (fn [_ pressed?] (reset! move-left? pressed?))287 "key-g" (fn [_ pressed?] (reset! move-right? pressed?))288 "key-v" (fn [_ pressed?] (reset! roll-left? pressed?))289 "key-b" (fn [_ pressed?] (reset! roll-right? pressed?))})290 (fn [world]291 (set-gravity world (Vector3f. 0 0 0))292 (.setMoveSpeed (.getFlyByCamera world) 50)293 (.setRotationSpeed (.getFlyByCamera world) 50)294 (light-up-everything world)295 (.setTimer world (NanoTimer.))296 )297 (fn [_ _]298 (if @move-up?299 (.applyTorque control300 (.mult (.getPhysicsRotation control)301 (Vector3f. 0 0 10))))302 (if @move-down?303 (.applyTorque control304 (.mult (.getPhysicsRotation control)305 (Vector3f. 0 0 -10))))306 (if @move-left?307 (.applyTorque control308 (.mult (.getPhysicsRotation control)309 (Vector3f. 0 10 0))))310 (if @move-right?311 (.applyTorque control312 (.mult (.getPhysicsRotation control)313 (Vector3f. 0 -10 0))))314 (if @roll-left?315 (.applyTorque control316 (.mult (.getPhysicsRotation control)317 (Vector3f. -1 0 0))))318 (if @roll-right?319 (.applyTorque control320 (.mult (.getPhysicsRotation control)321 (Vector3f. 1 0 0))))323 (if (= 0 (rem (swap! time inc) 2000))324 (do326 (apply327 (comp328 println-repl329 #(format "pitch: %1.2f\nyaw: %1.2f\nroll: %1.2f\n" %1 %2 %3))330 (relative-positions joint))))))))332 #+end_src335 * COMMENT code-limbo336 #+begin_src clojure337 ;;(.loadModel338 ;; (doto (asset-manager)339 ;; (.registerLoader BlenderModelLoader (into-array String ["blend"])))340 ;; "Models/person/person.blend")342 (defn view-model [^String model]343 (view344 (.loadModel345 (doto (asset-manager)346 (.registerLoader BlenderModelLoader (into-array String ["blend"])))347 model)))349 (defn load-blender-scene [^String model]350 (.loadModel351 (doto (asset-manager)352 (.registerLoader BlenderLoader (into-array String ["blend"])))353 model))355 (defn worm356 []357 (.loadModel (asset-manager) "Models/anim2/Cube.mesh.xml"))359 (defn oto360 []361 (.loadModel (asset-manager) "Models/Oto/Oto.mesh.xml"))363 (defn sinbad364 []365 (.loadModel (asset-manager) "Models/Sinbad/Sinbad.mesh.xml"))367 (defn worm-blender368 []369 (first (seq (.getChildren (load-blender-model370 "Models/anim2/simple-worm.blend")))))372 (defn body373 "given a node with a SkeletonControl, will produce a body sutiable374 for AI control with movement and proprioception."375 [node]376 (let [skeleton-control (.getControl node SkeletonControl)377 krc (KinematicRagdollControl.)]378 (comment379 (dorun380 (map #(.addBoneName krc %)381 ["mid2" "tail" "head" "mid1" "mid3" "mid4" "Dummy-Root" ""]382 ;;"mid2" "mid3" "tail" "head"]383 )))384 (.addControl node krc)385 (.setRagdollMode krc)386 )387 node388 )389 (defn show-skeleton [node]390 (let [sd392 (doto393 (SkeletonDebugger. "aurellem-skel-debug"394 (skel node))395 (.setMaterial (green-x-ray)))]396 (.attachChild node sd)397 node))401 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;403 ;; this could be a good way to give objects special properties like404 ;; being eyes and the like406 (.getUserData407 (.getChild408 (load-blender-model "Models/property/test.blend") 0)409 "properties")411 ;; the properties are saved along with the blender file.412 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;417 (defn init-debug-skel-node418 [f debug-node skeleton]419 (let [bones420 (map #(.getBone skeleton %)421 (range (.getBoneCount skeleton)))]422 (dorun (map #(.setUserControl % true) bones))423 (dorun (map (fn [b]424 (println (.getName b)425 " -- " (f b)))426 bones))427 (dorun428 (map #(.attachChild429 debug-node430 (doto431 (sphere 0.1432 :position (f %)433 :physical? false)434 (.setMaterial (green-x-ray))))435 bones)))436 debug-node)438 (import jme3test.bullet.PhysicsTestHelper)441 (defn test-zzz [the-worm world value]442 (if (not value)443 (let [skeleton (skel the-worm)]444 (println-repl "enabling bones")445 (dorun446 (map447 #(.setUserControl (.getBone skeleton %) true)448 (range (.getBoneCount skeleton))))451 (let [b (.getBone skeleton 2)]452 (println-repl "moving " (.getName b))453 (println-repl (.getLocalPosition b))454 (.setUserTransforms b455 Vector3f/UNIT_X456 Quaternion/IDENTITY457 ;;(doto (Quaternion.)458 ;; (.fromAngles (/ Math/PI 2)459 ;; 0460 ;; 0462 (Vector3f. 1 1 1))463 )465 (println-repl "hi! <3"))))468 (defn test-ragdoll []470 (let [the-worm472 ;;(.loadModel (asset-manager) "Models/anim2/Cube.mesh.xml")473 (doto (show-skeleton (worm-blender))474 (.setLocalTranslation (Vector3f. 0 10 0))475 ;;(worm)476 ;;(oto)477 ;;(sinbad)478 )479 ]482 (.start483 (world484 (doto (Node.)485 (.attachChild the-worm))486 {"key-return" (fire-cannon-ball)487 "key-space" (partial test-zzz the-worm)488 }489 (fn [world]490 (light-up-everything world)491 (PhysicsTestHelper/createPhysicsTestWorld492 (.getRootNode world)493 (asset-manager)494 (.getPhysicsSpace495 (.getState (.getStateManager world) BulletAppState)))496 (set-gravity world Vector3f/ZERO)497 ;;(.setTimer world (NanoTimer.))498 ;;(org.lwjgl.input.Mouse/setGrabbed false)499 )500 no-op501 )504 )))507 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;508 ;;; here is the ragdoll stuff510 (def worm-mesh (.getMesh (.getChild (worm-blender) 0)))511 (def mesh worm-mesh)513 (.getFloatBuffer mesh VertexBuffer$Type/Position)514 (.getFloatBuffer mesh VertexBuffer$Type/BoneWeight)515 (.getData (.getBuffer mesh VertexBuffer$Type/BoneIndex))518 (defn position [index]519 (.get520 (.getFloatBuffer worm-mesh VertexBuffer$Type/Position)521 index))523 (defn bones [index]524 (.get525 (.getData (.getBuffer mesh VertexBuffer$Type/BoneIndex))526 index))528 (defn bone-weights [index]529 (.get530 (.getFloatBuffer mesh VertexBuffer$Type/BoneWeight)531 index))535 (defn vertex-bones [vertex]536 (vec (map (comp int bones) (range (* vertex 4) (+ (* vertex 4) 4)))))538 (defn vertex-weights [vertex]539 (vec (map (comp float bone-weights) (range (* vertex 4) (+ (* vertex 4) 4)))))541 (defn vertex-position [index]542 (let [offset (* index 3)]543 (Vector3f. (position offset)544 (position (inc offset))545 (position (inc(inc offset))))))547 (def vertex-info (juxt vertex-position vertex-bones vertex-weights))549 (defn bone-control-color [index]550 (get {[1 0 0 0] ColorRGBA/Red551 [1 2 0 0] ColorRGBA/Magenta552 [2 0 0 0] ColorRGBA/Blue}553 (vertex-bones index)554 ColorRGBA/White))556 (defn influence-color [index bone-num]557 (get558 {(float 0) ColorRGBA/Blue559 (float 0.5) ColorRGBA/Green560 (float 1) ColorRGBA/Red}561 ;; find the weight of the desired bone562 ((zipmap (vertex-bones index)(vertex-weights index))563 bone-num)564 ColorRGBA/Blue))566 (def worm-vertices (set (map vertex-info (range 60))))569 (defn test-info []570 (let [points (Node.)]571 (dorun572 (map #(.attachChild points %)573 (map #(sphere 0.01574 :position (vertex-position %)575 :color (influence-color % 1)576 :physical? false)577 (range 60))))578 (view points)))581 (defrecord JointControl [joint physics-space]582 PhysicsControl583 (setPhysicsSpace [this space]584 (dosync585 (ref-set (:physics-space this) space))586 (.addJoint space (:joint this)))587 (update [this tpf])588 (setSpatial [this spatial])589 (render [this rm vp])590 (getPhysicsSpace [this] (deref (:physics-space this)))591 (isEnabled [this] true)592 (setEnabled [this state]))594 (defn add-joint595 "Add a joint to a particular object. When the object is added to the596 PhysicsSpace of a simulation, the joint will also be added"597 [object joint]598 (let [control (JointControl. joint (ref nil))]599 (.addControl object control))600 object)603 (defn hinge-world604 []605 (let [sphere1 (sphere)606 sphere2 (sphere 1 :position (Vector3f. 3 3 3))607 joint (Point2PointJoint.608 (.getControl sphere1 RigidBodyControl)609 (.getControl sphere2 RigidBodyControl)610 Vector3f/ZERO (Vector3f. 3 3 3))]611 (add-joint sphere1 joint)612 (doto (Node. "hinge-world")613 (.attachChild sphere1)614 (.attachChild sphere2))))617 (defn test-joint []618 (view (hinge-world)))620 ;; (defn copier-gen []621 ;; (let [count (atom 0)]622 ;; (fn [in]623 ;; (swap! count inc)624 ;; (clojure.contrib.duck-streams/copy625 ;; in (File. (str "/home/r/tmp/mao-test/clojure-images/"626 ;; ;;/home/r/tmp/mao-test/clojure-images627 ;; (format "%08d.png" @count)))))))628 ;; (defn decrease-framerate []629 ;; (map630 ;; (copier-gen)631 ;; (sort632 ;; (map first633 ;; (partition634 ;; 4635 ;; (filter #(re-matches #".*.png$" (.getCanonicalPath %))636 ;; (file-seq637 ;; (file-str638 ;; "/home/r/media/anime/mao-temp/images"))))))))642 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;644 (defn proprioception645 "Create a proprioception map that reports the rotations of the646 various limbs of the creature's body"647 [creature]648 [#^Node creature]649 (let [650 nodes (node-seq creature)651 joints652 (map653 :joint654 (filter655 #(isa? (class %) JointControl)656 (reduce657 concat658 (map (fn [node]659 (map (fn [num] (.getControl node num))660 (range (.getNumControls node))))661 nodes))))]662 (fn []663 (reduce concat (map relative-positions (list (first joints)))))))666 (defn skel [node]667 (doto668 (.getSkeleton669 (.getControl node SkeletonControl))670 ;; this is necessary to force the skeleton to have accurate world671 ;; transforms before it is rendered to the screen.672 (.resetAndUpdate)))674 (defn green-x-ray []675 (doto (Material. (asset-manager)676 "Common/MatDefs/Misc/Unshaded.j3md")677 (.setColor "Color" ColorRGBA/Green)678 (-> (.getAdditionalRenderState)679 (.setDepthTest false))))681 (defn test-worm []682 (.start683 (world684 (doto (Node.)685 ;;(.attachChild (point-worm))686 (.attachChild (load-blender-model687 "Models/anim2/joint-worm.blend"))689 (.attachChild (box 10 1 10690 :position (Vector3f. 0 -2 0) :mass 0691 :color (ColorRGBA/Gray))))692 {693 "key-space" (fire-cannon-ball)694 }695 (fn [world]696 (enable-debug world)697 (light-up-everything world)698 ;;(.setTimer world (NanoTimer.))699 )700 no-op)))704 ;; defunct movement stuff705 (defn torque-controls [control]706 (let [torques707 (concat708 (map #(Vector3f. 0 (Math/sin %) (Math/cos %))709 (range 0 (* Math/PI 2) (/ (* Math/PI 2) 20)))710 [Vector3f/UNIT_X])]711 (map (fn [torque-axis]712 (fn [torque]713 (.applyTorque714 control715 (.mult (.mult (.getPhysicsRotation control)716 torque-axis)717 (float718 (* (.getMass control) torque))))))719 torques)))721 (defn motor-map722 "Take a creature and generate a function that will enable fine723 grained control over all the creature's limbs."724 [#^Node creature]725 (let [controls (keep #(.getControl % RigidBodyControl)726 (node-seq creature))727 limb-controls (reduce concat (map torque-controls controls))728 body-control (partial map #(%1 %2) limb-controls)]729 body-control))731 (defn test-motor-map732 "see how torque works."733 []734 (let [finger (box 3 0.5 0.5 :position (Vector3f. 0 2 0)735 :mass 1 :color ColorRGBA/Green)736 motor-map (motor-map finger)]737 (world738 (nodify [finger739 (box 10 0.5 10 :position (Vector3f. 0 -5 0) :mass 0740 :color ColorRGBA/Gray)])741 standard-debug-controls742 (fn [world]743 (set-gravity world Vector3f/ZERO)744 (light-up-everything world)745 (.setTimer world (NanoTimer.)))746 (fn [_ _]747 (dorun (motor-map [0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0]))))))750 #+end_src758 * COMMENT generate Source.759 #+begin_src clojure :tangle ../src/cortex/body.clj760 <<body-main>>761 #+end_src