Mercurial > cortex
view org/world.org @ 456:a3e23fb5d387
remove USELESS file.
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Fri, 07 Jun 2013 04:36:23 -0400 |
parents | 52de8a36edde |
children | 939bcc5950b2 |
line wrap: on
line source
1 #+title: A Virtual World for Sensate Creatures2 #+author: Robert McIntyre3 #+email: rlm@mit.edu4 #+description: Creating a Virtual World for AI constructs using clojure and JME35 #+keywords: JME3, clojure, virtual world, exception handling6 #+SETUPFILE: ../../aurellem/org/setup.org7 #+INCLUDE: ../../aurellem/org/level-0.org8 #+BABEL: :mkdirp yes :noweb yes :exports both10 * The World12 There's no point in having senses if there's nothing to experience. In13 this section I make some tools with which to build virtual worlds for14 my characters to inhabit. If you look at the tutorials at [[http://www.jmonkeyengine.org/wiki/doku.php/jme3:beginner][the jme315 website]], you will see a pattern in how virtual worlds are normally16 built. I call this "the Java way" of making worlds.18 - The Java way:19 - Create a class that extends =SimpleApplication= or =Application=20 - Implement setup functions that create all the scene objects using21 the inherited =assetManager= and call them by overriding the22 =simpleInitApp= method.23 - Create =ActionListeners= and add them to the =inputManager=24 inherited from =Application= to handle key-bindings.25 - Override =simpleUpdate= to implement game logic.26 - Running/Testing an Application involves creating a new JVM,27 running the App, and then closing everything down.30 - A more Clojureish way:31 - Use a map from keys->functions to specify key-bindings.32 - Use functions to create objects separately from any particular33 application.34 - Use a REPL -- this means that there's only ever one JVM, and35 Applications come and go.37 Since most development work using jMonkeyEngine is done in Java, jme338 supports "the Java way" quite well out of the box. To work "the39 clojure way", it necessary to wrap the JME3 elements that deal with40 the Application life-cycle with a REPL driven interface.42 The most important modifications are:44 - Separation of Object life-cycles with the Application life-cycle.45 - Functional interface to the underlying =Application= and46 =SimpleApplication= classes.48 ** Header49 #+name: header50 #+begin_src clojure :results silent51 (ns cortex.world52 "World Creation, abstraction over jme3's input system, and REPL53 driven exception handling"54 {:author "Robert McIntyre"}56 (:import com.aurellem.capture.IsoTimer)58 (:import com.jme3.math.Vector3f)59 (:import com.jme3.scene.Node)60 (:import com.jme3.system.AppSettings)61 (:import com.jme3.system.JmeSystem)62 (:import com.jme3.input.KeyInput)63 (:import com.jme3.input.controls.KeyTrigger)64 (:import com.jme3.input.controls.MouseButtonTrigger)65 (:import com.jme3.input.InputManager)66 (:import com.jme3.bullet.BulletAppState)67 (:import com.jme3.shadow.BasicShadowRenderer)68 (:import com.jme3.app.SimpleApplication)69 (:import com.jme3.input.controls.ActionListener)70 (:import com.jme3.renderer.queue.RenderQueue$ShadowMode)71 (:import org.lwjgl.input.Mouse)72 (:import com.aurellem.capture.AurellemSystemDelegate))74 #+end_src76 ** General Settings77 #+name: settings78 #+begin_src clojure79 (in-ns 'cortex.world)81 (def ^:dynamic *app-settings*82 "These settings control how the game is displayed on the screen for83 debugging purposes. Use binding forms to change this if desired.84 Full-screen mode does not work on some computers."85 (doto (AppSettings. true)86 (.setFullscreen false)87 (.setTitle "Aurellem.")88 ;; The "Send" AudioRenderer supports simulated hearing.89 (.setAudioRenderer "Send")))91 (defn asset-manager92 "returns a new, configured assetManager" []93 (JmeSystem/newAssetManager94 (.getResource95 (.getContextClassLoader (Thread/currentThread))96 "com/jme3/asset/Desktop.cfg")))97 #+end_src99 Normally, people just use the =AssetManager= inherited from100 =Application= whenever they extend that class. However,101 =AssetManagers= are useful on their own to create objects/ materials,102 independent from any particular application. =(asset-manager)= makes103 object creation less tightly bound to a particular Application104 Instance.106 ** Exception Protection107 #+name: exceptions108 #+begin_src clojure109 (in-ns 'cortex.world)111 (defmacro no-exceptions112 "Sweet relief like I never knew."113 [& forms]114 `(try ~@forms (catch Exception e# (.printStackTrace e#))))116 (defn thread-exception-removal117 "Exceptions thrown in the graphics rendering thread generally cause118 the entire REPL to crash! It is good to suppress them while trying119 things out to shorten the debug loop."120 []121 (.setUncaughtExceptionHandler122 (Thread/currentThread)123 (proxy [Thread$UncaughtExceptionHandler] []124 (uncaughtException125 [thread thrown]126 (println "uncaught-exception thrown in " thread)127 (println (.getMessage thrown))))))129 #+end_src131 Exceptions thrown in the LWJGL render thread, if not caught, will132 destroy the entire JVM process including the REPL and slow development133 to a crawl. It is better to try to continue on in the face of134 exceptions and keep the REPL alive as long as possible. Normally it135 is possible to just exit the faulty Application, fix the bug,136 reevaluate the appropriate forms, and be on your way, without137 restarting the JVM.139 ** Input140 #+name: input141 #+begin_src clojure142 (in-ns 'cortex.world)144 (defn static-integer?145 "does the field represent a static integer constant?"146 [#^java.lang.reflect.Field field]147 (and (java.lang.reflect.Modifier/isStatic (.getModifiers field))148 (integer? (.get field nil))))150 (defn integer-constants [class]151 (filter static-integer? (.getFields class)))153 (defn constant-map154 "Takes a class and creates a map of the static constant integer155 fields with their names. This helps with C wrappers where they have156 just defined a bunch of integer constants instead of enums"157 [class]158 (let [integer-fields (integer-constants class)]159 (into (sorted-map)160 (zipmap (map #(.get % nil) integer-fields)161 (map #(.getName %) integer-fields)))))162 (alter-var-root #'constant-map memoize)164 (defn all-keys165 "Uses reflection to generate a map of string names to jme3 trigger166 objects, which govern input from the keyboard and mouse"167 []168 (let [inputs (constant-map KeyInput)]169 (assoc170 (zipmap (map (fn [field]171 (.toLowerCase (.replaceAll field "_" "-"))) (vals inputs))172 (map (fn [val] (KeyTrigger. val)) (keys inputs)))173 ;;explicitly add mouse controls174 "mouse-left" (MouseButtonTrigger. 0)175 "mouse-middle" (MouseButtonTrigger. 2)176 "mouse-right" (MouseButtonTrigger. 1))))178 (defn initialize-inputs179 "Establish key-bindings for a particular virtual world."180 [game input-manager key-map]181 (doall182 (map (fn [[name trigger]]183 (.addMapping184 ^InputManager input-manager185 name (into-array (class trigger)186 [trigger]))) key-map))187 (doall188 (map (fn [name]189 (.addListener190 ^InputManager input-manager game191 (into-array String [name]))) (keys key-map))))193 #+end_src195 #+results: input196 : #'cortex.world/initialize-inputs198 These functions are for controlling the world through the keyboard and199 mouse.201 =constant-map= gets the numerical values for all the keys defined in202 the =KeyInput= class.204 #+begin_src clojure :exports both :results verbatim205 (take 5 (vals (cortex.world/constant-map KeyInput)))206 #+end_src208 #+results:209 : ("KEY_ESCAPE" "KEY_1" "KEY_2" "KEY_3" "KEY_4")211 =(all-keys)= converts the constant names like =KEY_J= to the more212 clojure-like =key-j=, and returns a map from these keys to213 jMonkeyEngine =KeyTrigger= objects, which jMonkeyEngine3 uses as it's214 abstraction over the physical keys. =all-keys= also adds the three215 mouse button controls to the map.217 #+begin_src clojure :exports both :results output218 (clojure.pprint/pprint219 (take 6 (cortex.world/all-keys)))220 #+end_src222 #+results:223 : (["key-n" #<KeyTrigger com.jme3.input.controls.KeyTrigger@2ad82934>]224 : ["key-apps" #<KeyTrigger com.jme3.input.controls.KeyTrigger@3c900d00>]225 : ["key-pgup" #<KeyTrigger com.jme3.input.controls.KeyTrigger@7d051157>]226 : ["key-f8" #<KeyTrigger com.jme3.input.controls.KeyTrigger@717f0d2d>]227 : ["key-o" #<KeyTrigger com.jme3.input.controls.KeyTrigger@4a555fcc>]228 : ["key-at" #<KeyTrigger com.jme3.input.controls.KeyTrigger@47d31aaa>])230 ** World Creation231 #+name: world232 #+begin_src clojure :results silent233 (in-ns 'cortex.world)235 (defn no-op236 "Takes any number of arguments and does nothing."237 [& _])239 (defn traverse240 "apply f to every non-node, deeply"241 [f node]242 (if (isa? (class node) Node)243 (dorun (map (partial traverse f) (.getChildren node)))244 (f node)))246 (defn world247 "the =world= function takes care of the details of initializing a248 SimpleApplication.250 ***** Arguments:252 - root-node : a com.jme3.scene.Node object which contains all of253 the objects that should be in the simulation.255 - key-map : a map from strings describing keys to functions that256 should be executed whenever that key is pressed.257 the functions should take a SimpleApplication object and a258 boolean value. The SimpleApplication is the current simulation259 that is running, and the boolean is true if the key is being260 pressed, and false if it is being released. As an example,262 {\"key-j\" (fn [game value] (if value (println \"key j pressed\")))}264 is a valid key-map which will cause the simulation to print a265 message whenever the 'j' key on the keyboard is pressed.267 - setup-fn : a function that takes a SimpleApplication object. It268 is called once when initializing the simulation. Use it to269 create things like lights, change the gravity, initialize debug270 nodes, etc.272 - update-fn : this function takes a SimpleApplication object and a273 float and is called every frame of the simulation. The float274 tells how many seconds is has been since the last frame was275 rendered, according to whatever clock jme is currently276 using. The default is to use IsoTimer which will result in this277 value always being the same.278 "279 [root-node key-map setup-fn update-fn]280 (let [physics-manager (BulletAppState.)]281 (JmeSystem/setSystemDelegate (AurellemSystemDelegate.))282 (doto283 (proxy [SimpleApplication ActionListener] []284 (simpleInitApp285 []286 (no-exceptions287 ;; allow AI entities as much time as they need to think.288 (.setTimer this (IsoTimer. 60))289 (.setFrustumFar (.getCamera this) 300)290 ;; Create default key-map.291 (initialize-inputs this (.getInputManager this) (all-keys))292 ;; Don't take control of the mouse293 (org.lwjgl.input.Mouse/setGrabbed false)294 ;; add all objects to the world295 (.attachChild (.getRootNode this) root-node)296 ;; enable physics297 ;; add a physics manager298 (.attach (.getStateManager this) physics-manager)299 (.setGravity (.getPhysicsSpace physics-manager)300 (Vector3f. 0 -9.81 0))301 ;; go through every object and add it to the physics302 ;; manager if relevant.303 ;;(traverse (fn [geom]304 ;; (dorun305 ;; (for [n (range (.getNumControls geom))]306 ;; (do307 ;; (cortex.util/println-repl308 ;; "adding " (.getControl geom n))309 ;; (.add (.getPhysicsSpace physics-manager)310 ;; (.getControl geom n))))))311 ;; (.getRootNode this))312 ;; call the supplied setup-fn313 ;; simpler !314 (.addAll (.getPhysicsSpace physics-manager) root-node)315 (if setup-fn316 (setup-fn this))))317 (simpleUpdate318 [tpf]319 (no-exceptions320 (update-fn this tpf)))321 (onAction322 [binding value tpf]323 ;; whenever a key is pressed, call the function returned324 ;; from key-map.325 (no-exceptions326 (if-let [react (key-map binding)]327 (react this value)))))328 ;; don't show a menu to change options.329 (.setShowSettings false)330 ;; continue running simulation even if the window has lost331 ;; focus.332 (.setPauseOnLostFocus false)333 (.setSettings *app-settings*))))335 #+end_src338 =(world)= is the most important function here. It presents a more339 functional interface to the Application life-cycle, and all its340 arguments except =root-node= are plain immutable clojure data341 structures. This makes it easier to extend functionally by composing342 multiple functions together, and to add more keyboard-driven actions343 by combining clojure maps.347 * COMMENT code generation348 #+begin_src clojure :tangle ../src/cortex/world.clj :noweb yes349 <<header>>350 <<settings>>351 <<exceptions>>352 <<input>>353 <<world>>354 #+end_src