view org/test-creature.org @ 112:128fa71ee188

working on retina design
author Robert McIntyre <rlm@mit.edu>
date Thu, 19 Jan 2012 11:29:46 -0700
parents 61d9c0e8d188
children 9d0fe7f54e14
line wrap: on
line source
1 #+title: First attempt at a creature!
2 #+author: Robert McIntyre
3 #+email: rlm@mit.edu
4 #+description:
5 #+keywords: simulation, jMonkeyEngine3, clojure
6 #+SETUPFILE: ../../aurellem/org/setup.org
7 #+INCLUDE: ../../aurellem/org/level-0.org
9 * objectives
10 - [X] get an overall bitmap-like image for touch
11 - [X] write code to visuliaze this bitmap
12 - [ ] directly change the UV-pixels to show touch sensor activation
13 - [ ] write an explination for why b&w bitmaps for senses is appropiate
14 - [ ] clean up touch code and write visulazation test
15 - [ ] do the same for eyes
17 * Intro
18 So far, I've made the following senses --
19 - Vision
20 - Hearing
21 - Touch
22 - Proprioception
24 And one effector:
25 - Movement
27 However, the code so far has only enabled these senses, but has not
28 actually implemented them. For example, there is still a lot of work
29 to be done for vision. I need to be able to create an /eyeball/ in
30 simulation that can be moved around and see the world from different
31 angles. I also need to determine weather to use log-polar or cartesian
32 for the visual input, and I need to determine how/wether to
33 disceritise the visual input.
35 I also want to be able to visualize both the sensors and the
36 effectors in pretty pictures. This semi-retarted creature will be my
37 first attempt at bringing everything together.
39 * The creature's body
41 Still going to do an eve-like body in blender, but due to problems
42 importing the joints, etc into jMonkeyEngine3, I'm going to do all
43 the connecting here in clojure code, using the names of the individual
44 components and trial and error. Later, I'll maybe make some sort of
45 creature-building modifications to blender that support whatever
46 discreitized senses I'm going to make.
48 #+name: body-1
49 #+begin_src clojure
50 (ns cortex.silly
51 "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 view-image
71 "Initailizes a JPanel on which you may draw a BufferedImage.
72 Returns a function that accepts a BufferedImage and draws it to the
73 JPanel."
74 []
75 (let [image
76 (atom
77 (BufferedImage. 1 1 BufferedImage/TYPE_4BYTE_ABGR))
78 panel
79 (proxy [JPanel] []
80 (paint
81 [graphics]
82 (proxy-super paintComponent graphics)
83 (.drawImage graphics @image 0 0 nil)))
84 frame (JFrame. "Display Image")]
85 (SwingUtilities/invokeLater
86 (fn []
87 (doto frame
88 (-> (.getContentPane) (.add panel))
89 (.pack)
90 (.setLocationRelativeTo nil)
91 (.setResizable true)
92 (.setVisible true))))
93 (fn [#^BufferedImage i]
94 (reset! image i)
95 (.setSize frame (+ 8 (.getWidth i)) (+ 28 (.getHeight i)))
96 (.repaint panel 0 0 (.getWidth i) (.getHeight i)))))
98 (defn points->image
99 "Take a sparse collection of points and visuliaze it as a
100 BufferedImage."
102 ;; TODO maybe parallelize this since it's easy
104 [points]
105 (if (empty? points)
106 (BufferedImage. 1 1 BufferedImage/TYPE_BYTE_BINARY)
107 (let [xs (vec (map first points))
108 ys (vec (map second points))
109 x0 (apply min xs)
110 y0 (apply min ys)
111 width (- (apply max xs) x0)
112 height (- (apply max ys) y0)
113 image (BufferedImage. (inc width) (inc height)
114 BufferedImage/TYPE_BYTE_BINARY)]
115 (dorun
116 (for [index (range (count points))]
117 (.setRGB image (- (xs index) x0) (- (ys index) y0) -1)))
119 image)))
121 (defn test-data
122 []
123 (vec
124 (for [a (range 0 1000 2)
125 b (range 0 1000 2)]
126 (vector a b))
127 ))
129 (defn average [coll]
130 (/ (reduce + coll) (count coll)))
132 (defn collapse-1d
133 "One dimensional analogue of collapse"
134 [center line]
135 (let [length (count line)
136 num-above (count (filter (partial < center) line))
137 num-below (- length num-above)]
138 (range (- center num-below)
139 (+ center num-above))
140 ))
142 (defn collapse
143 "Take a set of pairs of integers and collapse them into a
144 contigous bitmap."
145 [points]
146 (if (empty? points) []
147 (let
148 [num-points (count points)
149 center (vector
150 (int (average (map first points)))
151 (int (average (map first points))))
152 flattened
153 (reduce
154 concat
155 (map
156 (fn [column]
157 (map vector
158 (map first column)
159 (collapse-1d (second center)
160 (map second column))))
161 (partition-by first (sort-by first points))))
162 squeezed
163 (reduce
164 concat
165 (map
166 (fn [row]
167 (map vector
168 (collapse-1d (first center)
169 (map first row))
170 (map second row)))
171 (partition-by second (sort-by second flattened))))
172 relocate
173 (let [min-x (apply min (map first squeezed))
174 min-y (apply min (map second squeezed))]
175 (map (fn [[x y]]
176 [(- x min-x)
177 (- y min-y)])
178 squeezed))]
179 relocate
180 )))
182 (defn load-bullet []
183 (let [sim (world (Node.) {} no-op no-op)]
184 (doto sim
185 (.enqueue
186 (fn []
187 (.stop sim)))
188 (.start))))
190 (defn load-blender-model
191 "Load a .blend file using an asset folder relative path."
192 [^String model]
193 (.loadModel
194 (doto (asset-manager)
195 (.registerLoader BlenderModelLoader (into-array String ["blend"])))
196 model))
198 (defn meta-data [blender-node key]
199 (if-let [data (.getUserData blender-node "properties")]
200 (.findValue data key)
201 nil))
203 (defn blender-to-jme
204 "Convert from Blender coordinates to JME coordinates"
205 [#^Vector3f in]
206 (Vector3f. (.getX in)
207 (.getZ in)
208 (- (.getY in))))
210 (defn jme-to-blender
211 "Convert from JME coordinates to Blender coordinates"
212 [#^Vector3f in]
213 (Vector3f. (.getX in)
214 (- (.getZ in))
215 (.getY in)))
217 (defn joint-targets
218 "Return the two closest two objects to the joint object, ordered
219 from bottom to top according to the joint's rotation."
220 [#^Node parts #^Node joint]
221 ;;(println (meta-data joint "joint"))
222 (.getWorldRotation joint)
223 (loop [radius (float 0.01)]
224 (let [results (CollisionResults.)]
225 (.collideWith
226 parts
227 (BoundingBox. (.getWorldTranslation joint)
228 radius radius radius)
229 results)
230 (let [targets
231 (distinct
232 (map #(.getGeometry %) results))]
233 (if (>= (count targets) 2)
234 (sort-by
235 #(let [v
236 (jme-to-blender
237 (.mult
238 (.inverse (.getWorldRotation joint))
239 (.subtract (.getWorldTranslation %)
240 (.getWorldTranslation joint))))]
241 (println-repl (.getName %) ":" v)
242 (.dot (Vector3f. 1 1 1)
243 v))
244 (take 2 targets))
245 (recur (float (* radius 2))))))))
247 (defn world-to-local
248 "Convert the world coordinates into coordinates relative to the
249 object (i.e. local coordinates), taking into account the rotation
250 of object."
251 [#^Spatial object world-coordinate]
252 (let [out (Vector3f.)]
253 (.worldToLocal object world-coordinate out) out))
255 (defn local-to-world
256 "Convert the local coordinates into coordinates into world relative
257 coordinates"
258 [#^Spatial object local-coordinate]
259 (let [world-coordinate (Vector3f.)]
260 (.localToWorld object local-coordinate world-coordinate)
261 world-coordinate))
264 (defmulti joint-dispatch
265 "Translate blender pseudo-joints into real JME joints."
266 (fn [constraints & _]
267 (:type constraints)))
269 (defmethod joint-dispatch :point
270 [constraints control-a control-b pivot-a pivot-b rotation]
271 (println-repl "creating POINT2POINT joint")
272 (Point2PointJoint.
273 control-a
274 control-b
275 pivot-a
276 pivot-b))
278 (defmethod joint-dispatch :hinge
279 [constraints control-a control-b pivot-a pivot-b rotation]
280 (println-repl "creating HINGE joint")
281 (let [axis
282 (if-let
283 [axis (:axis constraints)]
284 axis
285 Vector3f/UNIT_X)
286 [limit-1 limit-2] (:limit constraints)
287 hinge-axis
288 (.mult
289 rotation
290 (blender-to-jme axis))]
291 (doto
292 (HingeJoint.
293 control-a
294 control-b
295 pivot-a
296 pivot-b
297 hinge-axis
298 hinge-axis)
299 (.setLimit limit-1 limit-2))))
301 (defmethod joint-dispatch :cone
302 [constraints control-a control-b pivot-a pivot-b rotation]
303 (let [limit-xz (:limit-xz constraints)
304 limit-xy (:limit-xy constraints)
305 twist (:twist constraints)]
307 (println-repl "creating CONE joint")
308 (println-repl rotation)
309 (println-repl
310 "UNIT_X --> " (.mult rotation (Vector3f. 1 0 0)))
311 (println-repl
312 "UNIT_Y --> " (.mult rotation (Vector3f. 0 1 0)))
313 (println-repl
314 "UNIT_Z --> " (.mult rotation (Vector3f. 0 0 1)))
315 (doto
316 (ConeJoint.
317 control-a
318 control-b
319 pivot-a
320 pivot-b
321 rotation
322 rotation)
323 (.setLimit (float limit-xz)
324 (float limit-xy)
325 (float twist)))))
327 (defn connect
328 "here are some examples:
329 {:type :point}
330 {:type :hinge :limit [0 (/ Math/PI 2)] :axis (Vector3f. 0 1 0)}
331 (:axis defaults to (Vector3f. 1 0 0) if not provided for hinge joints)
333 {:type :cone :limit-xz 0]
334 :limit-xy 0]
335 :twist 0]} (use XZY rotation mode in blender!)"
336 [#^Node obj-a #^Node obj-b #^Node joint]
337 (let [control-a (.getControl obj-a RigidBodyControl)
338 control-b (.getControl obj-b RigidBodyControl)
339 joint-center (.getWorldTranslation joint)
340 joint-rotation (.toRotationMatrix (.getWorldRotation joint))
341 pivot-a (world-to-local obj-a joint-center)
342 pivot-b (world-to-local obj-b joint-center)]
344 (if-let [constraints
345 (map-vals
346 eval
347 (read-string
348 (meta-data joint "joint")))]
349 ;; A side-effect of creating a joint registers
350 ;; it with both physics objects which in turn
351 ;; will register the joint with the physics system
352 ;; when the simulation is started.
353 (do
354 (println-repl "creating joint between"
355 (.getName obj-a) "and" (.getName obj-b))
356 (joint-dispatch constraints
357 control-a control-b
358 pivot-a pivot-b
359 joint-rotation))
360 (println-repl "could not find joint meta-data!"))))
362 (defn assemble-creature [#^Node pieces joints]
363 (dorun
364 (map
365 (fn [geom]
366 (let [physics-control
367 (RigidBodyControl.
368 (HullCollisionShape.
369 (.getMesh geom))
370 (if-let [mass (meta-data geom "mass")]
371 (do
372 (println-repl
373 "setting" (.getName geom) "mass to" (float mass))
374 (float mass))
375 (float 1)))]
377 (.addControl geom physics-control)))
378 (filter #(isa? (class %) Geometry )
379 (node-seq pieces))))
380 (dorun
381 (map
382 (fn [joint]
383 (let [[obj-a obj-b]
384 (joint-targets pieces joint)]
385 (connect obj-a obj-b joint)))
386 joints))
387 pieces)
389 (defn blender-creature [blender-path]
390 (let [model (load-blender-model blender-path)
391 joints
392 (if-let [joint-node (.getChild model "joints")]
393 (seq (.getChildren joint-node))
394 (do (println-repl "could not find joints node")
395 []))]
396 (assemble-creature model joints)))
398 (def hand "Models/creature1/one.blend")
400 (def worm "Models/creature1/try-again.blend")
402 (def touch "Models/creature1/touch.blend")
404 (defn worm-model [] (load-blender-model worm))
406 (defn x-ray [#^ColorRGBA color]
407 (doto (Material. (asset-manager)
408 "Common/MatDefs/Misc/Unshaded.j3md")
409 (.setColor "Color" color)
410 (-> (.getAdditionalRenderState)
411 (.setDepthTest false))))
413 (defn colorful []
414 (.getChild (worm-model) "worm-21"))
416 (import jme3tools.converters.ImageToAwt)
418 (import ij.ImagePlus)
420 ;; Every Mesh has many triangles, each with its own index.
421 ;; Every vertex has its own index as well.
423 (defn tactile-sensor-image
424 "Return the touch-sensor distribution image in BufferedImage format,
425 or nil if it does not exist."
426 [#^Geometry obj]
427 (if-let [image-path (meta-data obj "touch")]
428 (ImageToAwt/convert
429 (.getImage
430 (.loadTexture
431 (asset-manager)
432 image-path))
433 false false 0)))
435 (import ij.process.ImageProcessor)
436 (import java.awt.image.BufferedImage)
438 (def white -1)
440 (defn filter-pixels
441 "List the coordinates of all pixels matching pred, within the bounds
442 provided. Bounds -> [x0 y0 width height]"
443 {:author "Dylan Holmes"}
444 ([pred #^BufferedImage image]
445 (filter-pixels pred image [0 0 (.getWidth image) (.getHeight image)]))
446 ([pred #^BufferedImage image [x0 y0 width height]]
447 ((fn accumulate [x y matches]
448 (cond
449 (>= y (+ height y0)) matches
450 (>= x (+ width x0)) (recur 0 (inc y) matches)
451 (pred (.getRGB image x y))
452 (recur (inc x) y (conj matches [x y]))
453 :else (recur (inc x) y matches)))
454 x0 y0 [])))
456 (defn white-coordinates
457 "Coordinates of all the white pixels in a subset of the image."
458 ([#^BufferedImage image bounds]
459 (filter-pixels #(= % white) image bounds))
460 ([#^BufferedImage image]
461 (filter-pixels #(= % white) image)))
463 (defn triangle
464 "Get the triangle specified by triangle-index from the mesh within
465 bounds."
466 [#^Mesh mesh triangle-index]
467 (let [scratch (Triangle.)]
468 (.getTriangle mesh triangle-index scratch)
469 scratch))
471 (defn triangle-vertex-indices
472 "Get the triangle vertex indices of a given triangle from a given
473 mesh."
474 [#^Mesh mesh triangle-index]
475 (let [indices (int-array 3)]
476 (.getTriangle mesh triangle-index indices)
477 (vec indices)))
479 (defn vertex-UV-coord
480 "Get the uv-coordinates of the vertex named by vertex-index"
481 [#^Mesh mesh vertex-index]
482 (let [UV-buffer
483 (.getData
484 (.getBuffer
485 mesh
486 VertexBuffer$Type/TexCoord))]
487 [(.get UV-buffer (* vertex-index 2))
488 (.get UV-buffer (+ 1 (* vertex-index 2)))]))
490 (defn triangle-UV-coord
491 "Get the uv-cooridnates of the triangle's verticies."
492 [#^Mesh mesh width height triangle-index]
493 (map (fn [[u v]] (vector (* width u) (* height v)))
494 (map (partial vertex-UV-coord mesh)
495 (triangle-vertex-indices mesh triangle-index))))
497 (defn same-side?
498 "Given the points p1 and p2 and the reference point ref, is point p
499 on the same side of the line that goes through p1 and p2 as ref is?"
500 [p1 p2 ref p]
501 (<=
502 0
503 (.dot
504 (.cross (.subtract p2 p1) (.subtract p p1))
505 (.cross (.subtract p2 p1) (.subtract ref p1)))))
507 (defn triangle-seq [#^Triangle tri]
508 [(.get1 tri) (.get2 tri) (.get3 tri)])
510 (defn vector3f-seq [#^Vector3f v]
511 [(.getX v) (.getY v) (.getZ v)])
513 (defn inside-triangle?
514 "Is the point inside the triangle?"
515 {:author "Dylan Holmes"}
516 [#^Triangle tri #^Vector3f p]
517 (let [[vert-1 vert-2 vert-3] (triangle-seq tri)]
518 (and
519 (same-side? vert-1 vert-2 vert-3 p)
520 (same-side? vert-2 vert-3 vert-1 p)
521 (same-side? vert-3 vert-1 vert-2 p))))
523 (defn triangle->matrix4f
524 "Converts the triangle into a 4x4 matrix: The first three columns
525 contain the vertices of the triangle; the last contains the unit
526 normal of the triangle. The bottom row is filled with 1s."
527 [#^Triangle t]
528 (let [mat (Matrix4f.)
529 [vert-1 vert-2 vert-3]
530 ((comp vec map) #(.get t %) (range 3))
531 unit-normal (do (.calculateNormal t)(.getNormal t))
532 vertices [vert-1 vert-2 vert-3 unit-normal]]
533 (dorun
534 (for [row (range 4) col (range 3)]
535 (do
536 (.set mat col row (.get (vertices row)col))
537 (.set mat 3 row 1))))
538 mat))
540 (defn triangle-transformation
541 "Returns the affine transformation that converts each vertex in the
542 first triangle into the corresponding vertex in the second
543 triangle."
544 [#^Triangle tri-1 #^Triangle tri-2]
545 (.mult
546 (triangle->matrix4f tri-2)
547 (.invert (triangle->matrix4f tri-1))))
549 (defn point->vector2f [[u v]]
550 (Vector2f. u v))
552 (defn vector2f->vector3f [v]
553 (Vector3f. (.getX v) (.getY v) 0))
555 (defn map-triangle [f #^Triangle tri]
556 (Triangle.
557 (f 0 (.get1 tri))
558 (f 1 (.get2 tri))
559 (f 2 (.get3 tri))))
561 (defn points->triangle
562 "Convert a list of points into a triangle."
563 [points]
564 (apply #(Triangle. %1 %2 %3)
565 (map (fn [point]
566 (let [point (vec point)]
567 (Vector3f. (get point 0 0)
568 (get point 1 0)
569 (get point 2 0))))
570 (take 3 points))))
572 (defn convex-bounds
573 "Dimensions of the smallest integer bounding square of the list of
574 2D verticies in the form: [x y width height]."
575 [uv-verts]
576 (let [xs (map first uv-verts)
577 ys (map second uv-verts)
578 x0 (Math/floor (apply min xs))
579 y0 (Math/floor (apply min ys))
580 x1 (Math/ceil (apply max xs))
581 y1 (Math/ceil (apply max ys))]
582 [x0 y0 (- x1 x0) (- y1 y0)]))
584 (defn sensors-in-triangle
585 "Find the locations of the touch sensors within a triangle in both
586 UV and gemoetry relative coordinates."
587 [image mesh tri-index]
588 (let [width (.getWidth image)
589 height (.getHeight image)
590 UV-vertex-coords (triangle-UV-coord mesh width height tri-index)
591 bounds (convex-bounds UV-vertex-coords)
593 cutout-triangle (points->triangle UV-vertex-coords)
594 UV-sensor-coords
595 (filter (comp (partial inside-triangle? cutout-triangle)
596 (fn [[u v]] (Vector3f. u v 0)))
597 (white-coordinates image bounds))
598 UV->geometry (triangle-transformation
599 cutout-triangle
600 (triangle mesh tri-index))
601 geometry-sensor-coords
602 (map (fn [[u v]] (.mult UV->geometry (Vector3f. u v 0)))
603 UV-sensor-coords)]
604 {:UV UV-sensor-coords :geometry geometry-sensor-coords}))
606 (defn-memo locate-feelers
607 "Search the geometry's tactile UV image for touch sensors, returning
608 their positions in geometry-relative coordinates."
609 [#^Geometry geo]
610 (let [mesh (.getMesh geo)
611 num-triangles (.getTriangleCount mesh)]
612 (if-let [image (tactile-sensor-image geo)]
613 (map
614 (partial sensors-in-triangle image mesh)
615 (range num-triangles))
616 (repeat (.getTriangleCount mesh) {:UV nil :geometry nil}))))
618 (use 'clojure.contrib.def)
620 (defn-memo touch-topology [#^Gemoetry geo]
621 (vec (collapse (reduce concat (map :UV (locate-feelers geo))))))
623 (defn-memo feeler-coordinates [#^Geometry geo]
624 (vec (map :geometry (locate-feelers geo))))
626 (defn enable-touch [#^Geometry geo]
627 (let [feeler-coords (feeler-coordinates geo)
628 tris (triangles geo)
629 limit 0.1
630 ;;results (CollisionResults.)
631 ]
632 (if (empty? (touch-topology geo))
633 nil
634 (fn [node]
635 (let [sensor-origins
636 (map
637 #(map (partial local-to-world geo) %)
638 feeler-coords)
639 triangle-normals
640 (map (partial get-ray-direction geo)
641 tris)
642 rays
643 (flatten
644 (map (fn [origins norm]
645 (map #(doto (Ray. % norm)
646 (.setLimit limit)) origins))
647 sensor-origins triangle-normals))]
648 (vector
649 (touch-topology geo)
650 (vec
651 (for [ray rays]
652 (do
653 (let [results (CollisionResults.)]
654 (.collideWith node ray results)
655 (let [touch-objects
656 (set
657 (filter #(not (= geo %))
658 (map #(.getGeometry %) results)))]
659 (if (> (count touch-objects) 0)
660 1 0))))))))))))
662 (defn touch [#^Node pieces]
663 (filter (comp not nil?)
664 (map enable-touch
665 (filter #(isa? (class %) Geometry)
666 (node-seq pieces)))))
669 ;; human eye transmits 62kb/s to brain Bandwidth is 8.75 Mb/s
670 ;; http://en.wikipedia.org/wiki/Retina
672 (defn test-eye []
673 (.getChild (worm-model) "worm-11"))
676 (defn retina-sensor-image
677 "Return a map of pixel selection functions to BufferedImages
678 describing the distribution of light-sensitive components on this
679 geometry's surface. Each function creates an integer from the rgb
680 values found in the pixel. :red, :green, :blue, :gray are already
681 defined as extracting the red green blue and average components
682 respectively."
683 [#^Geometry eye]
684 (if-let [eye-map (meta-data eye "eye")]
685 (map-vals
686 #(ImageToAwt/convert
687 (.getImage (.loadTexture (asset-manager) %))
688 false false 0)
689 (read-string
690 eye-map))))
693 (defn enable-vision
695 ;; need to create a camera based on uv image,
696 ;; update this camera every frame based on the position of this
697 ;; geometry. (maybe can get cam to follow the object)
699 ;; use a stack for the continuation to grab the image.
702 [#^Geometry eye]
705 ;; Here's how vision will work.
707 ;; Make the continuation in scene-processor take FrameBuffer,
708 ;; byte-buffer, BufferedImage already sized to the correct
709 ;; dimensions. the continuation will decide wether to "mix" them
710 ;; into the BufferedImage, lazily ignore them, or mix them halfway
711 ;; and call c/graphics card routines.
713 ;; (vision creature) will take an optional :skip argument which will
714 ;; inform the continuations in scene processor to skip the given
715 ;; number of cycles; 0 means that no cycles will be skipped.
717 ;; (vision creature) will return [init-functions sensor-functions].
718 ;; The init-functions are each single-arg functions that take the
719 ;; world and register the cameras and must each be called before the
720 ;; corresponding sensor-functions. Each init-function returns the
721 ;; viewport for that eye which can be manipulated, saved, etc. Each
722 ;; sensor-function is a thunk and will return data in the same
723 ;; format as the tactile-sensor functions; the structure is
724 ;; [topology, sensor-data]. Internally, these sensor-functions
725 ;; maintain a reference to sensor-data which is periodically updated
726 ;; by the continuation function established by its init-function.
727 ;; They can be queried every cycle, but their information may not
728 ;; necessairly be different every cycle.
730 ;; Each eye in the creature in blender will work the same way as
731 ;; joints -- a one dimensional object with no geometry whose local
732 ;; coordinate system determines the orientation of the resulting
733 ;; eye. All eyes will have a parent named "eyes" just as all joints
734 ;; have a parent named "joints". The resulting camera will be a
735 ;; ChaseCamera or a CameraNode bound to the geo that is closest to
736 ;; the eye marker. The eye marker will contain the metadata for the
737 ;; eye, and will be moved by it's bound geometry. The dimensions of
738 ;; the eye's camera are equal to the dimensions of the eye's "UV"
739 ;; map.
742 )
744 (defn debug-window
745 "creates function that offers a debug view of sensor data"
746 []
747 (let [vi (view-image)]
748 (fn
749 [[coords sensor-data]]
750 (let [image (points->image coords)]
751 (dorun
752 (for [i (range (count coords))]
753 (.setRGB image ((coords i) 0) ((coords i) 1)
754 ({0 -16777216
755 1 -1} (sensor-data i)))))
756 (vi image)))))
759 ;;(defn test-touch [world creature]
762 (defn test-creature [thing]
763 (let [x-axis
764 (box 1 0.01 0.01 :physical? false :color ColorRGBA/Red)
765 y-axis
766 (box 0.01 1 0.01 :physical? false :color ColorRGBA/Green)
767 z-axis
768 (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 (world
774 (nodify [creature
775 (box 10 2 10 :position (Vector3f. 0 -9 0)
776 :color ColorRGBA/Gray :mass 0)
777 x-axis y-axis z-axis
778 ])
779 standard-debug-controls
780 (fn [world]
781 (light-up-everything world)
782 (enable-debug world)
783 ;;(com.aurellem.capture.Capture/captureVideo
784 ;; 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 ;;(dorun
791 ;; (map #(%1 %2) touch-nerves (repeat (.getRootNode world))))
793 (dorun
794 (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 collisions
818 (defn collision-test []
819 (let [b-radius 1
820 b-position (Vector3f. 0 0 0)
821 obj-b (box 1 1 1 :color ColorRGBA/Blue
822 :position b-position
823 :mass 0)
824 node (nodify [obj-b])
825 bounds-b
826 (doto (Picture.)
827 (.setHeight 50)
828 (.setWidth 50)
829 (.setImage (asset-manager)
830 "Models/creature1/hand.png"
831 false
832 ))
834 ;;(Ray. (Vector3f. 0 -5 0) (.normalize (Vector3f. 0 1 0)))
836 collisions
837 (let [cr (CollisionResults.)]
838 (.collideWith node bounds-b cr)
839 (println (map #(.getContactPoint %) cr))
840 cr)
842 ;;collision-points
843 ;;(map #(sphere 0.1 :position (.getContactPoint %))
844 ;; collisions)
846 ;;node (nodify (conj collision-points obj-b))
848 sim
849 (world node
850 {"key-space"
851 (fn [_ value]
852 (if value
853 (let [cr (CollisionResults.)]
854 (.collideWith node bounds-b cr)
855 (println-repl (map #(.getContactPoint %) cr))
856 cr)))}
857 no-op
858 no-op)
860 ]
861 sim
863 ))
868 #+end_src
870 #+results: body-1
871 : #'cortex.silly/test-creature
874 * COMMENT purgatory
875 #+begin_src clojure
876 (defn bullet-trans []
877 (let [obj-a (sphere 0.5 :color ColorRGBA/Red
878 :position (Vector3f. -10 5 0))
879 obj-b (sphere 0.5 :color ColorRGBA/Blue
880 :position (Vector3f. -10 -5 0)
881 :mass 0)
882 control-a (.getControl obj-a RigidBodyControl)
883 control-b (.getControl obj-b RigidBodyControl)
884 swivel
885 (.toRotationMatrix
886 (doto (Quaternion.)
887 (.fromAngleAxis (/ Math/PI 2)
888 Vector3f/UNIT_X)))]
889 (doto
890 (ConeJoint.
891 control-a control-b
892 (Vector3f. 0 5 0)
893 (Vector3f. 0 -5 0)
894 swivel swivel)
895 (.setLimit (* 0.6 (/ Math/PI 4))
896 (/ Math/PI 4)
897 (* Math/PI 0.8)))
898 (world (nodify
899 [obj-a obj-b])
900 standard-debug-controls
901 enable-debug
902 no-op)))
905 (defn bullet-trans* []
906 (let [obj-a (box 1.5 0.5 0.5 :color ColorRGBA/Red
907 :position (Vector3f. 5 0 0)
908 :mass 90)
909 obj-b (sphere 0.5 :color ColorRGBA/Blue
910 :position (Vector3f. -5 0 0)
911 :mass 0)
912 control-a (.getControl obj-a RigidBodyControl)
913 control-b (.getControl obj-b RigidBodyControl)
914 move-up? (atom nil)
915 move-down? (atom nil)
916 move-left? (atom nil)
917 move-right? (atom nil)
918 roll-left? (atom nil)
919 roll-right? (atom nil)
920 force 100
921 swivel
922 (.toRotationMatrix
923 (doto (Quaternion.)
924 (.fromAngleAxis (/ Math/PI 2)
925 Vector3f/UNIT_X)))
926 x-move
927 (doto (Matrix3f.)
928 (.fromStartEndVectors Vector3f/UNIT_X
929 (.normalize (Vector3f. 1 1 0))))
931 timer (atom 0)]
932 (doto
933 (ConeJoint.
934 control-a control-b
935 (Vector3f. -8 0 0)
936 (Vector3f. 2 0 0)
937 ;;swivel swivel
938 ;;Matrix3f/IDENTITY Matrix3f/IDENTITY
939 x-move Matrix3f/IDENTITY
940 )
941 (.setCollisionBetweenLinkedBodys false)
942 (.setLimit (* 1 (/ Math/PI 4)) ;; twist
943 (* 1 (/ Math/PI 4)) ;; swing span in X-Y plane
944 (* 0 (/ Math/PI 4)))) ;; swing span in Y-Z plane
945 (world (nodify
946 [obj-a obj-b])
947 (merge standard-debug-controls
948 {"key-r" (fn [_ pressed?] (reset! move-up? pressed?))
949 "key-t" (fn [_ pressed?] (reset! move-down? pressed?))
950 "key-f" (fn [_ pressed?] (reset! move-left? pressed?))
951 "key-g" (fn [_ pressed?] (reset! move-right? pressed?))
952 "key-v" (fn [_ pressed?] (reset! roll-left? pressed?))
953 "key-b" (fn [_ pressed?] (reset! roll-right? pressed?))})
955 (fn [world]
956 (enable-debug world)
957 (set-gravity world Vector3f/ZERO)
958 )
960 (fn [world _]
962 (if @move-up?
963 (.applyForce control-a
964 (Vector3f. force 0 0)
965 (Vector3f. 0 0 0)))
966 (if @move-down?
967 (.applyForce control-a
968 (Vector3f. (- force) 0 0)
969 (Vector3f. 0 0 0)))
970 (if @move-left?
971 (.applyForce control-a
972 (Vector3f. 0 force 0)
973 (Vector3f. 0 0 0)))
974 (if @move-right?
975 (.applyForce control-a
976 (Vector3f. 0 (- force) 0)
977 (Vector3f. 0 0 0)))
979 (if @roll-left?
980 (.applyForce control-a
981 (Vector3f. 0 0 force)
982 (Vector3f. 0 0 0)))
983 (if @roll-right?
984 (.applyForce control-a
985 (Vector3f. 0 0 (- force))
986 (Vector3f. 0 0 0)))
988 (if (zero? (rem (swap! timer inc) 100))
989 (.attachChild
990 (.getRootNode world)
991 (sphere 0.05 :color ColorRGBA/Yellow
992 :physical? false :position
993 (.getWorldTranslation obj-a)))))
994 )
995 ))
997 (defn transform-trianglesdsd
998 "Transform that converts each vertex in the first triangle
999 into the corresponding vertex in the second triangle."
1000 [#^Triangle tri-1 #^Triangle tri-2]
1001 (let [in [(.get1 tri-1)
1002 (.get2 tri-1)
1003 (.get3 tri-1)]
1004 out [(.get1 tri-2)
1005 (.get2 tri-2)
1006 (.get3 tri-2)]]
1007 (let [translate (doto (Matrix4f.) (.setTranslation (.negate (in 0))))
1008 in* [(.mult translate (in 0))
1009 (.mult translate (in 1))
1010 (.mult translate (in 2))]
1011 final-translation
1012 (doto (Matrix4f.)
1013 (.setTranslation (out 1)))
1015 rotate-1
1016 (doto (Matrix3f.)
1017 (.fromStartEndVectors
1018 (.normalize
1019 (.subtract
1020 (in* 1) (in* 0)))
1021 (.normalize
1022 (.subtract
1023 (out 1) (out 0)))))
1024 in** [(.mult rotate-1 (in* 0))
1025 (.mult rotate-1 (in* 1))
1026 (.mult rotate-1 (in* 2))]
1027 scale-factor-1
1028 (.mult
1029 (.normalize
1030 (.subtract
1031 (out 1)
1032 (out 0)))
1033 (/ (.length
1034 (.subtract (out 1)
1035 (out 0)))
1036 (.length
1037 (.subtract (in** 1)
1038 (in** 0)))))
1039 scale-1 (doto (Matrix4f.) (.setScale scale-factor-1))
1040 in*** [(.mult scale-1 (in** 0))
1041 (.mult scale-1 (in** 1))
1042 (.mult scale-1 (in** 2))]
1050 (dorun (map println in))
1051 (println)
1052 (dorun (map println in*))
1053 (println)
1054 (dorun (map println in**))
1055 (println)
1056 (dorun (map println in***))
1057 (println)
1059 ))))
1062 (defn world-setup [joint]
1063 (let [joint-position (Vector3f. 0 0 0)
1064 joint-rotation
1065 (.toRotationMatrix
1066 (.mult
1067 (doto (Quaternion.)
1068 (.fromAngleAxis
1069 (* 1 (/ Math/PI 4))
1070 (Vector3f. -1 0 0)))
1071 (doto (Quaternion.)
1072 (.fromAngleAxis
1073 (* 1 (/ Math/PI 2))
1074 (Vector3f. 0 0 1)))))
1075 top-position (.mult joint-rotation (Vector3f. 8 0 0))
1077 origin (doto
1078 (sphere 0.1 :physical? false :color ColorRGBA/Cyan
1079 :position top-position))
1080 top (doto
1081 (sphere 0.1 :physical? false :color ColorRGBA/Yellow
1082 :position top-position)
1084 (.addControl
1085 (RigidBodyControl.
1086 (CapsuleCollisionShape. 0.5 1.5 1) (float 20))))
1087 bottom (doto
1088 (sphere 0.1 :physical? false :color ColorRGBA/DarkGray
1089 :position (Vector3f. 0 0 0))
1090 (.addControl
1091 (RigidBodyControl.
1092 (CapsuleCollisionShape. 0.5 1.5 1) (float 0))))
1093 table (box 10 2 10 :position (Vector3f. 0 -20 0)
1094 :color ColorRGBA/Gray :mass 0)
1095 a (.getControl top RigidBodyControl)
1096 b (.getControl bottom RigidBodyControl)]
1098 (cond
1099 (= joint :cone)
1101 (doto (ConeJoint.
1102 a b
1103 (world-to-local top joint-position)
1104 (world-to-local bottom joint-position)
1105 joint-rotation
1106 joint-rotation
1110 (.setLimit (* (/ 10) Math/PI)
1111 (* (/ 4) Math/PI)
1112 0)))
1113 [origin top bottom table]))
1115 (defn test-joint [joint]
1116 (let [[origin top bottom floor] (world-setup joint)
1117 control (.getControl top RigidBodyControl)
1118 move-up? (atom false)
1119 move-down? (atom false)
1120 move-left? (atom false)
1121 move-right? (atom false)
1122 roll-left? (atom false)
1123 roll-right? (atom false)
1124 timer (atom 0)]
1126 (world
1127 (nodify [top bottom floor origin])
1128 (merge standard-debug-controls
1129 {"key-r" (fn [_ pressed?] (reset! move-up? pressed?))
1130 "key-t" (fn [_ pressed?] (reset! move-down? pressed?))
1131 "key-f" (fn [_ pressed?] (reset! move-left? pressed?))
1132 "key-g" (fn [_ pressed?] (reset! move-right? pressed?))
1133 "key-v" (fn [_ pressed?] (reset! roll-left? pressed?))
1134 "key-b" (fn [_ pressed?] (reset! roll-right? pressed?))})
1136 (fn [world]
1137 (light-up-everything world)
1138 (enable-debug world)
1139 (set-gravity world (Vector3f. 0 0 0))
1142 (fn [world _]
1143 (if (zero? (rem (swap! timer inc) 100))
1144 (do
1145 ;; (println-repl @timer)
1146 (.attachChild (.getRootNode world)
1147 (sphere 0.05 :color ColorRGBA/Yellow
1148 :position (.getWorldTranslation top)
1149 :physical? false))
1150 (.attachChild (.getRootNode world)
1151 (sphere 0.05 :color ColorRGBA/LightGray
1152 :position (.getWorldTranslation bottom)
1153 :physical? false))))
1155 (if @move-up?
1156 (.applyTorque control
1157 (.mult (.getPhysicsRotation control)
1158 (Vector3f. 0 0 10))))
1159 (if @move-down?
1160 (.applyTorque control
1161 (.mult (.getPhysicsRotation control)
1162 (Vector3f. 0 0 -10))))
1163 (if @move-left?
1164 (.applyTorque control
1165 (.mult (.getPhysicsRotation control)
1166 (Vector3f. 0 10 0))))
1167 (if @move-right?
1168 (.applyTorque control
1169 (.mult (.getPhysicsRotation control)
1170 (Vector3f. 0 -10 0))))
1171 (if @roll-left?
1172 (.applyTorque control
1173 (.mult (.getPhysicsRotation control)
1174 (Vector3f. -1 0 0))))
1175 (if @roll-right?
1176 (.applyTorque control
1177 (.mult (.getPhysicsRotation control)
1178 (Vector3f. 1 0 0))))))))
1182 (defprotocol Frame
1183 (frame [this]))
1185 (extend-type BufferedImage
1186 Frame
1187 (frame [image]
1188 (merge
1189 (apply
1190 hash-map
1191 (interleave
1192 (doall (for [x (range (.getWidth image)) y (range (.getHeight image))]
1193 (vector x y)))
1194 (doall (for [x (range (.getWidth image)) y (range (.getHeight image))]
1195 (let [data (.getRGB image x y)]
1196 (hash-map :r (bit-shift-right (bit-and 0xff0000 data) 16)
1197 :g (bit-shift-right (bit-and 0x00ff00 data) 8)
1198 :b (bit-and 0x0000ff data)))))))
1199 {:width (.getWidth image) :height (.getHeight image)})))
1202 (extend-type ImagePlus
1203 Frame
1204 (frame [image+]
1205 (frame (.getBufferedImage image+))))
1208 #+end_src
1211 * COMMENT generate source
1212 #+begin_src clojure :tangle ../src/cortex/silly.clj
1213 <<body-1>>
1214 #+end_src