Mercurial > cortex
view org/util.org @ 309:5d448182c807
added/verified YouTube backup links for all videos.
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Sat, 18 Feb 2012 11:42:34 -0700 |
parents | 7e7f8d6d9ec5 |
children | bb3f8a4af87f |
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 useful for debugging purposes since56 it allows completion for almost all of JME's classes from the REPL.58 Out of curiosity, 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)105 (:import com.jme3.scene.plugins.blender.BlenderModelLoader)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 #^Vector3f position #^Quaternion rotation]117 (doto (.getCamera world)118 (.setLocation position)119 (.setRotation rotation)))121 (defn enable-debug122 "Turn on debug wireframes for every object in this simulation."123 [world]124 (.enableDebug125 (.getPhysicsSpace126 (.getState127 (.getStateManager world)128 BulletAppState))129 (asset-manager)))131 (defn speed-up132 "Increase the dismally slow speed of the world's camera."133 [world]134 (.setMoveSpeed (.getFlyByCamera world)135 (float 60))136 (.setRotationSpeed (.getFlyByCamera world)137 (float 3))138 world)141 (defn no-logging142 "Disable all of jMonkeyEngine's logging."143 []144 (.setLevel (Logger/getLogger "com.jme3") Level/OFF))146 (defn set-accuracy147 "Change the accuracy at which the World's Physics is calculated."148 [world new-accuracy]149 (let [physics-manager150 (.getState151 (.getStateManager world) BulletAppState)]152 (.setAccuracy153 (.getPhysicsSpace physics-manager)154 (float new-accuracy))))157 (defn set-gravity158 "In order to change the gravity of a scene, it is not only necessary159 to set the gravity variable, but to \"tap\" every physics object in160 the scene to reactivate physics calculations."161 [world gravity]162 (traverse163 (fn [geom]164 (if-let165 ;; only set gravity for physical objects.166 [control (.getControl geom RigidBodyControl)]167 (do168 (.setGravity control gravity)169 ;; tappsies!170 (.applyImpulse control Vector3f/ZERO Vector3f/ZERO))))171 (.getRootNode world)))173 (defn add-element174 "Add the Spatial to the world's environment"175 ([world element node]176 (.addAll177 (.getPhysicsSpace178 (.getState179 (.getStateManager world)180 BulletAppState))181 element)182 (.attachChild node element))183 ([world element]184 (add-element world element (.getRootNode world))))186 (defn apply-map187 "Like apply, but works for maps and functions that expect an188 implicit map and nothing else as in (fn [& {}]).189 ------- Example -------190 (defn demo [& {:keys [www] :or {www \"oh yeah\"} :as env}]191 (println www))192 (apply-map demo {:www \"hello!\"})193 -->\"hello\""194 [fn m]195 (apply fn (reduce #(into %1 %2) [] m)))197 (defn map-vals198 "Transform a map by applying a function to its values,199 keeping the keys the same."200 [f m] (zipmap (keys m) (map f (vals m))))202 (defn runonce203 "Decorator. returns a function which will run only once.204 Inspired by Halloway's version from Lancet."205 {:author "Robert McIntyre"}206 [function]207 (let [sentinel (Object.)208 result (atom sentinel)]209 (fn [& args]210 (locking sentinel211 (if (= @result sentinel)212 (reset! result (apply function args))213 @result)))))216 #+end_src218 #+results: util219 : #'cortex.util/runonce222 *** Creating Basic Shapes224 #+name: shapes225 #+begin_src clojure :results silent226 (in-ns 'cortex.util)228 (defn load-bullet229 "Running this function unpacks the native bullet libraries and makes230 them available."231 []232 (let [sim (world (Node.) {} no-op no-op)]233 (doto sim234 (.enqueue235 (fn []236 (.stop sim)))237 (.start))))240 (defrecord shape-description241 [name242 color243 mass244 friction245 texture246 material247 position248 rotation249 shape250 physical?251 GImpact?252 ])254 (defvar base-shape255 (shape-description.256 "default-shape"257 false258 ;;ColorRGBA/Blue259 1.0 ;; mass260 1.0 ;; friction261 ;; texture262 "Textures/Terrain/BrickWall/BrickWall.jpg"263 ;; material264 "Common/MatDefs/Misc/Unshaded.j3md"265 Vector3f/ZERO266 Quaternion/IDENTITY267 (Box. Vector3f/ZERO 0.5 0.5 0.5)268 true269 false)270 "Basic settings for shapes.")272 (defn make-shape273 [#^shape-description d]274 (let [asset-manager (asset-manager)275 mat (Material. asset-manager (:material d))276 geom (Geometry. (:name d) (:shape d))]277 (if (:texture d)278 (let [key (TextureKey. (:texture d))]279 ;;(.setGenerateMips key true)280 ;;(.setTexture mat "ColorMap" (.loadTexture asset-manager key))281 ))282 (if (:color d) (.setColor mat "Color" (:color d)))283 (.setMaterial geom mat)284 (if-let [rotation (:rotation d)] (.rotate geom rotation))285 (.setLocalTranslation geom (:position d))286 (if (:physical? d)287 (let [physics-control288 (if (:GImpact d)289 ;; Create an accurate mesh collision shape if desired.290 (RigidBodyControl.291 (doto (GImpactCollisionShape.292 (.getMesh geom))293 (.createJmeMesh)294 ;;(.setMargin 0)295 )296 (float (:mass d)))297 ;; otherwise use jme3's default298 (RigidBodyControl. (float (:mass d))))]299 (.addControl geom physics-control)300 ;;(.setSleepingThresholds physics-control (float 0) (float 0))301 (.setFriction physics-control (:friction d))))302 geom))304 (defn box305 ([l w h & {:as options}]306 (let [options (merge base-shape options)]307 (make-shape (assoc options308 :shape (Box. l w h)))))309 ([] (box 0.5 0.5 0.5)))311 (defn sphere312 ([r & {:as options}]313 (let [options (merge base-shape options)]314 (make-shape (assoc options315 :shape (Sphere. 32 32 (float r))))))316 ([] (sphere 0.5)))318 (defn x-ray319 "A useful material for debugging -- it can be seen no matter what320 object occludes it."321 [#^ColorRGBA color]322 (doto (Material. (asset-manager)323 "Common/MatDefs/Misc/Unshaded.j3md")324 (.setColor "Color" color)325 (-> (.getAdditionalRenderState)326 (.setDepthTest false))))328 (defn node-seq329 "Take a node and return a seq of all its children330 recursively. There will be no nodes left in the resulting331 structure"332 [#^Node node]333 (tree-seq #(isa? (class %) Node) #(.getChildren %) node))335 (defn nodify336 "Take a sequence of things that can be attached to a node and return337 a node with all of them attached"338 ([name children]339 (let [node (Node. name)]340 (dorun (map #(.attachChild node %) children))341 node))342 ([children] (nodify "" children)))344 (defn load-blender-model345 "Load a .blend file using an asset folder relative path."346 [^String model]347 (.loadModel348 (doto (asset-manager)349 (.registerLoader BlenderModelLoader350 (into-array String ["blend"]))) model))353 #+end_src356 *** Debug Actions357 #+name: debug-actions358 #+begin_src clojure :results silent359 (in-ns 'cortex.util)361 (defn basic-light-setup362 "returns a sequence of lights appropriate for fully lighting a scene"363 []364 (conj365 (doall366 (map367 (fn [direction]368 (doto (DirectionalLight.)369 (.setDirection direction)370 (.setColor ColorRGBA/White)))371 [;; six faces of a cube372 Vector3f/UNIT_X373 Vector3f/UNIT_Y374 Vector3f/UNIT_Z375 (.mult Vector3f/UNIT_X (float -1))376 (.mult Vector3f/UNIT_Y (float -1))377 (.mult Vector3f/UNIT_Z (float -1))]))378 (doto (AmbientLight.)379 (.setColor ColorRGBA/White))))381 (defn light-up-everything382 "Add lights to a world appropriate for quickly seeing everything383 in the scene. Adds six DirectionalLights facing in orthogonal384 directions, and one AmbientLight to provide overall lighting385 coverage."386 [world]387 (dorun388 (map389 #(.addLight (.getRootNode world) %)390 (basic-light-setup))))392 (defn fire-cannon-ball393 "Creates a function that fires a cannon-ball from the current game's394 camera. The cannon-ball will be attached to the node if provided, or395 to the game's RootNode if no node is provided."396 ([node]397 (fn [game value]398 (if (not value)399 (let [camera (.getCamera game)400 cannon-ball401 (sphere 0.7402 :material "Common/MatDefs/Misc/Unshaded.j3md"403 :color ColorRGBA/White404 :name "cannonball!"405 :position406 (.add (.getLocation camera)407 (.mult (.getDirection camera) (float 1)))408 :mass 3)] ;200 0.05409 (.setLinearVelocity410 (.getControl cannon-ball RigidBodyControl)411 (.mult (.getDirection camera) (float 50))) ;50412 (add-element game cannon-ball (if node node (.getRootNode413 game)))414 cannon-ball))))415 ([]416 (fire-cannon-ball false)))418 (def standard-debug-controls419 {"key-space" (fire-cannon-ball)})422 (defn tap [obj direction force]423 (let [control (.getControl obj RigidBodyControl)]424 (.applyTorque425 control426 (.mult (.getPhysicsRotation control)427 (.mult (.normalize direction) (float force))))))430 (defn with-movement431 [object432 [up down left right roll-up roll-down :as keyboard]433 forces434 [root-node435 keymap436 initialization437 world-loop]]438 (let [add-keypress439 (fn [state keymap key]440 (merge keymap441 {key442 (fn [_ pressed?]443 (reset! state pressed?))}))444 move-up? (atom false)445 move-down? (atom false)446 move-left? (atom false)447 move-right? (atom false)448 roll-left? (atom false)449 roll-right? (atom false)451 directions [(Vector3f. 0 1 0)(Vector3f. 0 -1 0)452 (Vector3f. 0 0 1)(Vector3f. 0 0 -1)453 (Vector3f. -1 0 0)(Vector3f. 1 0 0)]454 atoms [move-left? move-right? move-up? move-down?455 roll-left? roll-right?]457 keymap* (reduce merge458 (map #(add-keypress %1 keymap %2)459 atoms460 keyboard))462 splice-loop (fn []463 (dorun464 (map465 (fn [sym direction force]466 (if @sym467 (tap object direction force)))468 atoms directions forces)))470 world-loop* (fn [world tpf]471 (world-loop world tpf)472 (splice-loop))]473 [root-node474 keymap*475 initialization476 world-loop*]))478 (import com.jme3.font.BitmapText)479 (import com.jme3.scene.control.AbstractControl)480 (import com.aurellem.capture.IsoTimer)482 (defn display-dilated-time483 "Shows the time as it is flowing in the simulation on a HUD display.484 Useful for making videos."485 [world timer]486 (let [font (.loadFont (asset-manager) "Interface/Fonts/Default.fnt")487 text (BitmapText. font false)]488 (.setLocalTranslation text 300 (.getLineHeight text) 0)489 (.addControl490 text491 (proxy [AbstractControl] []492 (controlUpdate [tpf]493 (.setText text (format494 "%.2f"495 (float (/ (.getTime timer) 1000)))))496 (controlRender [_ _])))497 (.attachChild (.getGuiNode world) text)))498 #+end_src501 *** Viewing Objects503 #+name: world-view504 #+begin_src clojure :results silent505 (in-ns 'cortex.util)507 (defprotocol Viewable508 (view [something]))510 (extend-type com.jme3.scene.Geometry511 Viewable512 (view [geo]513 (view (doto (Node.)(.attachChild geo)))))515 (extend-type com.jme3.scene.Node516 Viewable517 (view518 [node]519 (.start520 (world521 node522 {}523 (fn [world]524 (enable-debug world)525 (set-gravity world Vector3f/ZERO)526 (light-up-everything world))527 no-op))))529 (extend-type com.jme3.math.ColorRGBA530 Viewable531 (view532 [color]533 (view (doto (Node.)534 (.attachChild (box 1 1 1 :color color))))))536 (defprotocol Textual537 (text [something]538 "Display a detailed textual analysis of the given object."))540 (extend-type com.jme3.scene.Node541 Textual542 (text [node]543 (println "Total Vertexes: " (.getVertexCount node))544 (println "Total Triangles: " (.getTriangleCount node))545 (println "Controls :")546 (dorun (map #(text (.getControl node %)) (range (.getNumControls node))))547 (println "Has " (.getQuantity node) " Children:")548 (doall (map text (.getChildren node)))))550 (extend-type com.jme3.animation.AnimControl551 Textual552 (text [control]553 (let [animations (.getAnimationNames control)]554 (println "Animation Control with " (count animations) " animation(s):")555 (dorun (map println animations)))))557 (extend-type com.jme3.animation.SkeletonControl558 Textual559 (text [control]560 (println "Skeleton Control with the following skeleton:")561 (println (.getSkeleton control))))563 (extend-type com.jme3.bullet.control.KinematicRagdollControl564 Textual565 (text [control]566 (println "Ragdoll Control")))568 (extend-type com.jme3.scene.Geometry569 Textual570 (text [control]571 (println "...geo...")))573 (extend-type Triangle574 Textual575 (text [t]576 (println "Triangle: " \newline (.get1 t) \newline577 (.get2 t) \newline (.get3 t))))579 #+end_src581 Here I make the =Viewable= protocol and extend it to JME's types. Now582 JME3's =hello-world= can be written as easily as:584 #+begin_src clojure :results silent585 (cortex.util/view (cortex.util/box))586 #+end_src589 * COMMENT code generation590 #+begin_src clojure :tangle ../src/cortex/import.clj591 <<import>>592 #+end_src595 #+begin_src clojure :tangle ../src/cortex/util.clj :noweb yes596 <<util>>597 <<shapes>>598 <<debug-actions>>599 <<world-view>>600 #+end_src