Mercurial > cortex
view org/util.org @ 73:257a86328adb
saving progress
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Wed, 28 Dec 2011 00:00:23 -0700 |
parents | 0235c32152af |
children | fb810a2c50c2 |
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.ColorRGBA)98 (:import com.jme3.bullet.BulletAppState)99 (:import com.jme3.material.Material)100 (:import com.jme3.scene.Geometry)101 (:import (java.util.logging Level Logger)))105 (defvar println-repl106 (bound-fn [& args] (apply println args))107 "println called from the LWJGL thread will not go to the REPL, but108 instead to whatever terminal started the JVM process. This function109 will always output to the REPL")111 (defn position-camera112 "Change the position of the in-world camera."113 ([world position direction up]114 (doto (.getCamera world)115 (.setLocation )116 (.lookAt direction up)))117 ([world position direction]118 (position-camera119 world position direction Vector3f/UNIT_Y)))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 no-logging132 "Disable all of jMonkeyEngine's logging."133 []134 (.setLevel (Logger/getLogger "com.jme3") Level/OFF))136 (defn set-accuracy137 "Change the accuracy at which the World's Physics is calculated."138 [world new-accuracy]139 (let [physics-manager140 (.getState141 (.getStateManager world) BulletAppState)]142 (.setAccuracy143 (.getPhysicsSpace physics-manager)144 (float new-accuracy))))147 (defn set-gravity148 "In order to change the gravity of a scene, it is not only necessary149 to set the gravity variable, but to \"tap\" every physics object in150 the scene to reactivate physics calculations."151 [world gravity]152 (traverse153 (fn [geom]154 (if-let155 ;; only set gravity for physical objects.156 [control (.getControl geom RigidBodyControl)]157 (do158 (.setGravity control gravity)159 ;; tappsies!160 (.applyImpulse control Vector3f/ZERO Vector3f/ZERO))))161 (.getRootNode world)))163 (defn add-element164 "Add the Spatial to the world's environment"165 ([world element node]166 (.addAll167 (.getPhysicsSpace168 (.getState169 (.getStateManager world)170 BulletAppState))171 element)172 (.attachChild node element))173 ([world element]174 (add-element world element (.getRootNode world))))176 (defn apply-map177 "Like apply, but works for maps and functions that expect an178 implicit map and nothing else as in (fn [& {}]).179 ------- Example -------180 (defn demo [& {:keys [www] :or {www \"oh yeah\"} :as env}]181 (println www))182 (apply-map demo {:www \"hello!\"})183 -->\"hello\""184 [fn m]185 (apply fn (reduce #(into %1 %2) [] m)))187 #+end_src189 #+results: util190 : #'cortex.util/apply-map193 *** Creating Basic Shapes195 #+name: shapes196 #+begin_src clojure :results silent197 (in-ns 'cortex.util)199 (defrecord shape-description200 [name201 color202 mass203 friction204 texture205 material206 position207 rotation208 shape209 physical?210 GImpact?211 ])213 (defvar base-shape214 (shape-description.215 "default-shape"216 false217 ;;ColorRGBA/Blue218 1.0 ;; mass219 1.0 ;; friction220 ;; texture221 "Textures/Terrain/BrickWall/BrickWall.jpg"222 ;; material223 "Common/MatDefs/Misc/Unshaded.j3md"224 Vector3f/ZERO225 Quaternion/IDENTITY226 (Box. Vector3f/ZERO 0.5 0.5 0.5)227 true228 false)229 "Basic settings for shapes.")231 (defn make-shape232 [#^shape-description d]233 (let [asset-manager (asset-manager)234 mat (Material. asset-manager (:material d))235 geom (Geometry. (:name d) (:shape d))]236 (if (:texture d)237 (let [key (TextureKey. (:texture d))]238 ;;(.setGenerateMips key true)239 ;;(.setTexture mat "ColorMap" (.loadTexture asset-manager key))240 ))241 (if (:color d) (.setColor mat "Color" (:color d)))242 (.setMaterial geom mat)243 (if-let [rotation (:rotation d)] (.rotate geom rotation))244 (.setLocalTranslation geom (:position d))245 (if (:physical? d)246 (let [physics-control247 (if (:GImpact d)248 ;; Create an accurate mesh collision shape if desired.249 (RigidBodyControl.250 (doto (GImpactCollisionShape.251 (.getMesh geom))252 (.createJmeMesh)253 ;;(.setMargin 0)254 )255 (float (:mass d)))256 ;; otherwise use jme3's default257 (RigidBodyControl. (float (:mass d))))]258 (.addControl geom physics-control)259 ;;(.setSleepingThresholds physics-control (float 0) (float 0))260 (.setFriction physics-control (:friction d))))261 geom))263 (defn box264 ([l w h & {:as options}]265 (let [options (merge base-shape options)]266 (make-shape (assoc options267 :shape (Box. l w h)))))268 ([] (box 0.5 0.5 0.5)))270 (defn sphere271 ([r & {:as options}]272 (let [options (merge base-shape options)]273 (make-shape (assoc options274 :shape (Sphere. 32 32 (float r))))))275 ([] (sphere 0.5)))277 (defn node-seq278 "Take a node and return a seq of all its children279 recursively. There will be no nodes left in the resulting280 structure"281 [#^Node node]282 (tree-seq #(isa? (class %) Node) #(.getChildren %) node))284 (defn nodify285 "Take a sequence of things that can be attached to a node and return286 a node with all of them attached"287 ([name children]288 (let [node (Node. name)]289 (dorun (map #(.attachChild node %) children))290 node))291 ([children] (nodify "" children)))294 #+end_src297 *** Debug Actions298 #+name: debug-actions299 #+begin_src clojure :results silent300 (in-ns 'cortex.util)302 (defn basic-light-setup303 "returns a sequence of lights appropiate for fully lighting a scene"304 []305 (conj306 (doall307 (map308 (fn [direction]309 (doto (DirectionalLight.)310 (.setDirection direction)311 (.setColor ColorRGBA/White)))312 [;; six faces of a cube313 Vector3f/UNIT_X314 Vector3f/UNIT_Y315 Vector3f/UNIT_Z316 (.mult Vector3f/UNIT_X (float -1))317 (.mult Vector3f/UNIT_Y (float -1))318 (.mult Vector3f/UNIT_Z (float -1))]))319 (doto (AmbientLight.)320 (.setColor ColorRGBA/White))))322 (defn light-up-everything323 "Add lights to a world appropiate for quickly seeing everything324 in the scene. Adds six DirectionalLights facing in orthogonal325 directions, and one AmbientLight to provide overall lighting326 coverage."327 [world]328 (dorun329 (map330 #(.addLight (.getRootNode world) %)331 (basic-light-setup))))333 (defn fire-cannon-ball334 "Creates a function that fires a cannon-ball from the current game's335 camera. The cannon-ball will be attached to the node if provided, or336 to the game's RootNode if no node is provided."337 ([node]338 (fn [game value]339 (if (not value)340 (let [camera (.getCamera game)341 cannon-ball342 (sphere 0.7343 :material "Common/MatDefs/Misc/Unshaded.j3md"344 :texture "Textures/PokeCopper.jpg"345 :position346 (.add (.getLocation camera)347 (.mult (.getDirection camera) (float 1)))348 :mass 3)] ;200 0.05349 (.setLinearVelocity350 (.getControl cannon-ball RigidBodyControl)351 (.mult (.getDirection camera) (float 50))) ;50352 (add-element game cannon-ball (if node node (.getRootNode game)))))))353 ([]354 (fire-cannon-ball false)))356 (def standard-debug-controls357 {"key-space" (fire-cannon-ball)})362 #+end_src365 *** Viewing Objects367 #+name: world-view368 #+begin_src clojure :results silent369 (in-ns 'cortex.util)371 (defprotocol Viewable372 (view [something]))374 (extend-type com.jme3.scene.Geometry375 Viewable376 (view [geo]377 (view (doto (Node.)(.attachChild geo)))))379 (extend-type com.jme3.scene.Node380 Viewable381 (view382 [node]383 (.start384 (world385 node386 {}387 (fn [world]388 (enable-debug world)389 (set-gravity world Vector3f/ZERO)390 (light-up-everything world))391 no-op))))393 (extend-type com.jme3.math.ColorRGBA394 Viewable395 (view396 [color]397 (view (doto (Node.)398 (.attachChild (box 1 1 1 :color color))))))400 (defprotocol Textual401 (text [something]402 "Display a detailed textual analysis of the given object."))404 (extend-type com.jme3.scene.Node405 Textual406 (text [node]407 (println "Total Vertexes: " (.getVertexCount node))408 (println "Total Triangles: " (.getTriangleCount node))409 (println "Controls :")410 (dorun (map #(text (.getControl node %)) (range (.getNumControls node))))411 (println "Has " (.getQuantity node) " Children:")412 (doall (map text (.getChildren node)))))414 (extend-type com.jme3.animation.AnimControl415 Textual416 (text [control]417 (let [animations (.getAnimationNames control)]418 (println "Animation Control with " (count animations) " animation(s):")419 (dorun (map println animations)))))421 (extend-type com.jme3.animation.SkeletonControl422 Textual423 (text [control]424 (println "Skeleton Control with the following skeleton:")425 (println (.getSkeleton control))))427 (extend-type com.jme3.bullet.control.KinematicRagdollControl428 Textual429 (text [control]430 (println "Ragdoll Control")))432 (extend-type com.jme3.scene.Geometry433 Textual434 (text [control]435 (println "...geo...")))436 #+end_src438 Here I make the =Viewable= protocol and extend it to JME's types. Now439 JME3's =hello-world= can be written as easily as:441 #+begin_src clojure :results silent442 (cortex.util/view (cortex.util/box))443 #+end_src446 * COMMENT code generation447 #+begin_src clojure :tangle ../src/cortex/import.clj448 <<import>>449 #+end_src452 #+begin_src clojure :tangle ../src/cortex/util.clj :noweb yes453 <<util>>454 <<shapes>>455 <<debug-actions>>456 <<world-view>>457 #+end_src