Mercurial > cortex
view org/body.org @ 145:7a49b81ca1bf
finally got proprioception working to my satisfaction
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Thu, 02 Feb 2012 12:49:11 -0700 |
parents | 48f9cba082eb |
children | e1232043656a |
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 * Proprioception9 #+name: proprioception10 #+begin_src clojure11 (ns cortex.body12 (:use (cortex world util))13 (:import14 com.jme3.math.Vector3f15 com.jme3.math.Quaternion16 com.jme3.math.Vector2f17 com.jme3.math.Matrix3f18 com.jme3.bullet.control.RigidBodyControl19 com.jme3.collision.CollisionResults20 com.jme3.bounding.BoundingBox))22 (import com.jme3.scene.Node)24 (defn jme-to-blender25 "Convert from JME coordinates to Blender coordinates"26 [#^Vector3f in]27 (Vector3f. (.getX in)28 (- (.getZ in))29 (.getY in)))31 (defn joint-targets32 "Return the two closest two objects to the joint object, ordered33 from bottom to top according to the joint's rotation."34 [#^Node parts #^Node joint]35 (loop [radius (float 0.01)]36 (let [results (CollisionResults.)]37 (.collideWith38 parts39 (BoundingBox. (.getWorldTranslation joint)40 radius radius radius)41 results)42 (let [targets43 (distinct44 (map #(.getGeometry %) results))]45 (if (>= (count targets) 2)46 (sort-by47 #(let [v48 (jme-to-blender49 (.mult50 (.inverse (.getWorldRotation joint))51 (.subtract (.getWorldTranslation %)52 (.getWorldTranslation joint))))]53 (println-repl (.getName %) ":" v)54 (.dot (Vector3f. 1 1 1)55 v))56 (take 2 targets))57 (recur (float (* radius 2))))))))59 (defn creature-joints60 "Return the children of the creature's \"joints\" node."61 [#^Node creature]62 (if-let [joint-node (.getChild creature "joints")]63 (seq (.getChildren joint-node))64 (do (println-repl "could not find JOINTS node") [])))66 (defn right-handed? [vec1 vec2 vec3]67 (< 0 (.dot (.cross vec1 vec2) vec3)))69 (defn absolute-angle [vec1 vec2 axis]70 (let [angle (.angleBetween vec1 vec2)]71 (if (right-handed? vec1 vec2 axis)72 angle (- (* 2 Math/PI) angle))))75 (defn joint-proprioception [#^Node parts #^Node joint]76 (let [[obj-a obj-b] (joint-targets parts joint)77 joint-rot (.getWorldRotation joint)78 x0 (.mult joint-rot Vector3f/UNIT_X)79 y0 (.mult joint-rot Vector3f/UNIT_Y)80 z0 (.mult joint-rot Vector3f/UNIT_Z)]81 (println-repl "x:" x0)82 (println-repl "y:" y0)83 (println-repl "z:" z0)84 (println-repl "init-a:" (.getWorldRotation obj-a))85 (println-repl "init-b:" (.getWorldRotation obj-b))87 (fn []88 (let [rot-a (.clone (.getWorldRotation obj-a))89 rot-b (.clone (.getWorldRotation obj-b))90 x (.mult rot-a x0)91 y (.mult rot-a y0)92 z (.mult rot-a z0)94 X (.mult rot-b x0)95 Y (.mult rot-b y0)96 Z (.mult rot-b z0)97 heading (Math/atan2 (.dot X z) (.dot X x))98 pitch (Math/atan2 (.dot X y) (.dot X x))100 ;; rotate x-vector back to origin101 reverse102 (doto (Quaternion.)103 (.fromAngleAxis104 (.angleBetween X x)105 (let [cross (.normalize (.cross X x))]106 (if (= 0 (.length cross)) y cross))))107 roll (absolute-angle (.mult reverse Y) y x)]109 [heading pitch roll]))))111 (defn proprioception112 "Create a function that provides proprioceptive information about an113 entire body."114 [#^Node creature]115 ;; extract the body's joints116 (let [joints (creature-joints creature)117 senses (map (partial joint-proprioception creature) joints)]118 (fn []119 (map #(%) senses))))121 (defn tap [obj direction force]122 (let [control (.getControl obj RigidBodyControl)]123 (.applyTorque124 control125 (.mult (.getPhysicsRotation control)126 (.mult (.normalize direction) (float force))))))129 (defn with-movement130 [object131 [up down left right roll-up roll-down :as keyboard]132 forces133 [root-node134 keymap135 intilization136 world-loop]]137 (let [add-keypress138 (fn [state keymap key]139 (merge keymap140 {key141 (fn [_ pressed?]142 (reset! state pressed?))}))143 move-up? (atom false)144 move-down? (atom false)145 move-left? (atom false)146 move-right? (atom false)147 roll-left? (atom false)148 roll-right? (atom false)150 directions [(Vector3f. 0 1 0)(Vector3f. 0 -1 0)151 (Vector3f. 0 0 1)(Vector3f. 0 0 -1)152 (Vector3f. -1 0 0)(Vector3f. 1 0 0)]153 atoms [move-left? move-right? move-up? move-down?154 roll-left? roll-right?]156 keymap* (reduce merge157 (map #(add-keypress %1 keymap %2)158 atoms159 keyboard))161 splice-loop (fn []162 (dorun163 (map164 (fn [sym direction force]165 (if @sym166 (tap object direction force)))167 atoms directions forces)))169 world-loop* (fn [world tpf]170 (world-loop world tpf)171 (splice-loop))]172 [root-node173 keymap*174 intilization175 world-loop*]))177 (import java.awt.image.BufferedImage)179 (defn draw-sprite [image sprite x y color ]180 (dorun181 (for [[u v] sprite]182 (.setRGB image (+ u x) (+ v y) color))))184 (defn view-angle185 "create a debug view of an angle"186 [color]187 (let [image (BufferedImage. 50 50 BufferedImage/TYPE_INT_RGB)188 previous (atom [25 25])189 sprite [[0 0] [0 1]190 [0 -1] [-1 0] [1 0]]]191 (fn [angle]192 (let [angle (float angle)]193 (let [position194 [(+ 25 (int (* 20 (Math/cos angle))))195 (+ 25 (int (* -20 (Math/sin angle))))]]196 (draw-sprite image sprite (@previous 0) (@previous 1) 0x000000)197 (draw-sprite image sprite (position 0) (position 1) color)198 (reset! previous position))199 image))))201 (defn proprioception-debug-window202 []203 (let [heading (view-angle 0xFF0000)204 pitch (view-angle 0x00FF00)205 roll (view-angle 0xFFFFFF)206 v-heading (view-image)207 v-pitch (view-image)208 v-roll (view-image)209 ]210 (fn [prop-data]211 (dorun212 (map213 (fn [[h p r]]214 (v-heading (heading h))215 (v-pitch (pitch p))216 (v-roll (roll r)))217 prop-data)))))220 #+end_src222 #+results: proprioception223 : #'cortex.body/proprioception-debug-window225 * Motor Control226 #+name: motor-control227 #+begin_src clojure228 (in-ns 'cortex.body)230 ;; surprisingly enough, terristerial creatures only move by using231 ;; torque applied about their joints. There's not a single straight232 ;; line of force in the human body at all! (A straight line of force233 ;; would correspond to some sort of jet or rocket propulseion.)235 (defn vector-motor-control236 "Create a function that accepts a sequence of Vector3f objects that237 describe the torque to be applied to each part of the body."238 [body]239 (let [nodes (node-seq body)240 controls (keep #(.getControl % RigidBodyControl) nodes)]241 (fn [torques]242 (map #(.applyTorque %1 %2)243 controls torques))))244 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;245 #+end_src247 ## note -- might want to add a lower dimensional, discrete version of248 ## this if it proves useful from a x-modal clustering perspective.250 * Examples252 #+name: test-body253 #+begin_src clojure254 (ns cortex.test.body255 (:use (cortex world util body))256 (:require cortex.silly)257 (:import258 com.jme3.math.Vector3f259 com.jme3.math.ColorRGBA260 com.jme3.bullet.joints.Point2PointJoint261 com.jme3.bullet.control.RigidBodyControl262 com.jme3.system.NanoTimer263 com.jme3.math.Quaternion))265 (defn worm-segments266 "Create multiple evenly spaced box segments. They're fabulous!"267 [segment-length num-segments interstitial-space radius]268 (letfn [(nth-segment269 [n]270 (box segment-length radius radius :mass 0.1271 :position272 (Vector3f.273 (* 2 n (+ interstitial-space segment-length)) 0 0)274 :name (str "worm-segment" n)275 :color (ColorRGBA/randomColor)))]276 (map nth-segment (range num-segments))))278 (defn connect-at-midpoint279 "Connect two physics objects with a Point2Point joint constraint at280 the point equidistant from both objects' centers."281 [segmentA segmentB]282 (let [centerA (.getWorldTranslation segmentA)283 centerB (.getWorldTranslation segmentB)284 midpoint (.mult (.add centerA centerB) (float 0.5))285 pivotA (.subtract midpoint centerA)286 pivotB (.subtract midpoint centerB)288 ;; A side-effect of creating a joint registers289 ;; it with both physics objects which in turn290 ;; will register the joint with the physics system291 ;; when the simulation is started.292 joint (Point2PointJoint.293 (.getControl segmentA RigidBodyControl)294 (.getControl segmentB RigidBodyControl)295 pivotA296 pivotB)]297 segmentB))299 (defn eve-worm300 "Create a worm-like body bound by invisible joint constraints."301 []302 (let [segments (worm-segments 0.2 5 0.1 0.1)]303 (dorun (map (partial apply connect-at-midpoint)304 (partition 2 1 segments)))305 (nodify "worm" segments)))307 (defn worm-pattern308 "This is a simple, mindless motor control pattern that drives the309 second segment of the worm's body at an offset angle with310 sinusoidally varying strength."311 [time]312 (let [angle (* Math/PI (/ 9 20))313 direction (Vector3f. 0 (Math/sin angle) (Math/cos angle))]314 [Vector3f/ZERO315 (.mult316 direction317 (float (* 2 (Math/sin (* Math/PI 2 (/ (rem time 300 ) 300))))))318 Vector3f/ZERO319 Vector3f/ZERO320 Vector3f/ZERO]))322 (defn test-motor-control323 "Testing motor-control:324 You should see a multi-segmented worm-like object fall onto the325 table and begin writhing and moving."326 []327 (let [worm (eve-worm)328 time (atom 0)329 worm-motor-map (vector-motor-control worm)]330 (world331 (nodify [worm332 (box 10 0.5 10 :position (Vector3f. 0 -5 0) :mass 0333 :color ColorRGBA/Gray)])334 standard-debug-controls335 (fn [world]336 (enable-debug world)337 (light-up-everything world)338 (comment339 (com.aurellem.capture.Capture/captureVideo340 world341 (file-str "/home/r/proj/cortex/tmp/moving-worm")))342 )344 (fn [_ _]345 (swap! time inc)346 (Thread/sleep 20)347 (dorun (worm-motor-map348 (worm-pattern @time)))))))352 (defn join-at-point [obj-a obj-b world-pivot]353 (cortex.silly/joint-dispatch354 {:type :point}355 (.getControl obj-a RigidBodyControl)356 (.getControl obj-b RigidBodyControl)357 (cortex.silly/world-to-local obj-a world-pivot)358 (cortex.silly/world-to-local obj-b world-pivot)359 nil360 ))362 (import com.jme3.bullet.collision.PhysicsCollisionObject)364 (defn blab-* []365 (let [hand (box 0.5 0.2 0.2 :position (Vector3f. 0 0 0)366 :mass 0 :color ColorRGBA/Green)367 finger (box 0.5 0.2 0.2 :position (Vector3f. 2.4 0 0)368 :mass 1 :color ColorRGBA/Red)369 connection-point (Vector3f. 1.2 0 0)370 root (nodify [hand finger])]372 (join-at-point hand finger (Vector3f. 1.2 0 0))374 (.setCollisionGroup375 (.getControl hand RigidBodyControl)376 PhysicsCollisionObject/COLLISION_GROUP_NONE)377 (world378 root379 standard-debug-controls380 (fn [world]381 (enable-debug world)382 (.setTimer world (com.aurellem.capture.RatchetTimer. 60))383 (set-gravity world Vector3f/ZERO)384 )385 no-op)))386 (comment388 (defn proprioception-debug-window389 []390 (let [time (atom 0)]391 (fn [prop-data]392 (if (= 0 (rem (swap! time inc) 40))393 (println-repl prop-data)))))394 )396 (comment397 (dorun398 (map399 (comp400 println-repl401 (fn [[p y r]]402 (format403 "pitch: %1.2f\nyaw: %1.2f\nroll: %1.2f\n"404 p y r)))405 prop-data)))410 (defn test-proprioception411 "Testing proprioception:412 You should see two foating bars, and a printout of pitch, yaw, and413 roll. Pressing key-r/key-t should move the blue bar up and down and414 change only the value of pitch. key-f/key-g moves it side to side415 and changes yaw. key-v/key-b will spin the blue segment clockwise416 and counterclockwise, and only affect roll."417 []418 (let [hand (box 0.2 1 0.2 :position (Vector3f. 0 0 0)419 :mass 0 :color ColorRGBA/Green :name "hand")420 finger (box 0.2 1 0.2 :position (Vector3f. 0 2.4 0)421 :mass 1 :color ColorRGBA/Red :name "finger")422 joint-node (box 0.1 0.05 0.05 :color ColorRGBA/Yellow423 :position (Vector3f. 0 1.2 0)424 :rotation (doto (Quaternion.)425 (.fromAngleAxis426 (/ Math/PI 2)427 (Vector3f. 0 0 1)))428 :physical? false)429 joint (join-at-point hand finger (Vector3f. 0 1.2 0 ))430 creature (nodify [hand finger joint-node])431 finger-control (.getControl finger RigidBodyControl)432 hand-control (.getControl hand RigidBodyControl)]435 (let436 ;; *******************************************438 [floor (box 10 10 10 :position (Vector3f. 0 -15 0)439 :mass 0 :color ColorRGBA/Gray)441 root (nodify [creature floor])442 prop (joint-proprioception creature joint-node)443 prop-view (proprioception-debug-window)445 controls446 (merge standard-debug-controls447 {"key-o"448 (fn [_ _] (.setEnabled finger-control true))449 "key-p"450 (fn [_ _] (.setEnabled finger-control false))451 "key-k"452 (fn [_ _] (.setEnabled hand-control true))453 "key-l"454 (fn [_ _] (.setEnabled hand-control false))455 "key-i"456 (fn [world _] (set-gravity world (Vector3f. 0 0 0)))457 "key-period"458 (fn [world _]459 (.setEnabled finger-control false)460 (.setEnabled hand-control false)461 (.rotate creature (doto (Quaternion.)462 (.fromAngleAxis463 (float (/ Math/PI 15))464 (Vector3f. 0 0 -1))))466 (.setEnabled finger-control true)467 (.setEnabled hand-control true)468 (set-gravity world (Vector3f. 0 0 0))469 )472 }473 )475 ]476 (comment477 (.setCollisionGroup478 (.getControl hand RigidBodyControl)479 PhysicsCollisionObject/COLLISION_GROUP_NONE)480 )481 (apply482 world483 (with-movement484 hand485 ["key-y" "key-u" "key-h" "key-j" "key-n" "key-m"]486 [10 10 10 10 1 1]487 (with-movement488 finger489 ["key-r" "key-t" "key-f" "key-g" "key-v" "key-b"]490 [1 1 10 10 10 10]491 [root492 controls493 (fn [world]494 (.setTimer world (com.aurellem.capture.RatchetTimer. 60))495 (set-gravity world (Vector3f. 0 0 0))496 (light-up-everything world))497 (fn [_ _] (prop-view (list (prop))))]))))))499 #+end_src501 #+results: test-body502 : #'cortex.test.body/test-proprioception505 * COMMENT code-limbo506 #+begin_src clojure507 ;;(.loadModel508 ;; (doto (asset-manager)509 ;; (.registerLoader BlenderModelLoader (into-array String ["blend"])))510 ;; "Models/person/person.blend")513 (defn load-blender-model514 "Load a .blend file using an asset folder relative path."515 [^String model]516 (.loadModel517 (doto (asset-manager)518 (.registerLoader BlenderModelLoader (into-array String ["blend"])))519 model))522 (defn view-model [^String model]523 (view524 (.loadModel525 (doto (asset-manager)526 (.registerLoader BlenderModelLoader (into-array String ["blend"])))527 model)))529 (defn load-blender-scene [^String model]530 (.loadModel531 (doto (asset-manager)532 (.registerLoader BlenderLoader (into-array String ["blend"])))533 model))535 (defn worm536 []537 (.loadModel (asset-manager) "Models/anim2/Cube.mesh.xml"))539 (defn oto540 []541 (.loadModel (asset-manager) "Models/Oto/Oto.mesh.xml"))543 (defn sinbad544 []545 (.loadModel (asset-manager) "Models/Sinbad/Sinbad.mesh.xml"))547 (defn worm-blender548 []549 (first (seq (.getChildren (load-blender-model550 "Models/anim2/simple-worm.blend")))))552 (defn body553 "given a node with a SkeletonControl, will produce a body sutiable554 for AI control with movement and proprioception."555 [node]556 (let [skeleton-control (.getControl node SkeletonControl)557 krc (KinematicRagdollControl.)]558 (comment559 (dorun560 (map #(.addBoneName krc %)561 ["mid2" "tail" "head" "mid1" "mid3" "mid4" "Dummy-Root" ""]562 ;;"mid2" "mid3" "tail" "head"]563 )))564 (.addControl node krc)565 (.setRagdollMode krc)566 )567 node568 )569 (defn show-skeleton [node]570 (let [sd572 (doto573 (SkeletonDebugger. "aurellem-skel-debug"574 (skel node))575 (.setMaterial (green-x-ray)))]576 (.attachChild node sd)577 node))581 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;583 ;; this could be a good way to give objects special properties like584 ;; being eyes and the like586 (.getUserData587 (.getChild588 (load-blender-model "Models/property/test.blend") 0)589 "properties")591 ;; the properties are saved along with the blender file.592 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;597 (defn init-debug-skel-node598 [f debug-node skeleton]599 (let [bones600 (map #(.getBone skeleton %)601 (range (.getBoneCount skeleton)))]602 (dorun (map #(.setUserControl % true) bones))603 (dorun (map (fn [b]604 (println (.getName b)605 " -- " (f b)))606 bones))607 (dorun608 (map #(.attachChild609 debug-node610 (doto611 (sphere 0.1612 :position (f %)613 :physical? false)614 (.setMaterial (green-x-ray))))615 bones)))616 debug-node)618 (import jme3test.bullet.PhysicsTestHelper)621 (defn test-zzz [the-worm world value]622 (if (not value)623 (let [skeleton (skel the-worm)]624 (println-repl "enabling bones")625 (dorun626 (map627 #(.setUserControl (.getBone skeleton %) true)628 (range (.getBoneCount skeleton))))631 (let [b (.getBone skeleton 2)]632 (println-repl "moving " (.getName b))633 (println-repl (.getLocalPosition b))634 (.setUserTransforms b635 Vector3f/UNIT_X636 Quaternion/IDENTITY637 ;;(doto (Quaternion.)638 ;; (.fromAngles (/ Math/PI 2)639 ;; 0640 ;; 0642 (Vector3f. 1 1 1))643 )645 (println-repl "hi! <3"))))648 (defn test-ragdoll []650 (let [the-worm652 ;;(.loadModel (asset-manager) "Models/anim2/Cube.mesh.xml")653 (doto (show-skeleton (worm-blender))654 (.setLocalTranslation (Vector3f. 0 10 0))655 ;;(worm)656 ;;(oto)657 ;;(sinbad)658 )659 ]662 (.start663 (world664 (doto (Node.)665 (.attachChild the-worm))666 {"key-return" (fire-cannon-ball)667 "key-space" (partial test-zzz the-worm)668 }669 (fn [world]670 (light-up-everything world)671 (PhysicsTestHelper/createPhysicsTestWorld672 (.getRootNode world)673 (asset-manager)674 (.getPhysicsSpace675 (.getState (.getStateManager world) BulletAppState)))676 (set-gravity world Vector3f/ZERO)677 ;;(.setTimer world (NanoTimer.))678 ;;(org.lwjgl.input.Mouse/setGrabbed false)679 )680 no-op681 )684 )))687 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;688 ;;; here is the ragdoll stuff690 (def worm-mesh (.getMesh (.getChild (worm-blender) 0)))691 (def mesh worm-mesh)693 (.getFloatBuffer mesh VertexBuffer$Type/Position)694 (.getFloatBuffer mesh VertexBuffer$Type/BoneWeight)695 (.getData (.getBuffer mesh VertexBuffer$Type/BoneIndex))698 (defn position [index]699 (.get700 (.getFloatBuffer worm-mesh VertexBuffer$Type/Position)701 index))703 (defn bones [index]704 (.get705 (.getData (.getBuffer mesh VertexBuffer$Type/BoneIndex))706 index))708 (defn bone-weights [index]709 (.get710 (.getFloatBuffer mesh VertexBuffer$Type/BoneWeight)711 index))715 (defn vertex-bones [vertex]716 (vec (map (comp int bones) (range (* vertex 4) (+ (* vertex 4) 4)))))718 (defn vertex-weights [vertex]719 (vec (map (comp float bone-weights) (range (* vertex 4) (+ (* vertex 4) 4)))))721 (defn vertex-position [index]722 (let [offset (* index 3)]723 (Vector3f. (position offset)724 (position (inc offset))725 (position (inc(inc offset))))))727 (def vertex-info (juxt vertex-position vertex-bones vertex-weights))729 (defn bone-control-color [index]730 (get {[1 0 0 0] ColorRGBA/Red731 [1 2 0 0] ColorRGBA/Magenta732 [2 0 0 0] ColorRGBA/Blue}733 (vertex-bones index)734 ColorRGBA/White))736 (defn influence-color [index bone-num]737 (get738 {(float 0) ColorRGBA/Blue739 (float 0.5) ColorRGBA/Green740 (float 1) ColorRGBA/Red}741 ;; find the weight of the desired bone742 ((zipmap (vertex-bones index)(vertex-weights index))743 bone-num)744 ColorRGBA/Blue))746 (def worm-vertices (set (map vertex-info (range 60))))749 (defn test-info []750 (let [points (Node.)]751 (dorun752 (map #(.attachChild points %)753 (map #(sphere 0.01754 :position (vertex-position %)755 :color (influence-color % 1)756 :physical? false)757 (range 60))))758 (view points)))761 (defrecord JointControl [joint physics-space]762 PhysicsControl763 (setPhysicsSpace [this space]764 (dosync765 (ref-set (:physics-space this) space))766 (.addJoint space (:joint this)))767 (update [this tpf])768 (setSpatial [this spatial])769 (render [this rm vp])770 (getPhysicsSpace [this] (deref (:physics-space this)))771 (isEnabled [this] true)772 (setEnabled [this state]))774 (defn add-joint775 "Add a joint to a particular object. When the object is added to the776 PhysicsSpace of a simulation, the joint will also be added"777 [object joint]778 (let [control (JointControl. joint (ref nil))]779 (.addControl object control))780 object)783 (defn hinge-world784 []785 (let [sphere1 (sphere)786 sphere2 (sphere 1 :position (Vector3f. 3 3 3))787 joint (Point2PointJoint.788 (.getControl sphere1 RigidBodyControl)789 (.getControl sphere2 RigidBodyControl)790 Vector3f/ZERO (Vector3f. 3 3 3))]791 (add-joint sphere1 joint)792 (doto (Node. "hinge-world")793 (.attachChild sphere1)794 (.attachChild sphere2))))797 (defn test-joint []798 (view (hinge-world)))800 ;; (defn copier-gen []801 ;; (let [count (atom 0)]802 ;; (fn [in]803 ;; (swap! count inc)804 ;; (clojure.contrib.duck-streams/copy805 ;; in (File. (str "/home/r/tmp/mao-test/clojure-images/"806 ;; ;;/home/r/tmp/mao-test/clojure-images807 ;; (format "%08d.png" @count)))))))808 ;; (defn decrease-framerate []809 ;; (map810 ;; (copier-gen)811 ;; (sort812 ;; (map first813 ;; (partition814 ;; 4815 ;; (filter #(re-matches #".*.png$" (.getCanonicalPath %))816 ;; (file-seq817 ;; (file-str818 ;; "/home/r/media/anime/mao-temp/images"))))))))822 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;824 (defn proprioception825 "Create a proprioception map that reports the rotations of the826 various limbs of the creature's body"827 [creature]828 [#^Node creature]829 (let [830 nodes (node-seq creature)831 joints832 (map833 :joint834 (filter835 #(isa? (class %) JointControl)836 (reduce837 concat838 (map (fn [node]839 (map (fn [num] (.getControl node num))840 (range (.getNumControls node))))841 nodes))))]842 (fn []843 (reduce concat (map relative-positions (list (first joints)))))))846 (defn skel [node]847 (doto848 (.getSkeleton849 (.getControl node SkeletonControl))850 ;; this is necessary to force the skeleton to have accurate world851 ;; transforms before it is rendered to the screen.852 (.resetAndUpdate)))854 (defn green-x-ray []855 (doto (Material. (asset-manager)856 "Common/MatDefs/Misc/Unshaded.j3md")857 (.setColor "Color" ColorRGBA/Green)858 (-> (.getAdditionalRenderState)859 (.setDepthTest false))))861 (defn test-worm []862 (.start863 (world864 (doto (Node.)865 ;;(.attachChild (point-worm))866 (.attachChild (load-blender-model867 "Models/anim2/joint-worm.blend"))869 (.attachChild (box 10 1 10870 :position (Vector3f. 0 -2 0) :mass 0871 :color (ColorRGBA/Gray))))872 {873 "key-space" (fire-cannon-ball)874 }875 (fn [world]876 (enable-debug world)877 (light-up-everything world)878 ;;(.setTimer world (NanoTimer.))879 )880 no-op)))884 ;; defunct movement stuff885 (defn torque-controls [control]886 (let [torques887 (concat888 (map #(Vector3f. 0 (Math/sin %) (Math/cos %))889 (range 0 (* Math/PI 2) (/ (* Math/PI 2) 20)))890 [Vector3f/UNIT_X])]891 (map (fn [torque-axis]892 (fn [torque]893 (.applyTorque894 control895 (.mult (.mult (.getPhysicsRotation control)896 torque-axis)897 (float898 (* (.getMass control) torque))))))899 torques)))901 (defn motor-map902 "Take a creature and generate a function that will enable fine903 grained control over all the creature's limbs."904 [#^Node creature]905 (let [controls (keep #(.getControl % RigidBodyControl)906 (node-seq creature))907 limb-controls (reduce concat (map torque-controls controls))908 body-control (partial map #(%1 %2) limb-controls)]909 body-control))911 (defn test-motor-map912 "see how torque works."913 []914 (let [finger (box 3 0.5 0.5 :position (Vector3f. 0 2 0)915 :mass 1 :color ColorRGBA/Green)916 motor-map (motor-map finger)]917 (world918 (nodify [finger919 (box 10 0.5 10 :position (Vector3f. 0 -5 0) :mass 0920 :color ColorRGBA/Gray)])921 standard-debug-controls922 (fn [world]923 (set-gravity world Vector3f/ZERO)924 (light-up-everything world)925 (.setTimer world (NanoTimer.)))926 (fn [_ _]927 (dorun (motor-map [0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0928 0]))))))930 (defn joint-proprioception [#^Node parts #^Node joint]931 (let [[obj-a obj-b] (joint-targets parts joint)932 joint-rot (.getWorldRotation joint)933 pre-inv-a (.inverse (.getWorldRotation obj-a))934 x (.mult pre-inv-a (.mult joint-rot Vector3f/UNIT_X))935 y (.mult pre-inv-a (.mult joint-rot Vector3f/UNIT_Y))936 z (.mult pre-inv-a (.mult joint-rot Vector3f/UNIT_Z))938 x Vector3f/UNIT_Y939 y Vector3f/UNIT_Z940 z Vector3f/UNIT_X943 tmp-rot-a (.getWorldRotation obj-a)]944 (println-repl "x:" (.mult tmp-rot-a x))945 (println-repl "y:" (.mult tmp-rot-a y))946 (println-repl "z:" (.mult tmp-rot-a z))947 (println-repl "rot-a" (.getWorldRotation obj-a))948 (println-repl "rot-b" (.getWorldRotation obj-b))949 (println-repl "joint-rot" joint-rot)950 ;; this function will report proprioceptive information for the951 ;; joint.952 (fn []953 ;; x is the "twist" axis, y and z are the "bend" axes954 (let [rot-a (.getWorldRotation obj-a)955 ;;inv-a (.inverse rot-a)956 rot-b (.getWorldRotation obj-b)957 ;;relative (.mult rot-b inv-a)958 basis (doto (Matrix3f.)959 (.setColumn 0 (.mult rot-a x))960 (.setColumn 1 (.mult rot-a y))961 (.setColumn 2 (.mult rot-a z)))962 rotation-about-joint963 (doto (Quaternion.)964 (.fromRotationMatrix965 (.mult (.invert basis)966 (.toRotationMatrix rot-b))))967 [yaw roll pitch]968 (seq (.toAngles rotation-about-joint nil))]969 ;;return euler angles of the quaternion around the new basis970 [yaw roll pitch]))))972 #+end_src980 * COMMENT generate Source981 #+begin_src clojure :tangle ../src/cortex/body.clj982 <<proprioception>>983 <<motor-control>>984 #+end_src986 #+begin_src clojure :tangle ../src/cortex/test/body.clj987 <<test-body>>988 #+end_src