Mercurial > cortex
view org/util.org @ 151:aaacf087504c
refactored vision code
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Fri, 03 Feb 2012 05:52:18 -0700 |
parents | b591da250afc |
children | c95179907951 |
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))))207 #+end_src209 #+results: util210 : #'cortex.util/apply-map213 *** Creating Basic Shapes215 #+name: shapes216 #+begin_src clojure :results silent217 (in-ns 'cortex.util)219 (defrecord shape-description220 [name221 color222 mass223 friction224 texture225 material226 position227 rotation228 shape229 physical?230 GImpact?231 ])233 (defvar base-shape234 (shape-description.235 "default-shape"236 false237 ;;ColorRGBA/Blue238 1.0 ;; mass239 1.0 ;; friction240 ;; texture241 "Textures/Terrain/BrickWall/BrickWall.jpg"242 ;; material243 "Common/MatDefs/Misc/Unshaded.j3md"244 Vector3f/ZERO245 Quaternion/IDENTITY246 (Box. Vector3f/ZERO 0.5 0.5 0.5)247 true248 false)249 "Basic settings for shapes.")251 (defn make-shape252 [#^shape-description d]253 (let [asset-manager (asset-manager)254 mat (Material. asset-manager (:material d))255 geom (Geometry. (:name d) (:shape d))]256 (if (:texture d)257 (let [key (TextureKey. (:texture d))]258 ;;(.setGenerateMips key true)259 ;;(.setTexture mat "ColorMap" (.loadTexture asset-manager key))260 ))261 (if (:color d) (.setColor mat "Color" (:color d)))262 (.setMaterial geom mat)263 (if-let [rotation (:rotation d)] (.rotate geom rotation))264 (.setLocalTranslation geom (:position d))265 (if (:physical? d)266 (let [physics-control267 (if (:GImpact d)268 ;; Create an accurate mesh collision shape if desired.269 (RigidBodyControl.270 (doto (GImpactCollisionShape.271 (.getMesh geom))272 (.createJmeMesh)273 ;;(.setMargin 0)274 )275 (float (:mass d)))276 ;; otherwise use jme3's default277 (RigidBodyControl. (float (:mass d))))]278 (.addControl geom physics-control)279 ;;(.setSleepingThresholds physics-control (float 0) (float 0))280 (.setFriction physics-control (:friction d))))281 geom))283 (defn box284 ([l w h & {:as options}]285 (let [options (merge base-shape options)]286 (make-shape (assoc options287 :shape (Box. l w h)))))288 ([] (box 0.5 0.5 0.5)))290 (defn sphere291 ([r & {:as options}]292 (let [options (merge base-shape options)]293 (make-shape (assoc options294 :shape (Sphere. 32 32 (float r))))))295 ([] (sphere 0.5)))297 (defn green-x-ray298 "A usefull material for debuging -- it can be seen no matter what299 object occuldes it."300 []301 (doto (Material. (asset-manager)302 "Common/MatDefs/Misc/Unshaded.j3md")303 (.setColor "Color" ColorRGBA/Green)304 (-> (.getAdditionalRenderState)305 (.setDepthTest false))))307 (defn node-seq308 "Take a node and return a seq of all its children309 recursively. There will be no nodes left in the resulting310 structure"311 [#^Node node]312 (tree-seq #(isa? (class %) Node) #(.getChildren %) node))314 (defn nodify315 "Take a sequence of things that can be attached to a node and return316 a node with all of them attached"317 ([name children]318 (let [node (Node. name)]319 (dorun (map #(.attachChild node %) children))320 node))321 ([children] (nodify "" children)))324 #+end_src327 *** Debug Actions328 #+name: debug-actions329 #+begin_src clojure :results silent330 (in-ns 'cortex.util)332 (defn basic-light-setup333 "returns a sequence of lights appropiate for fully lighting a scene"334 []335 (conj336 (doall337 (map338 (fn [direction]339 (doto (DirectionalLight.)340 (.setDirection direction)341 (.setColor ColorRGBA/White)))342 [;; six faces of a cube343 Vector3f/UNIT_X344 Vector3f/UNIT_Y345 Vector3f/UNIT_Z346 (.mult Vector3f/UNIT_X (float -1))347 (.mult Vector3f/UNIT_Y (float -1))348 (.mult Vector3f/UNIT_Z (float -1))]))349 (doto (AmbientLight.)350 (.setColor ColorRGBA/White))))352 (defn light-up-everything353 "Add lights to a world appropiate for quickly seeing everything354 in the scene. Adds six DirectionalLights facing in orthogonal355 directions, and one AmbientLight to provide overall lighting356 coverage."357 [world]358 (dorun359 (map360 #(.addLight (.getRootNode world) %)361 (basic-light-setup))))363 (defn fire-cannon-ball364 "Creates a function that fires a cannon-ball from the current game's365 camera. The cannon-ball will be attached to the node if provided, or366 to the game's RootNode if no node is provided."367 ([node]368 (fn [game value]369 (if (not value)370 (let [camera (.getCamera game)371 cannon-ball372 (sphere 0.7373 :material "Common/MatDefs/Misc/Unshaded.j3md"374 :texture "Textures/PokeCopper.jpg"375 :position376 (.add (.getLocation camera)377 (.mult (.getDirection camera) (float 1)))378 :mass 3)] ;200 0.05379 (.setLinearVelocity380 (.getControl cannon-ball RigidBodyControl)381 (.mult (.getDirection camera) (float 50))) ;50382 (add-element game cannon-ball (if node node (.getRootNode game)))))))383 ([]384 (fire-cannon-ball false)))386 (def standard-debug-controls387 {"key-space" (fire-cannon-ball)})392 #+end_src395 *** Viewing Objects397 #+name: world-view398 #+begin_src clojure :results silent399 (in-ns 'cortex.util)401 (defn view-image402 "Initailizes a JPanel on which you may draw a BufferedImage.403 Returns a function that accepts a BufferedImage and draws it to the404 JPanel."405 []406 (let [image407 (atom408 (BufferedImage. 1 1 BufferedImage/TYPE_4BYTE_ABGR))409 panel410 (proxy [JPanel] []411 (paint412 [graphics]413 (proxy-super paintComponent graphics)414 (.drawImage graphics @image 0 0 nil)))415 frame (JFrame. "Display Image")]416 (SwingUtilities/invokeLater417 (fn []418 (doto frame419 (-> (.getContentPane) (.add panel))420 (.pack)421 (.setLocationRelativeTo nil)422 (.setResizable true)423 (.setVisible true))))424 (fn [#^BufferedImage i]425 (reset! image i)426 (.setSize frame (+ 8 (.getWidth i)) (+ 28 (.getHeight i)))427 (.repaint panel 0 0 (.getWidth i) (.getHeight i)))))429 (defprotocol Viewable430 (view [something]))432 (extend-type com.jme3.scene.Geometry433 Viewable434 (view [geo]435 (view (doto (Node.)(.attachChild geo)))))437 (extend-type com.jme3.scene.Node438 Viewable439 (view440 [node]441 (.start442 (world443 node444 {}445 (fn [world]446 (enable-debug world)447 (set-gravity world Vector3f/ZERO)448 (light-up-everything world))449 no-op))))451 (extend-type com.jme3.math.ColorRGBA452 Viewable453 (view454 [color]455 (view (doto (Node.)456 (.attachChild (box 1 1 1 :color color))))))458 (defprotocol Textual459 (text [something]460 "Display a detailed textual analysis of the given object."))462 (extend-type com.jme3.scene.Node463 Textual464 (text [node]465 (println "Total Vertexes: " (.getVertexCount node))466 (println "Total Triangles: " (.getTriangleCount node))467 (println "Controls :")468 (dorun (map #(text (.getControl node %)) (range (.getNumControls node))))469 (println "Has " (.getQuantity node) " Children:")470 (doall (map text (.getChildren node)))))472 (extend-type com.jme3.animation.AnimControl473 Textual474 (text [control]475 (let [animations (.getAnimationNames control)]476 (println "Animation Control with " (count animations) " animation(s):")477 (dorun (map println animations)))))479 (extend-type com.jme3.animation.SkeletonControl480 Textual481 (text [control]482 (println "Skeleton Control with the following skeleton:")483 (println (.getSkeleton control))))485 (extend-type com.jme3.bullet.control.KinematicRagdollControl486 Textual487 (text [control]488 (println "Ragdoll Control")))490 (extend-type com.jme3.scene.Geometry491 Textual492 (text [control]493 (println "...geo...")))495 (extend-type Triangle496 Textual497 (text [t]498 (println "Triangle: " \newline (.get1 t) \newline499 (.get2 t) \newline (.get3 t))))501 #+end_src503 Here I make the =Viewable= protocol and extend it to JME's types. Now504 JME3's =hello-world= can be written as easily as:506 #+begin_src clojure :results silent507 (cortex.util/view (cortex.util/box))508 #+end_src511 * COMMENT code generation512 #+begin_src clojure :tangle ../src/cortex/import.clj513 <<import>>514 #+end_src517 #+begin_src clojure :tangle ../src/cortex/util.clj :noweb yes518 <<util>>519 <<shapes>>520 <<debug-actions>>521 <<world-view>>522 #+end_src