Mercurial > cortex
view org/world.org @ 65:4b5f00110d8c
removed pokemon.lpsolve dependency
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Wed, 07 Dec 2011 10:29:35 -0600 |
parents | 00d0e1639d4b |
children | 1381a6ebd08b |
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 #+srcname: header50 #+begin_src clojure :results silent51 (ns cortex.world52 "World Creation, abstracion over jme3's input system, and REPL53 driven exception handling"54 {:author "Robert McIntyre"}56 (:use (clojure.contrib (def :only (defvar))))57 (:use [clojure.contrib [str-utils :only [re-gsub]]])59 (:import com.aurellem.capture.IsoTimer)61 (:import com.jme3.math.Vector3f)62 (:import com.jme3.scene.Node)63 (:import com.jme3.system.AppSettings)64 (:import com.jme3.system.JmeSystem)65 (:import com.jme3.input.KeyInput)66 (:import com.jme3.input.controls.KeyTrigger)67 (:import com.jme3.input.controls.MouseButtonTrigger)68 (:import com.jme3.input.InputManager)69 (:import com.jme3.bullet.BulletAppState)70 (:import com.jme3.shadow.BasicShadowRenderer)71 (:import com.jme3.app.SimpleApplication)72 (:import com.jme3.input.controls.ActionListener)73 (:import com.jme3.renderer.queue.RenderQueue$ShadowMode)74 (:import org.lwjgl.input.Mouse))75 #+end_src77 ** General Settings78 #+srcname: settings79 #+begin_src clojure80 (in-ns 'cortex.world)82 (defvar *app-settings*83 (doto (AppSettings. true)84 (.setFullscreen false)85 (.setTitle "Aurellem.")86 ;; The "Send" AudioRenderer supports sumulated hearing.87 (.setAudioRenderer "Send"))88 "These settings control how the game is displayed on the screen for89 debugging purposes. Use binding forms to change this if desired.90 Full-screen mode does not work on some computers.")92 (defn asset-manager93 "returns a new, configured assetManager" []94 (JmeSystem/newAssetManager95 (.getResource96 (.getContextClassLoader (Thread/currentThread))97 "com/jme3/asset/Desktop.cfg")))98 #+end_src100 Normally, people just use the =AssetManager= inherited from101 =Application= whenever they extend that class. However,102 =AssetManagers= are useful on their own to create objects/ materials,103 independent from any particular application. =(asset-manager)= makes104 object creation less tightly bound to a particular Application105 Instance.107 ** Exception Protection108 #+srcname: exceptions109 #+begin_src clojure110 (in-ns 'cortex.world)112 (defmacro no-exceptions113 "Sweet relief like I never knew."114 [& forms]115 `(try ~@forms (catch Exception e# (.printStackTrace e#))))117 (defn thread-exception-removal118 "Exceptions thrown in the graphics rendering thread generally cause119 the entire REPL to crash! It is good to suppress them while trying120 things out to shorten the debug loop."121 []122 (.setUncaughtExceptionHandler123 (Thread/currentThread)124 (proxy [Thread$UncaughtExceptionHandler] []125 (uncaughtException126 [thread thrown]127 (println "uncaught-exception thrown in " thread)128 (println (.getMessage thrown))))))130 #+end_src132 Exceptions thrown in the LWJGL render thread, if not caught, will133 destroy the entire JVM process including the REPL and slow development134 to a crawl. It is better to try to continue on in the face of135 exceptions and keep the REPL alive as long as possible. Normally it136 is possible to just exit the faulty Application, fix the bug,137 reevaluate the appropriate forms, and be on your way, without138 restarting the JVM.140 ** Input141 #+srcname: input142 #+begin_src clojure143 (in-ns 'cortex.world)145 (defn static-integer?146 "does the field represent a static integer constant?"147 [#^java.lang.reflect.Field field]148 (and (java.lang.reflect.Modifier/isStatic (.getModifiers field))149 (integer? (.get field nil))))151 (defn integer-constants [class]152 (filter static-integer? (.getFields class)))154 (defn-memo constant-map155 "Takes a class and creates a map of the static constant integer156 fields with their names. This helps with C wrappers where they have157 just defined a bunch of integer constants instead of enums"158 [class]159 (let [integer-fields (integer-constants class)]160 (into (sorted-map)161 (zipmap (map #(.get % nil) integer-fields)162 (map #(.getName %) integer-fields)))))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 (re-gsub #"_" "-" 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 These functions are for controlling the world through the keyboard and196 mouse.198 =constant-map= gets the numerical values for all the keys defined in199 the =KeyInput= class.201 #+begin_src clojure :exports both :results verbatim202 (take 5 (vals (cortex.world/constant-map KeyInput)))203 #+end_src205 #+results:206 : ("KEY_ESCAPE" "KEY_1" "KEY_2" "KEY_3" "KEY_4")208 =(all-keys)= converts the constant names like =KEY_J= to the more209 clojure-like =key-j=, and returns a map from these keys to210 jMonkeyEngine =KeyTrigger= objects, which jMonkeyEngine3 uses as it's211 abstraction over the physical keys. =all-keys= also adds the three212 mouse button controls to the map.214 #+begin_src clojure :exports both :results output215 (require 'clojure.contrib.pprint)216 (clojure.contrib.pprint/pprint217 (take 6 (cortex.world/all-keys)))218 #+end_src220 #+results:221 : (["key-n" #<KeyTrigger com.jme3.input.controls.KeyTrigger@9f9fec0>]222 : ["key-apps" #<KeyTrigger com.jme3.input.controls.KeyTrigger@28edbe7f>]223 : ["key-pgup" #<KeyTrigger com.jme3.input.controls.KeyTrigger@647fd33a>]224 : ["key-f8" #<KeyTrigger com.jme3.input.controls.KeyTrigger@24f97188>]225 : ["key-o" #<KeyTrigger com.jme3.input.controls.KeyTrigger@685c53ff>]226 : ["key-at" #<KeyTrigger com.jme3.input.controls.KeyTrigger@4c3e2e5f>])228 ** World Creation229 #+srcname: world230 #+begin_src clojure :results silent231 (in-ns 'cortex.world)233 (defn no-op234 "Takes any number of arguments and does nothing."235 [& _])237 (defn traverse238 "apply f to every non-node, deeply"239 [f node]240 (if (isa? (class node) Node)241 (dorun (map (partial traverse f) (.getChildren node)))242 (f node)))244 (defn world245 "the =world= function takes care of the details of initializing a246 SimpleApplication.248 ***** Arguments:250 - root-node : a com.jme3.scene.Node object which contains all of251 the objects that should be in the simulation.253 - key-map : a map from strings describing keys to functions that254 should be executed whenever that key is pressed.255 the functions should take a SimpleApplication object and a256 boolean value. The SimpleApplication is the current simulation257 that is running, and the boolean is true if the key is being258 pressed, and false if it is being released. As an example,260 {\"key-j\" (fn [game value] (if value (println \"key j pressed\")))}262 is a valid key-map which will cause the simulation to print a263 message whenever the 'j' key on the keyboard is pressed.265 - setup-fn : a function that takes a SimpleApplication object. It266 is called once when initializing the simulation. Use it to267 create things like lights, change the gravity, initialize debug268 nodes, etc.270 - update-fn : this function takes a SimpleApplication object and a271 float and is called every frame of the simulation. The float272 tells how many seconds is has been since the last frame was273 rendered, according to whatever clock jme is currently274 using. The default is to use IsoTimer which will result in this275 value always being the same.276 "277 [root-node key-map setup-fn update-fn]278 (let [physics-manager (BulletAppState.)]279 (doto280 (proxy [SimpleApplication ActionListener] []281 (simpleInitApp282 []283 (no-exceptions284 ;; allow AI entities as much time as they need to think.285 (.setTimer this (IsoTimer. 60))286 (.setFrustumFar (.getCamera this) 300)287 ;; Create default key-map.288 (initialize-inputs this (.getInputManager this) (all-keys))289 ;; Don't take control of the mouse290 (org.lwjgl.input.Mouse/setGrabbed false)291 ;; add all objects to the world292 (.attachChild (.getRootNode this) root-node)293 ;; enable physics294 ;; add a physics manager295 (.attach (.getStateManager this) physics-manager)296 (.setGravity (.getPhysicsSpace physics-manager)297 (Vector3f. 0 -9.81 0))298 ;; go through every object and add it to the physics299 ;; manager if relevant.300 ;;(traverse (fn [geom]301 ;; (dorun302 ;; (for [n (range (.getNumControls geom))]303 ;; (do304 ;; (cortex.util/println-repl305 ;; "adding " (.getControl geom n))306 ;; (.add (.getPhysicsSpace physics-manager)307 ;; (.getControl geom n))))))308 ;; (.getRootNode this))309 ;; call the supplied setup-fn310 ;; simpler !311 (.addAll (.getPhysicsSpace physics-manager) root-node)312 (if setup-fn313 (setup-fn this))))314 (simpleUpdate315 [tpf]316 (no-exceptions317 (update-fn this tpf)))318 (onAction319 [binding value tpf]320 ;; whenever a key is pressed, call the function returned321 ;; from key-map.322 (no-exceptions323 (if-let [react (key-map binding)]324 (react this value)))))325 ;; don't show a menu to change options.326 (.setShowSettings false)327 ;; continue running simulation even if the window has lost328 ;; focus.329 (.setPauseOnLostFocus false)330 (.setSettings *app-settings*))))331 #+end_src334 =(world)= is the most important function here. It presents a more335 functional interface to the Application life-cycle, and all its336 arguments except =root-node= are plain immutable clojure data337 structures. This makes it easier to extend functionally by composing338 multiple functions together, and to add more keyboard-driven actions339 by combining clojure maps.343 * COMMENT code generation344 #+begin_src clojure :tangle ../src/cortex/world.clj :noweb yes345 <<header>>346 <<settings>>347 <<exceptions>>348 <<input>>349 <<world>>350 #+end_src