Mercurial > cortex
view org/util.org @ 160:33278bf028e7
refactored joints
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Fri, 03 Feb 2012 06:47:05 -0700 |
parents | c95179907951 |
children | c33a8e5fe7bc |
line wrap: on
line source
1 #+title: Clojure Utilities for jMonkeyEngine32 #+author: Robert McIntyre3 #+email: rlm@mit.edu4 #+description:5 #+keywords: JME3, clojure, import, utilities6 #+SETUPFILE: ../../aurellem/org/setup.org7 #+INCLUDE: ../../aurellem/org/level-0.org9 [TABLE-OF-CONTENTS]11 These are a collection of functions to make programming jMonkeyEngine12 in clojure easier.14 * Imports16 #+name: import17 #+begin_src clojure :results silent18 (ns cortex.import19 (:require swank.util.class-browse))21 (defn permissive-import22 [classname]23 (eval `(try (import '~classname)24 (catch java.lang.Exception e#25 (println "couldn't import " '~classname))))26 classname)28 (defn jme-class? [classname]29 (and30 (.startsWith classname "com.jme3.")31 ;; Don't import the Lwjgl stuff since it can throw exceptions32 ;; upon being loaded.33 (not (re-matches #".*Lwjgl.*" classname))))35 (defn jme-classes36 "returns a list of all jme3 classes"37 []38 (filter39 jme-class?40 (map :name41 swank.util.class-browse/available-classes)))43 (defn mega-import-jme344 "Import ALL the jme classes. For REPL use."45 []46 (doall47 (map (comp permissive-import symbol) (jme-classes))))48 #+end_src50 jMonkeyEngine3 has a plethora of classes which can be overwhelming to51 manage. This code uses reflection to import all of them. Once I'm52 happy with the general structure of a namespace I can deal with53 importing only the classes it actually needs.55 The =mega-import-jme3= is quite usefull for debugging purposes since56 it allows completion for almost all of JME's classes from the REPL.58 Out of curiousity, let's see just how many classes =mega-import-jme3=59 imports:61 #+begin_src clojure :exports both :results output62 (println (clojure.core/count (cortex.import/jme-classes)) "classes")63 #+end_src65 #+results:66 : 955 classes69 * Utilities71 The utilities here come in three main groups:72 - Changing settings in a running =Application=73 - Creating objects74 - Debug Actions75 - Visualizing objects77 *** Changing Settings79 #+name: util80 #+begin_src clojure81 (ns cortex.util82 "Utility functions for making jMonkeyEngine3 easier to program from83 clojure."84 {:author "Robert McIntyre"}85 (:use cortex.world)86 (:use clojure.contrib.def)87 (:import com.jme3.math.Vector3f)88 (:import com.jme3.math.Quaternion)89 (:import com.jme3.asset.TextureKey)90 (:import com.jme3.bullet.control.RigidBodyControl)91 (:import com.jme3.bullet.collision.shapes.GImpactCollisionShape)92 (:import com.jme3.scene.shape.Box)93 (:import com.jme3.scene.Node)94 (:import com.jme3.scene.shape.Sphere)95 (:import com.jme3.light.AmbientLight)96 (:import com.jme3.light.DirectionalLight)97 (:import (com.jme3.math Triangle ColorRGBA))98 (:import com.jme3.bullet.BulletAppState)99 (:import com.jme3.material.Material)100 (:import com.jme3.scene.Geometry)101 (:import java.awt.image.BufferedImage)102 (:import javax.swing.JPanel)103 (:import javax.swing.JFrame)104 (:import javax.swing.SwingUtilities)106 (:import (java.util.logging Level Logger)))108 (defvar println-repl109 (bound-fn [& args] (apply println args))110 "println called from the LWJGL thread will not go to the REPL, but111 instead to whatever terminal started the JVM process. This function112 will always output to the REPL")114 (defn position-camera115 "Change the position of the in-world camera."116 ([world position direction up]117 (doto (.getCamera world)118 (.setLocation )119 (.lookAt direction up)))120 ([world position direction]121 (position-camera122 world position direction Vector3f/UNIT_Y)))124 (defn enable-debug125 "Turn on debug wireframes for every object in this simulation."126 [world]127 (.enableDebug128 (.getPhysicsSpace129 (.getState130 (.getStateManager world)131 BulletAppState))132 (asset-manager)))134 (defn speed-up135 "Increase the dismally slow speed of the world's camera."136 [world]137 (.setMoveSpeed (.getFlyByCamera world)138 (float 60))139 (.setRotationSpeed (.getFlyByCamera world)140 (float 3))141 world)144 (defn no-logging145 "Disable all of jMonkeyEngine's logging."146 []147 (.setLevel (Logger/getLogger "com.jme3") Level/OFF))149 (defn set-accuracy150 "Change the accuracy at which the World's Physics is calculated."151 [world new-accuracy]152 (let [physics-manager153 (.getState154 (.getStateManager world) BulletAppState)]155 (.setAccuracy156 (.getPhysicsSpace physics-manager)157 (float new-accuracy))))160 (defn set-gravity161 "In order to change the gravity of a scene, it is not only necessary162 to set the gravity variable, but to \"tap\" every physics object in163 the scene to reactivate physics calculations."164 [world gravity]165 (traverse166 (fn [geom]167 (if-let168 ;; only set gravity for physical objects.169 [control (.getControl geom RigidBodyControl)]170 (do171 (.setGravity control gravity)172 ;; tappsies!173 (.applyImpulse control Vector3f/ZERO Vector3f/ZERO))))174 (.getRootNode world)))176 (defn add-element177 "Add the Spatial to the world's environment"178 ([world element node]179 (.addAll180 (.getPhysicsSpace181 (.getState182 (.getStateManager world)183 BulletAppState))184 element)185 (.attachChild node element))186 ([world element]187 (add-element world element (.getRootNode world))))189 (defn apply-map190 "Like apply, but works for maps and functions that expect an191 implicit map and nothing else as in (fn [& {}]).192 ------- Example -------193 (defn demo [& {:keys [www] :or {www \"oh yeah\"} :as env}]194 (println www))195 (apply-map demo {:www \"hello!\"})196 -->\"hello\""197 [fn m]198 (apply fn (reduce #(into %1 %2) [] m)))200 (defn map-vals201 "Transform a map by applying a function to its values,202 keeping the keys the same."203 [f m] (zipmap (keys m) (map f (vals m))))206 #+end_src208 #+results: util209 : #'cortex.util/apply-map212 *** Creating Basic Shapes214 #+name: shapes215 #+begin_src clojure :results silent216 (in-ns 'cortex.util)218 (defn load-bullet219 "Runnig this function unpacks the native bullet libraries and makes220 them available."221 []222 (let [sim (world (Node.) {} no-op no-op)]223 (doto sim224 (.enqueue225 (fn []226 (.stop sim)))227 (.start))))230 (defrecord shape-description231 [name232 color233 mass234 friction235 texture236 material237 position238 rotation239 shape240 physical?241 GImpact?242 ])244 (defvar base-shape245 (shape-description.246 "default-shape"247 false248 ;;ColorRGBA/Blue249 1.0 ;; mass250 1.0 ;; friction251 ;; texture252 "Textures/Terrain/BrickWall/BrickWall.jpg"253 ;; material254 "Common/MatDefs/Misc/Unshaded.j3md"255 Vector3f/ZERO256 Quaternion/IDENTITY257 (Box. Vector3f/ZERO 0.5 0.5 0.5)258 true259 false)260 "Basic settings for shapes.")262 (defn make-shape263 [#^shape-description d]264 (let [asset-manager (asset-manager)265 mat (Material. asset-manager (:material d))266 geom (Geometry. (:name d) (:shape d))]267 (if (:texture d)268 (let [key (TextureKey. (:texture d))]269 ;;(.setGenerateMips key true)270 ;;(.setTexture mat "ColorMap" (.loadTexture asset-manager key))271 ))272 (if (:color d) (.setColor mat "Color" (:color d)))273 (.setMaterial geom mat)274 (if-let [rotation (:rotation d)] (.rotate geom rotation))275 (.setLocalTranslation geom (:position d))276 (if (:physical? d)277 (let [physics-control278 (if (:GImpact d)279 ;; Create an accurate mesh collision shape if desired.280 (RigidBodyControl.281 (doto (GImpactCollisionShape.282 (.getMesh geom))283 (.createJmeMesh)284 ;;(.setMargin 0)285 )286 (float (:mass d)))287 ;; otherwise use jme3's default288 (RigidBodyControl. (float (:mass d))))]289 (.addControl geom physics-control)290 ;;(.setSleepingThresholds physics-control (float 0) (float 0))291 (.setFriction physics-control (:friction d))))292 geom))294 (defn box295 ([l w h & {:as options}]296 (let [options (merge base-shape options)]297 (make-shape (assoc options298 :shape (Box. l w h)))))299 ([] (box 0.5 0.5 0.5)))301 (defn sphere302 ([r & {:as options}]303 (let [options (merge base-shape options)]304 (make-shape (assoc options305 :shape (Sphere. 32 32 (float r))))))306 ([] (sphere 0.5)))308 (defn green-x-ray309 "A usefull material for debuging -- it can be seen no matter what310 object occuldes it."311 []312 (doto (Material. (asset-manager)313 "Common/MatDefs/Misc/Unshaded.j3md")314 (.setColor "Color" ColorRGBA/Green)315 (-> (.getAdditionalRenderState)316 (.setDepthTest false))))318 (defn node-seq319 "Take a node and return a seq of all its children320 recursively. There will be no nodes left in the resulting321 structure"322 [#^Node node]323 (tree-seq #(isa? (class %) Node) #(.getChildren %) node))325 (defn nodify326 "Take a sequence of things that can be attached to a node and return327 a node with all of them attached"328 ([name children]329 (let [node (Node. name)]330 (dorun (map #(.attachChild node %) children))331 node))332 ([children] (nodify "" children)))335 #+end_src338 *** Debug Actions339 #+name: debug-actions340 #+begin_src clojure :results silent341 (in-ns 'cortex.util)343 (defn basic-light-setup344 "returns a sequence of lights appropiate for fully lighting a scene"345 []346 (conj347 (doall348 (map349 (fn [direction]350 (doto (DirectionalLight.)351 (.setDirection direction)352 (.setColor ColorRGBA/White)))353 [;; six faces of a cube354 Vector3f/UNIT_X355 Vector3f/UNIT_Y356 Vector3f/UNIT_Z357 (.mult Vector3f/UNIT_X (float -1))358 (.mult Vector3f/UNIT_Y (float -1))359 (.mult Vector3f/UNIT_Z (float -1))]))360 (doto (AmbientLight.)361 (.setColor ColorRGBA/White))))363 (defn light-up-everything364 "Add lights to a world appropiate for quickly seeing everything365 in the scene. Adds six DirectionalLights facing in orthogonal366 directions, and one AmbientLight to provide overall lighting367 coverage."368 [world]369 (dorun370 (map371 #(.addLight (.getRootNode world) %)372 (basic-light-setup))))374 (defn fire-cannon-ball375 "Creates a function that fires a cannon-ball from the current game's376 camera. The cannon-ball will be attached to the node if provided, or377 to the game's RootNode if no node is provided."378 ([node]379 (fn [game value]380 (if (not value)381 (let [camera (.getCamera game)382 cannon-ball383 (sphere 0.7384 :material "Common/MatDefs/Misc/Unshaded.j3md"385 :texture "Textures/PokeCopper.jpg"386 :position387 (.add (.getLocation camera)388 (.mult (.getDirection camera) (float 1)))389 :mass 3)] ;200 0.05390 (.setLinearVelocity391 (.getControl cannon-ball RigidBodyControl)392 (.mult (.getDirection camera) (float 50))) ;50393 (add-element game cannon-ball (if node node (.getRootNode game)))))))394 ([]395 (fire-cannon-ball false)))397 (def standard-debug-controls398 {"key-space" (fire-cannon-ball)})401 (defn tap [obj direction force]402 (let [control (.getControl obj RigidBodyControl)]403 (.applyTorque404 control405 (.mult (.getPhysicsRotation control)406 (.mult (.normalize direction) (float force))))))409 (defn with-movement410 [object411 [up down left right roll-up roll-down :as keyboard]412 forces413 [root-node414 keymap415 intilization416 world-loop]]417 (let [add-keypress418 (fn [state keymap key]419 (merge keymap420 {key421 (fn [_ pressed?]422 (reset! state pressed?))}))423 move-up? (atom false)424 move-down? (atom false)425 move-left? (atom false)426 move-right? (atom false)427 roll-left? (atom false)428 roll-right? (atom false)430 directions [(Vector3f. 0 1 0)(Vector3f. 0 -1 0)431 (Vector3f. 0 0 1)(Vector3f. 0 0 -1)432 (Vector3f. -1 0 0)(Vector3f. 1 0 0)]433 atoms [move-left? move-right? move-up? move-down?434 roll-left? roll-right?]436 keymap* (reduce merge437 (map #(add-keypress %1 keymap %2)438 atoms439 keyboard))441 splice-loop (fn []442 (dorun443 (map444 (fn [sym direction force]445 (if @sym446 (tap object direction force)))447 atoms directions forces)))449 world-loop* (fn [world tpf]450 (world-loop world tpf)451 (splice-loop))]452 [root-node453 keymap*454 intilization455 world-loop*]))459 #+end_src462 *** Viewing Objects464 #+name: world-view465 #+begin_src clojure :results silent466 (in-ns 'cortex.util)468 (defn view-image469 "Initailizes a JPanel on which you may draw a BufferedImage.470 Returns a function that accepts a BufferedImage and draws it to the471 JPanel."472 []473 (let [image474 (atom475 (BufferedImage. 1 1 BufferedImage/TYPE_4BYTE_ABGR))476 panel477 (proxy [JPanel] []478 (paint479 [graphics]480 (proxy-super paintComponent graphics)481 (.drawImage graphics @image 0 0 nil)))482 frame (JFrame. "Display Image")]483 (SwingUtilities/invokeLater484 (fn []485 (doto frame486 (-> (.getContentPane) (.add panel))487 (.pack)488 (.setLocationRelativeTo nil)489 (.setResizable true)490 (.setVisible true))))491 (fn [#^BufferedImage i]492 (reset! image i)493 (.setSize frame (+ 8 (.getWidth i)) (+ 28 (.getHeight i)))494 (.repaint panel 0 0 (.getWidth i) (.getHeight i)))))496 (defprotocol Viewable497 (view [something]))499 (extend-type com.jme3.scene.Geometry500 Viewable501 (view [geo]502 (view (doto (Node.)(.attachChild geo)))))504 (extend-type com.jme3.scene.Node505 Viewable506 (view507 [node]508 (.start509 (world510 node511 {}512 (fn [world]513 (enable-debug world)514 (set-gravity world Vector3f/ZERO)515 (light-up-everything world))516 no-op))))518 (extend-type com.jme3.math.ColorRGBA519 Viewable520 (view521 [color]522 (view (doto (Node.)523 (.attachChild (box 1 1 1 :color color))))))525 (defprotocol Textual526 (text [something]527 "Display a detailed textual analysis of the given object."))529 (extend-type com.jme3.scene.Node530 Textual531 (text [node]532 (println "Total Vertexes: " (.getVertexCount node))533 (println "Total Triangles: " (.getTriangleCount node))534 (println "Controls :")535 (dorun (map #(text (.getControl node %)) (range (.getNumControls node))))536 (println "Has " (.getQuantity node) " Children:")537 (doall (map text (.getChildren node)))))539 (extend-type com.jme3.animation.AnimControl540 Textual541 (text [control]542 (let [animations (.getAnimationNames control)]543 (println "Animation Control with " (count animations) " animation(s):")544 (dorun (map println animations)))))546 (extend-type com.jme3.animation.SkeletonControl547 Textual548 (text [control]549 (println "Skeleton Control with the following skeleton:")550 (println (.getSkeleton control))))552 (extend-type com.jme3.bullet.control.KinematicRagdollControl553 Textual554 (text [control]555 (println "Ragdoll Control")))557 (extend-type com.jme3.scene.Geometry558 Textual559 (text [control]560 (println "...geo...")))562 (extend-type Triangle563 Textual564 (text [t]565 (println "Triangle: " \newline (.get1 t) \newline566 (.get2 t) \newline (.get3 t))))568 #+end_src570 Here I make the =Viewable= protocol and extend it to JME's types. Now571 JME3's =hello-world= can be written as easily as:573 #+begin_src clojure :results silent574 (cortex.util/view (cortex.util/box))575 #+end_src578 * COMMENT code generation579 #+begin_src clojure :tangle ../src/cortex/import.clj580 <<import>>581 #+end_src584 #+begin_src clojure :tangle ../src/cortex/util.clj :noweb yes585 <<util>>586 <<shapes>>587 <<debug-actions>>588 <<world-view>>589 #+end_src