Mercurial > cortex
view org/test-creature.org @ 116:947bef5d6670
working on eye-following camera
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Fri, 20 Jan 2012 01:07:46 -0700 |
parents | 247860e25536 |
children | 94c005f7f9dd |
line wrap: on
line source
1 #+title: First attempt at a creature!2 #+author: Robert McIntyre3 #+email: rlm@mit.edu4 #+description:5 #+keywords: simulation, jMonkeyEngine3, clojure6 #+SETUPFILE: ../../aurellem/org/setup.org7 #+INCLUDE: ../../aurellem/org/level-0.org9 * objectives10 - [X] get an overall bitmap-like image for touch11 - [X] write code to visuliaze this bitmap12 - [ ] directly change the UV-pixels to show touch sensor activation13 - [ ] write an explination for why b&w bitmaps for senses is appropiate14 - [ ] clean up touch code and write visulazation test15 - [ ] do the same for eyes17 * Intro18 So far, I've made the following senses --19 - Vision20 - Hearing21 - Touch22 - Proprioception24 And one effector:25 - Movement27 However, the code so far has only enabled these senses, but has not28 actually implemented them. For example, there is still a lot of work29 to be done for vision. I need to be able to create an /eyeball/ in30 simulation that can be moved around and see the world from different31 angles. I also need to determine weather to use log-polar or cartesian32 for the visual input, and I need to determine how/wether to33 disceritise the visual input.35 I also want to be able to visualize both the sensors and the36 effectors in pretty pictures. This semi-retarted creature will be my37 first attempt at bringing everything together.39 * The creature's body41 Still going to do an eve-like body in blender, but due to problems42 importing the joints, etc into jMonkeyEngine3, I'm going to do all43 the connecting here in clojure code, using the names of the individual44 components and trial and error. Later, I'll maybe make some sort of45 creature-building modifications to blender that support whatever46 discreitized senses I'm going to make.48 #+name: body-149 #+begin_src clojure50 (ns cortex.silly51 "let's play!"52 {:author "Robert McIntyre"})54 ;; TODO remove this!55 (require 'cortex.import)56 (cortex.import/mega-import-jme3)57 (use '(cortex world util body hearing touch vision))59 (rlm.rlm-commands/help)60 (import java.awt.image.BufferedImage)61 (import javax.swing.JPanel)62 (import javax.swing.SwingUtilities)63 (import java.awt.Dimension)64 (import javax.swing.JFrame)65 (import java.awt.Dimension)66 (import com.aurellem.capture.RatchetTimer)67 (declare joint-create)68 (use 'clojure.contrib.def)70 (defn points->image71 "Take a sparse collection of points and visuliaze it as a72 BufferedImage."74 ;; TODO maybe parallelize this since it's easy76 [points]77 (if (empty? points)78 (BufferedImage. 1 1 BufferedImage/TYPE_BYTE_BINARY)79 (let [xs (vec (map first points))80 ys (vec (map second points))81 x0 (apply min xs)82 y0 (apply min ys)83 width (- (apply max xs) x0)84 height (- (apply max ys) y0)85 image (BufferedImage. (inc width) (inc height)86 BufferedImage/TYPE_BYTE_BINARY)]87 (dorun88 (for [index (range (count points))]89 (.setRGB image (- (xs index) x0) (- (ys index) y0) -1)))91 image)))93 (defn average [coll]94 (/ (reduce + coll) (count coll)))96 (defn collapse-1d97 "One dimensional analogue of collapse"98 [center line]99 (let [length (count line)100 num-above (count (filter (partial < center) line))101 num-below (- length num-above)]102 (range (- center num-below)103 (+ center num-above))))105 (defn collapse106 "Take a set of pairs of integers and collapse them into a107 contigous bitmap."108 [points]109 (if (empty? points) []110 (let111 [num-points (count points)112 center (vector113 (int (average (map first points)))114 (int (average (map first points))))115 flattened116 (reduce117 concat118 (map119 (fn [column]120 (map vector121 (map first column)122 (collapse-1d (second center)123 (map second column))))124 (partition-by first (sort-by first points))))125 squeezed126 (reduce127 concat128 (map129 (fn [row]130 (map vector131 (collapse-1d (first center)132 (map first row))133 (map second row)))134 (partition-by second (sort-by second flattened))))135 relocate136 (let [min-x (apply min (map first squeezed))137 min-y (apply min (map second squeezed))]138 (map (fn [[x y]]139 [(- x min-x)140 (- y min-y)])141 squeezed))]142 relocate)))144 (defn load-bullet []145 (let [sim (world (Node.) {} no-op no-op)]146 (doto sim147 (.enqueue148 (fn []149 (.stop sim)))150 (.start))))152 (defn load-blender-model153 "Load a .blend file using an asset folder relative path."154 [^String model]155 (.loadModel156 (doto (asset-manager)157 (.registerLoader BlenderModelLoader (into-array String ["blend"])))158 model))160 (defn meta-data [blender-node key]161 (if-let [data (.getUserData blender-node "properties")]162 (.findValue data key)163 nil))165 (defn blender-to-jme166 "Convert from Blender coordinates to JME coordinates"167 [#^Vector3f in]168 (Vector3f. (.getX in)169 (.getZ in)170 (- (.getY in))))172 (defn jme-to-blender173 "Convert from JME coordinates to Blender coordinates"174 [#^Vector3f in]175 (Vector3f. (.getX in)176 (- (.getZ in))177 (.getY in)))179 (defn joint-targets180 "Return the two closest two objects to the joint object, ordered181 from bottom to top according to the joint's rotation."182 [#^Node parts #^Node joint]183 (loop [radius (float 0.01)]184 (let [results (CollisionResults.)]185 (.collideWith186 parts187 (BoundingBox. (.getWorldTranslation joint)188 radius radius radius)189 results)190 (let [targets191 (distinct192 (map #(.getGeometry %) results))]193 (if (>= (count targets) 2)194 (sort-by195 #(let [v196 (jme-to-blender197 (.mult198 (.inverse (.getWorldRotation joint))199 (.subtract (.getWorldTranslation %)200 (.getWorldTranslation joint))))]201 (println-repl (.getName %) ":" v)202 (.dot (Vector3f. 1 1 1)203 v))204 (take 2 targets))205 (recur (float (* radius 2))))))))207 (defn world-to-local208 "Convert the world coordinates into coordinates relative to the209 object (i.e. local coordinates), taking into account the rotation210 of object."211 [#^Spatial object world-coordinate]212 (let [out (Vector3f.)]213 (.worldToLocal object world-coordinate out) out))215 (defn local-to-world216 "Convert the local coordinates into coordinates into world relative217 coordinates"218 [#^Spatial object local-coordinate]219 (let [world-coordinate (Vector3f.)]220 (.localToWorld object local-coordinate world-coordinate)221 world-coordinate))223 (defmulti joint-dispatch224 "Translate blender pseudo-joints into real JME joints."225 (fn [constraints & _]226 (:type constraints)))228 (defmethod joint-dispatch :point229 [constraints control-a control-b pivot-a pivot-b rotation]230 (println-repl "creating POINT2POINT joint")231 (Point2PointJoint.232 control-a233 control-b234 pivot-a235 pivot-b))237 (defmethod joint-dispatch :hinge238 [constraints control-a control-b pivot-a pivot-b rotation]239 (println-repl "creating HINGE joint")240 (let [axis241 (if-let242 [axis (:axis constraints)]243 axis244 Vector3f/UNIT_X)245 [limit-1 limit-2] (:limit constraints)246 hinge-axis247 (.mult248 rotation249 (blender-to-jme axis))]250 (doto251 (HingeJoint.252 control-a253 control-b254 pivot-a255 pivot-b256 hinge-axis257 hinge-axis)258 (.setLimit limit-1 limit-2))))260 (defmethod joint-dispatch :cone261 [constraints control-a control-b pivot-a pivot-b rotation]262 (let [limit-xz (:limit-xz constraints)263 limit-xy (:limit-xy constraints)264 twist (:twist constraints)]266 (println-repl "creating CONE joint")267 (println-repl rotation)268 (println-repl269 "UNIT_X --> " (.mult rotation (Vector3f. 1 0 0)))270 (println-repl271 "UNIT_Y --> " (.mult rotation (Vector3f. 0 1 0)))272 (println-repl273 "UNIT_Z --> " (.mult rotation (Vector3f. 0 0 1)))274 (doto275 (ConeJoint.276 control-a277 control-b278 pivot-a279 pivot-b280 rotation281 rotation)282 (.setLimit (float limit-xz)283 (float limit-xy)284 (float twist)))))286 (defn connect287 "here are some examples:288 {:type :point}289 {:type :hinge :limit [0 (/ Math/PI 2)] :axis (Vector3f. 0 1 0)}290 (:axis defaults to (Vector3f. 1 0 0) if not provided for hinge joints)292 {:type :cone :limit-xz 0]293 :limit-xy 0]294 :twist 0]} (use XZY rotation mode in blender!)"295 [#^Node obj-a #^Node obj-b #^Node joint]296 (let [control-a (.getControl obj-a RigidBodyControl)297 control-b (.getControl obj-b RigidBodyControl)298 joint-center (.getWorldTranslation joint)299 joint-rotation (.toRotationMatrix (.getWorldRotation joint))300 pivot-a (world-to-local obj-a joint-center)301 pivot-b (world-to-local obj-b joint-center)]303 (if-let [constraints304 (map-vals305 eval306 (read-string307 (meta-data joint "joint")))]308 ;; A side-effect of creating a joint registers309 ;; it with both physics objects which in turn310 ;; will register the joint with the physics system311 ;; when the simulation is started.312 (do313 (println-repl "creating joint between"314 (.getName obj-a) "and" (.getName obj-b))315 (joint-dispatch constraints316 control-a control-b317 pivot-a pivot-b318 joint-rotation))319 (println-repl "could not find joint meta-data!"))))321 (defn assemble-creature [#^Node pieces joints]322 (dorun323 (map324 (fn [geom]325 (let [physics-control326 (RigidBodyControl.327 (HullCollisionShape.328 (.getMesh geom))329 (if-let [mass (meta-data geom "mass")]330 (do331 (println-repl332 "setting" (.getName geom) "mass to" (float mass))333 (float mass))334 (float 1)))]336 (.addControl geom physics-control)))337 (filter #(isa? (class %) Geometry )338 (node-seq pieces))))339 (dorun340 (map341 (fn [joint]342 (let [[obj-a obj-b]343 (joint-targets pieces joint)]344 (connect obj-a obj-b joint)))345 joints))346 pieces)348 (declare blender-creature)350 (def hand "Models/creature1/one.blend")352 (def worm "Models/creature1/try-again.blend")354 (def touch "Models/creature1/touch.blend")356 (defn worm-model [] (load-blender-model worm))358 (defn x-ray [#^ColorRGBA color]359 (doto (Material. (asset-manager)360 "Common/MatDefs/Misc/Unshaded.j3md")361 (.setColor "Color" color)362 (-> (.getAdditionalRenderState)363 (.setDepthTest false))))365 (defn colorful []366 (.getChild (worm-model) "worm-21"))368 (import jme3tools.converters.ImageToAwt)370 (import ij.ImagePlus)372 ;; Every Mesh has many triangles, each with its own index.373 ;; Every vertex has its own index as well.375 (defn tactile-sensor-image376 "Return the touch-sensor distribution image in BufferedImage format,377 or nil if it does not exist."378 [#^Geometry obj]379 (if-let [image-path (meta-data obj "touch")]380 (ImageToAwt/convert381 (.getImage382 (.loadTexture383 (asset-manager)384 image-path))385 false false 0)))387 (import ij.process.ImageProcessor)388 (import java.awt.image.BufferedImage)390 (def white -1)392 (defn filter-pixels393 "List the coordinates of all pixels matching pred, within the bounds394 provided. Bounds -> [x0 y0 width height]"395 {:author "Dylan Holmes"}396 ([pred #^BufferedImage image]397 (filter-pixels pred image [0 0 (.getWidth image) (.getHeight image)]))398 ([pred #^BufferedImage image [x0 y0 width height]]399 ((fn accumulate [x y matches]400 (cond401 (>= y (+ height y0)) matches402 (>= x (+ width x0)) (recur 0 (inc y) matches)403 (pred (.getRGB image x y))404 (recur (inc x) y (conj matches [x y]))405 :else (recur (inc x) y matches)))406 x0 y0 [])))408 (defn white-coordinates409 "Coordinates of all the white pixels in a subset of the image."410 ([#^BufferedImage image bounds]411 (filter-pixels #(= % white) image bounds))412 ([#^BufferedImage image]413 (filter-pixels #(= % white) image)))415 (defn triangle416 "Get the triangle specified by triangle-index from the mesh within417 bounds."418 [#^Mesh mesh triangle-index]419 (let [scratch (Triangle.)]420 (.getTriangle mesh triangle-index scratch)421 scratch))423 (defn triangle-vertex-indices424 "Get the triangle vertex indices of a given triangle from a given425 mesh."426 [#^Mesh mesh triangle-index]427 (let [indices (int-array 3)]428 (.getTriangle mesh triangle-index indices)429 (vec indices)))431 (defn vertex-UV-coord432 "Get the uv-coordinates of the vertex named by vertex-index"433 [#^Mesh mesh vertex-index]434 (let [UV-buffer435 (.getData436 (.getBuffer437 mesh438 VertexBuffer$Type/TexCoord))]439 [(.get UV-buffer (* vertex-index 2))440 (.get UV-buffer (+ 1 (* vertex-index 2)))]))442 (defn triangle-UV-coord443 "Get the uv-cooridnates of the triangle's verticies."444 [#^Mesh mesh width height triangle-index]445 (map (fn [[u v]] (vector (* width u) (* height v)))446 (map (partial vertex-UV-coord mesh)447 (triangle-vertex-indices mesh triangle-index))))449 (defn same-side?450 "Given the points p1 and p2 and the reference point ref, is point p451 on the same side of the line that goes through p1 and p2 as ref is?"452 [p1 p2 ref p]453 (<=454 0455 (.dot456 (.cross (.subtract p2 p1) (.subtract p p1))457 (.cross (.subtract p2 p1) (.subtract ref p1)))))459 (defn triangle-seq [#^Triangle tri]460 [(.get1 tri) (.get2 tri) (.get3 tri)])462 (defn vector3f-seq [#^Vector3f v]463 [(.getX v) (.getY v) (.getZ v)])465 (defn inside-triangle?466 "Is the point inside the triangle?"467 {:author "Dylan Holmes"}468 [#^Triangle tri #^Vector3f p]469 (let [[vert-1 vert-2 vert-3] (triangle-seq tri)]470 (and471 (same-side? vert-1 vert-2 vert-3 p)472 (same-side? vert-2 vert-3 vert-1 p)473 (same-side? vert-3 vert-1 vert-2 p))))475 (defn triangle->matrix4f476 "Converts the triangle into a 4x4 matrix: The first three columns477 contain the vertices of the triangle; the last contains the unit478 normal of the triangle. The bottom row is filled with 1s."479 [#^Triangle t]480 (let [mat (Matrix4f.)481 [vert-1 vert-2 vert-3]482 ((comp vec map) #(.get t %) (range 3))483 unit-normal (do (.calculateNormal t)(.getNormal t))484 vertices [vert-1 vert-2 vert-3 unit-normal]]485 (dorun486 (for [row (range 4) col (range 3)]487 (do488 (.set mat col row (.get (vertices row)col))489 (.set mat 3 row 1))))490 mat))492 (defn triangle-transformation493 "Returns the affine transformation that converts each vertex in the494 first triangle into the corresponding vertex in the second495 triangle."496 [#^Triangle tri-1 #^Triangle tri-2]497 (.mult498 (triangle->matrix4f tri-2)499 (.invert (triangle->matrix4f tri-1))))501 (defn point->vector2f [[u v]]502 (Vector2f. u v))504 (defn vector2f->vector3f [v]505 (Vector3f. (.getX v) (.getY v) 0))507 (defn map-triangle [f #^Triangle tri]508 (Triangle.509 (f 0 (.get1 tri))510 (f 1 (.get2 tri))511 (f 2 (.get3 tri))))513 (defn points->triangle514 "Convert a list of points into a triangle."515 [points]516 (apply #(Triangle. %1 %2 %3)517 (map (fn [point]518 (let [point (vec point)]519 (Vector3f. (get point 0 0)520 (get point 1 0)521 (get point 2 0))))522 (take 3 points))))524 (defn convex-bounds525 "Dimensions of the smallest integer bounding square of the list of526 2D verticies in the form: [x y width height]."527 [uv-verts]528 (let [xs (map first uv-verts)529 ys (map second uv-verts)530 x0 (Math/floor (apply min xs))531 y0 (Math/floor (apply min ys))532 x1 (Math/ceil (apply max xs))533 y1 (Math/ceil (apply max ys))]534 [x0 y0 (- x1 x0) (- y1 y0)]))536 (defn sensors-in-triangle537 "Find the locations of the touch sensors within a triangle in both538 UV and gemoetry relative coordinates."539 [image mesh tri-index]540 (let [width (.getWidth image)541 height (.getHeight image)542 UV-vertex-coords (triangle-UV-coord mesh width height tri-index)543 bounds (convex-bounds UV-vertex-coords)545 cutout-triangle (points->triangle UV-vertex-coords)546 UV-sensor-coords547 (filter (comp (partial inside-triangle? cutout-triangle)548 (fn [[u v]] (Vector3f. u v 0)))549 (white-coordinates image bounds))550 UV->geometry (triangle-transformation551 cutout-triangle552 (triangle mesh tri-index))553 geometry-sensor-coords554 (map (fn [[u v]] (.mult UV->geometry (Vector3f. u v 0)))555 UV-sensor-coords)]556 {:UV UV-sensor-coords :geometry geometry-sensor-coords}))558 (defn-memo locate-feelers559 "Search the geometry's tactile UV image for touch sensors, returning560 their positions in geometry-relative coordinates."561 [#^Geometry geo]562 (let [mesh (.getMesh geo)563 num-triangles (.getTriangleCount mesh)]564 (if-let [image (tactile-sensor-image geo)]565 (map566 (partial sensors-in-triangle image mesh)567 (range num-triangles))568 (repeat (.getTriangleCount mesh) {:UV nil :geometry nil}))))570 (use 'clojure.contrib.def)572 (defn-memo touch-topology [#^Gemoetry geo]573 (vec (collapse (reduce concat (map :UV (locate-feelers geo))))))575 (defn-memo feeler-coordinates [#^Geometry geo]576 (vec (map :geometry (locate-feelers geo))))578 (defn enable-touch [#^Geometry geo]579 (let [feeler-coords (feeler-coordinates geo)580 tris (triangles geo)581 limit 0.1582 ;;results (CollisionResults.)583 ]584 (if (empty? (touch-topology geo))585 nil586 (fn [node]587 (let [sensor-origins588 (map589 #(map (partial local-to-world geo) %)590 feeler-coords)591 triangle-normals592 (map (partial get-ray-direction geo)593 tris)594 rays595 (flatten596 (map (fn [origins norm]597 (map #(doto (Ray. % norm)598 (.setLimit limit)) origins))599 sensor-origins triangle-normals))]600 (vector601 (touch-topology geo)602 (vec603 (for [ray rays]604 (do605 (let [results (CollisionResults.)]606 (.collideWith node ray results)607 (let [touch-objects608 (set609 (filter #(not (= geo %))610 (map #(.getGeometry %) results)))]611 (if (> (count touch-objects) 0)612 1 0))))))))))))614 (defn touch [#^Node pieces]615 (filter (comp not nil?)616 (map enable-touch617 (filter #(isa? (class %) Geometry)618 (node-seq pieces)))))621 ;; human eye transmits 62kb/s to brain Bandwidth is 8.75 Mb/s622 ;; http://en.wikipedia.org/wiki/Retina624 (defn test-eye []625 (.getChild (worm-model) "worm-11"))628 (defn retina-sensor-image629 "Return a map of pixel selection functions to BufferedImages630 describing the distribution of light-sensitive components on this631 geometry's surface. Each function creates an integer from the rgb632 values found in the pixel. :red, :green, :blue, :gray are already633 defined as extracting the red green blue and average components634 respectively."635 [#^Geometry eye]636 (if-let [eye-map (meta-data eye "eye")]637 (map-vals638 #(ImageToAwt/convert639 (.getImage (.loadTexture (asset-manager) %))640 false false 0)641 (read-string642 eye-map))))644 (defn creature-eyes645 "The eye nodes which are children of the \"eyes\" node in the646 creature."647 [#^Node creature]648 (if-let [eye-node (.getChild creature "eyes")]649 (seq (.getChildren eye-node))650 (do (println-repl "could not find eyes node") [])))653 ;; Here's how vision will work.655 ;; Make the continuation in scene-processor take FrameBuffer,656 ;; byte-buffer, BufferedImage already sized to the correct657 ;; dimensions. the continuation will decide wether to "mix" them658 ;; into the BufferedImage, lazily ignore them, or mix them halfway659 ;; and call c/graphics card routines.661 ;; (vision creature) will take an optional :skip argument which will662 ;; inform the continuations in scene processor to skip the given663 ;; number of cycles; 0 means that no cycles will be skipped.665 ;; (vision creature) will return [init-functions sensor-functions].666 ;; The init-functions are each single-arg functions that take the667 ;; world and register the cameras and must each be called before the668 ;; corresponding sensor-functions. Each init-function returns the669 ;; viewport for that eye which can be manipulated, saved, etc. Each670 ;; sensor-function is a thunk and will return data in the same671 ;; format as the tactile-sensor functions; the structure is672 ;; [topology, sensor-data]. Internally, these sensor-functions673 ;; maintain a reference to sensor-data which is periodically updated674 ;; by the continuation function established by its init-function.675 ;; They can be queried every cycle, but their information may not676 ;; necessairly be different every cycle.678 ;; Each eye in the creature in blender will work the same way as679 ;; joints -- a one dimensional object with no geometry whose local680 ;; coordinate system determines the orientation of the resulting681 ;; eye. All eyes will have a parent named "eyes" just as all joints682 ;; have a parent named "joints". The resulting camera will be a683 ;; ChaseCamera or a CameraNode bound to the geo that is closest to684 ;; the eye marker. The eye marker will contain the metadata for the685 ;; eye, and will be moved by it's bound geometry. The dimensions of686 ;; the eye's camera are equal to the dimensions of the eye's "UV"687 ;; map.689 (defn eye-target690 "The closest object in creature to eye."691 [#^Node creature #^Node eye]692 (loop [radius (float 0.01)]693 (let [results (CollisionResults.)]694 (.collideWith695 creature696 (BoundingBox. (.getWorldTranslation eye)697 radius radius radius)698 results)699 (if-let [target (first results)]700 (.getGeometry target)701 (recur (float (* 2 radius)))))))703 (defn attach-eyes704 "For each eye in the creature, attach a CameraNode to the appropiate705 area and return the Camera."706 [#^Node creature]707 (for [eye (creature-eyes creature)]708 (let [target (eye-target creature eye)]709 (CameraNode710 )712 (defn vision714 ;; need to create a camera based on uv image,715 ;; update this camera every frame based on the position of this716 ;; geometry. (maybe can get cam to follow the object)718 ;; use a stack for the continuation to grab the image.721 [#^Geometry eye]726 )729 (defn blender-creature730 "Return a creature with all joints in place."731 [blender-path]732 (let [model (load-blender-model blender-path)733 joints734 (if-let [joint-node (.getChild model "joints")]735 (seq (.getChildren joint-node))736 (do (println-repl "could not find joints node") []))]737 (assemble-creature model joints)))744 (defn debug-window745 "creates function that offers a debug view of sensor data"746 []747 (let [vi (view-image)]748 (fn749 [[coords sensor-data]]750 (let [image (points->image coords)]751 (dorun752 (for [i (range (count coords))]753 (.setRGB image ((coords i) 0) ((coords i) 1)754 ({0 -16777216755 1 -1} (sensor-data i)))))756 (vi image)))))759 ;;(defn test-touch [world creature]762 (defn test-creature [thing]763 (let [x-axis764 (box 1 0.01 0.01 :physical? false :color ColorRGBA/Red)765 y-axis766 (box 0.01 1 0.01 :physical? false :color ColorRGBA/Green)767 z-axis768 (box 0.01 0.01 1 :physical? false :color ColorRGBA/Blue)769 creature (blender-creature thing)770 touch-nerves (touch creature)771 touch-debug-windows (map (fn [_] (debug-window)) touch-nerves)772 ]773 (world774 (nodify [creature775 (box 10 2 10 :position (Vector3f. 0 -9 0)776 :color ColorRGBA/Gray :mass 0)777 x-axis y-axis z-axis778 ])779 standard-debug-controls780 (fn [world]781 (light-up-everything world)782 (enable-debug world)783 ;;(com.aurellem.capture.Capture/captureVideo784 ;; world (file-str "/home/r/proj/ai-videos/hand"))785 ;;(.setTimer world (RatchetTimer. 60))786 ;;(speed-up world)787 ;;(set-gravity world (Vector3f. 0 0 0))788 )789 (fn [world tpf]790 ;;(dorun791 ;; (map #(%1 %2) touch-nerves (repeat (.getRootNode world))))793 (dorun794 (map #(%1 (%2 (.getRootNode world)))795 touch-debug-windows touch-nerves)796 )798 )799 ;;(let [timer (atom 0)]800 ;; (fn [_ _]801 ;; (swap! timer inc)802 ;; (if (= (rem @timer 60) 0)803 ;; (println-repl (float (/ @timer 60))))))804 )))814 ;;; experiments in collisions818 (defn collision-test []819 (let [b-radius 1820 b-position (Vector3f. 0 0 0)821 obj-b (box 1 1 1 :color ColorRGBA/Blue822 :position b-position823 :mass 0)824 node (nodify [obj-b])825 bounds-b826 (doto (Picture.)827 (.setHeight 50)828 (.setWidth 50)829 (.setImage (asset-manager)830 "Models/creature1/hand.png"831 false832 ))834 ;;(Ray. (Vector3f. 0 -5 0) (.normalize (Vector3f. 0 1 0)))836 collisions837 (let [cr (CollisionResults.)]838 (.collideWith node bounds-b cr)839 (println (map #(.getContactPoint %) cr))840 cr)842 ;;collision-points843 ;;(map #(sphere 0.1 :position (.getContactPoint %))844 ;; collisions)846 ;;node (nodify (conj collision-points obj-b))848 sim849 (world node850 {"key-space"851 (fn [_ value]852 (if value853 (let [cr (CollisionResults.)]854 (.collideWith node bounds-b cr)855 (println-repl (map #(.getContactPoint %) cr))856 cr)))}857 no-op858 no-op)860 ]861 sim863 ))866 ;; the camera will stay in its initial position/rotation with relation867 ;; to the spatial.869 (defn bind-camera [#^Spatial obj #^Camera cam]870 (let [cam-offset (.subtract (.getLocation cam)871 (.getWorldTranslation obj))872 initial-cam-rotation (.getRotation cam)873 base-anti-rotation (.inverse (.getWorldRotation obj))]874 (.addControl875 obj876 (proxy [AbstractControl] []877 (controlUpdate [tpf]878 (let [total-rotation879 (.mult base-anti-rotation (.getWorldRotation obj))]881 (.setLocation cam882 (.add883 (.mult total-rotation cam-offset)884 (.getWorldTranslation obj)))885 (.setRotation cam886 initial-cam-rotation)887 ;;(.mult total-rotation initial-cam-rotation)889 ))891 (controlRender [_ _])))))895 (defn follow-test []896 (let [camera-pos (Vector3f. 0 30 0)897 rock (box 1 1 1 :color ColorRGBA/Blue898 :position (Vector3f. 0 10 0)899 :mass 30900 )902 table (box 3 1 10 :color ColorRGBA/Gray :mass 0903 :position (Vector3f. 0 -3 0))]905 (world906 (nodify [rock table])907 standard-debug-controls908 (fn [world]909 (let910 [cam (doto (.clone (.getCamera world))911 (.setLocation camera-pos)912 (.lookAt Vector3f/ZERO913 Vector3f/UNIT_X))]914 (bind-camera rock cam)916 (.setTimer world (RatchetTimer. 60))917 (add-eye world cam (comp (view-image) BufferedImage!))918 (add-eye world (.getCamera world) no-op))919 )920 no-op)))922 #+end_src924 #+results: body-1925 : #'cortex.silly/test-creature928 * COMMENT purgatory929 #+begin_src clojure930 (defn bullet-trans []931 (let [obj-a (sphere 0.5 :color ColorRGBA/Red932 :position (Vector3f. -10 5 0))933 obj-b (sphere 0.5 :color ColorRGBA/Blue934 :position (Vector3f. -10 -5 0)935 :mass 0)936 control-a (.getControl obj-a RigidBodyControl)937 control-b (.getControl obj-b RigidBodyControl)938 swivel939 (.toRotationMatrix940 (doto (Quaternion.)941 (.fromAngleAxis (/ Math/PI 2)942 Vector3f/UNIT_X)))]943 (doto944 (ConeJoint.945 control-a control-b946 (Vector3f. 0 5 0)947 (Vector3f. 0 -5 0)948 swivel swivel)949 (.setLimit (* 0.6 (/ Math/PI 4))950 (/ Math/PI 4)951 (* Math/PI 0.8)))952 (world (nodify953 [obj-a obj-b])954 standard-debug-controls955 enable-debug956 no-op)))959 (defn bullet-trans* []960 (let [obj-a (box 1.5 0.5 0.5 :color ColorRGBA/Red961 :position (Vector3f. 5 0 0)962 :mass 90)963 obj-b (sphere 0.5 :color ColorRGBA/Blue964 :position (Vector3f. -5 0 0)965 :mass 0)966 control-a (.getControl obj-a RigidBodyControl)967 control-b (.getControl obj-b RigidBodyControl)968 move-up? (atom nil)969 move-down? (atom nil)970 move-left? (atom nil)971 move-right? (atom nil)972 roll-left? (atom nil)973 roll-right? (atom nil)974 force 100975 swivel976 (.toRotationMatrix977 (doto (Quaternion.)978 (.fromAngleAxis (/ Math/PI 2)979 Vector3f/UNIT_X)))980 x-move981 (doto (Matrix3f.)982 (.fromStartEndVectors Vector3f/UNIT_X983 (.normalize (Vector3f. 1 1 0))))985 timer (atom 0)]986 (doto987 (ConeJoint.988 control-a control-b989 (Vector3f. -8 0 0)990 (Vector3f. 2 0 0)991 ;;swivel swivel992 ;;Matrix3f/IDENTITY Matrix3f/IDENTITY993 x-move Matrix3f/IDENTITY994 )995 (.setCollisionBetweenLinkedBodys false)996 (.setLimit (* 1 (/ Math/PI 4)) ;; twist997 (* 1 (/ Math/PI 4)) ;; swing span in X-Y plane998 (* 0 (/ Math/PI 4)))) ;; swing span in Y-Z plane999 (world (nodify1000 [obj-a obj-b])1001 (merge standard-debug-controls1002 {"key-r" (fn [_ pressed?] (reset! move-up? pressed?))1003 "key-t" (fn [_ pressed?] (reset! move-down? pressed?))1004 "key-f" (fn [_ pressed?] (reset! move-left? pressed?))1005 "key-g" (fn [_ pressed?] (reset! move-right? pressed?))1006 "key-v" (fn [_ pressed?] (reset! roll-left? pressed?))1007 "key-b" (fn [_ pressed?] (reset! roll-right? pressed?))})1009 (fn [world]1010 (enable-debug world)1011 (set-gravity world Vector3f/ZERO)1012 )1014 (fn [world _]1016 (if @move-up?1017 (.applyForce control-a1018 (Vector3f. force 0 0)1019 (Vector3f. 0 0 0)))1020 (if @move-down?1021 (.applyForce control-a1022 (Vector3f. (- force) 0 0)1023 (Vector3f. 0 0 0)))1024 (if @move-left?1025 (.applyForce control-a1026 (Vector3f. 0 force 0)1027 (Vector3f. 0 0 0)))1028 (if @move-right?1029 (.applyForce control-a1030 (Vector3f. 0 (- force) 0)1031 (Vector3f. 0 0 0)))1033 (if @roll-left?1034 (.applyForce control-a1035 (Vector3f. 0 0 force)1036 (Vector3f. 0 0 0)))1037 (if @roll-right?1038 (.applyForce control-a1039 (Vector3f. 0 0 (- force))1040 (Vector3f. 0 0 0)))1042 (if (zero? (rem (swap! timer inc) 100))1043 (.attachChild1044 (.getRootNode world)1045 (sphere 0.05 :color ColorRGBA/Yellow1046 :physical? false :position1047 (.getWorldTranslation obj-a)))))1048 )1049 ))1051 (defn transform-trianglesdsd1052 "Transform that converts each vertex in the first triangle1053 into the corresponding vertex in the second triangle."1054 [#^Triangle tri-1 #^Triangle tri-2]1055 (let [in [(.get1 tri-1)1056 (.get2 tri-1)1057 (.get3 tri-1)]1058 out [(.get1 tri-2)1059 (.get2 tri-2)1060 (.get3 tri-2)]]1061 (let [translate (doto (Matrix4f.) (.setTranslation (.negate (in 0))))1062 in* [(.mult translate (in 0))1063 (.mult translate (in 1))1064 (.mult translate (in 2))]1065 final-translation1066 (doto (Matrix4f.)1067 (.setTranslation (out 1)))1069 rotate-11070 (doto (Matrix3f.)1071 (.fromStartEndVectors1072 (.normalize1073 (.subtract1074 (in* 1) (in* 0)))1075 (.normalize1076 (.subtract1077 (out 1) (out 0)))))1078 in** [(.mult rotate-1 (in* 0))1079 (.mult rotate-1 (in* 1))1080 (.mult rotate-1 (in* 2))]1081 scale-factor-11082 (.mult1083 (.normalize1084 (.subtract1085 (out 1)1086 (out 0)))1087 (/ (.length1088 (.subtract (out 1)1089 (out 0)))1090 (.length1091 (.subtract (in** 1)1092 (in** 0)))))1093 scale-1 (doto (Matrix4f.) (.setScale scale-factor-1))1094 in*** [(.mult scale-1 (in** 0))1095 (.mult scale-1 (in** 1))1096 (.mult scale-1 (in** 2))]1102 ]1104 (dorun (map println in))1105 (println)1106 (dorun (map println in*))1107 (println)1108 (dorun (map println in**))1109 (println)1110 (dorun (map println in***))1111 (println)1113 ))))1116 (defn world-setup [joint]1117 (let [joint-position (Vector3f. 0 0 0)1118 joint-rotation1119 (.toRotationMatrix1120 (.mult1121 (doto (Quaternion.)1122 (.fromAngleAxis1123 (* 1 (/ Math/PI 4))1124 (Vector3f. -1 0 0)))1125 (doto (Quaternion.)1126 (.fromAngleAxis1127 (* 1 (/ Math/PI 2))1128 (Vector3f. 0 0 1)))))1129 top-position (.mult joint-rotation (Vector3f. 8 0 0))1131 origin (doto1132 (sphere 0.1 :physical? false :color ColorRGBA/Cyan1133 :position top-position))1134 top (doto1135 (sphere 0.1 :physical? false :color ColorRGBA/Yellow1136 :position top-position)1138 (.addControl1139 (RigidBodyControl.1140 (CapsuleCollisionShape. 0.5 1.5 1) (float 20))))1141 bottom (doto1142 (sphere 0.1 :physical? false :color ColorRGBA/DarkGray1143 :position (Vector3f. 0 0 0))1144 (.addControl1145 (RigidBodyControl.1146 (CapsuleCollisionShape. 0.5 1.5 1) (float 0))))1147 table (box 10 2 10 :position (Vector3f. 0 -20 0)1148 :color ColorRGBA/Gray :mass 0)1149 a (.getControl top RigidBodyControl)1150 b (.getControl bottom RigidBodyControl)]1152 (cond1153 (= joint :cone)1155 (doto (ConeJoint.1156 a b1157 (world-to-local top joint-position)1158 (world-to-local bottom joint-position)1159 joint-rotation1160 joint-rotation1161 )1164 (.setLimit (* (/ 10) Math/PI)1165 (* (/ 4) Math/PI)1166 0)))1167 [origin top bottom table]))1169 (defn test-joint [joint]1170 (let [[origin top bottom floor] (world-setup joint)1171 control (.getControl top RigidBodyControl)1172 move-up? (atom false)1173 move-down? (atom false)1174 move-left? (atom false)1175 move-right? (atom false)1176 roll-left? (atom false)1177 roll-right? (atom false)1178 timer (atom 0)]1180 (world1181 (nodify [top bottom floor origin])1182 (merge standard-debug-controls1183 {"key-r" (fn [_ pressed?] (reset! move-up? pressed?))1184 "key-t" (fn [_ pressed?] (reset! move-down? pressed?))1185 "key-f" (fn [_ pressed?] (reset! move-left? pressed?))1186 "key-g" (fn [_ pressed?] (reset! move-right? pressed?))1187 "key-v" (fn [_ pressed?] (reset! roll-left? pressed?))1188 "key-b" (fn [_ pressed?] (reset! roll-right? pressed?))})1190 (fn [world]1191 (light-up-everything world)1192 (enable-debug world)1193 (set-gravity world (Vector3f. 0 0 0))1194 )1196 (fn [world _]1197 (if (zero? (rem (swap! timer inc) 100))1198 (do1199 ;; (println-repl @timer)1200 (.attachChild (.getRootNode world)1201 (sphere 0.05 :color ColorRGBA/Yellow1202 :position (.getWorldTranslation top)1203 :physical? false))1204 (.attachChild (.getRootNode world)1205 (sphere 0.05 :color ColorRGBA/LightGray1206 :position (.getWorldTranslation bottom)1207 :physical? false))))1209 (if @move-up?1210 (.applyTorque control1211 (.mult (.getPhysicsRotation control)1212 (Vector3f. 0 0 10))))1213 (if @move-down?1214 (.applyTorque control1215 (.mult (.getPhysicsRotation control)1216 (Vector3f. 0 0 -10))))1217 (if @move-left?1218 (.applyTorque control1219 (.mult (.getPhysicsRotation control)1220 (Vector3f. 0 10 0))))1221 (if @move-right?1222 (.applyTorque control1223 (.mult (.getPhysicsRotation control)1224 (Vector3f. 0 -10 0))))1225 (if @roll-left?1226 (.applyTorque control1227 (.mult (.getPhysicsRotation control)1228 (Vector3f. -1 0 0))))1229 (if @roll-right?1230 (.applyTorque control1231 (.mult (.getPhysicsRotation control)1232 (Vector3f. 1 0 0))))))))1236 (defprotocol Frame1237 (frame [this]))1239 (extend-type BufferedImage1240 Frame1241 (frame [image]1242 (merge1243 (apply1244 hash-map1245 (interleave1246 (doall (for [x (range (.getWidth image)) y (range (.getHeight image))]1247 (vector x y)))1248 (doall (for [x (range (.getWidth image)) y (range (.getHeight image))]1249 (let [data (.getRGB image x y)]1250 (hash-map :r (bit-shift-right (bit-and 0xff0000 data) 16)1251 :g (bit-shift-right (bit-and 0x00ff00 data) 8)1252 :b (bit-and 0x0000ff data)))))))1253 {:width (.getWidth image) :height (.getHeight image)})))1256 (extend-type ImagePlus1257 Frame1258 (frame [image+]1259 (frame (.getBufferedImage image+))))1262 #+end_src1265 * COMMENT generate source1266 #+begin_src clojure :tangle ../src/cortex/silly.clj1267 <<body-1>>1268 #+end_src