view org/world.org @ 548:0b891e0dd809

version 0.2 of thesis complete.
author Robert McIntyre <rlm@mit.edu>
date Thu, 01 May 2014 23:41:41 -0400
parents 939bcc5950b2
children
line wrap: on
line source
1 #+title: A Virtual World for Sensate Creatures
2 #+author: Robert McIntyre
3 #+email: rlm@mit.edu
4 #+description: Creating a Virtual World for AI constructs using clojure and JME3
5 #+keywords: JME3, clojure, virtual world, exception handling
6 #+SETUPFILE: ../../aurellem/org/setup.org
7 #+INCLUDE: ../../aurellem/org/level-0.org
8 #+BABEL: :mkdirp yes :noweb yes :exports both
10 * The World
12 There's no point in having senses if there's nothing to experience. In
13 this section I make some tools with which to build virtual worlds for
14 my characters to inhabit. If you look at the tutorials at [[http://www.jmonkeyengine.org/wiki/doku.php/jme3:beginner][the jme3
15 website]], you will see a pattern in how virtual worlds are normally
16 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 using
21 the inherited =assetManager= and call them by overriding the
22 =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 particular
33 application.
34 - Use a REPL -- this means that there's only ever one JVM, and
35 Applications come and go.
37 Since most development work using jMonkeyEngine is done in Java, jme3
38 supports "the Java way" quite well out of the box. To work "the
39 clojure way", it necessary to wrap the JME3 elements that deal with
40 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= and
46 =SimpleApplication= classes.
48 ** Header
49 #+name: header
50 #+begin_src clojure :results silent
51 (ns cortex.world
52 "World Creation, abstraction over jme3's input system, and REPL
53 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_src
76 ** General Settings
77 #+name: settings
78 #+begin_src clojure
79 (in-ns 'cortex.world)
81 (def ^:dynamic *app-settings*
82 "These settings control how the game is displayed on the screen for
83 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-manager
92 "returns a new, configured assetManager" []
93 (JmeSystem/newAssetManager
94 (.getResource
95 (.getContextClassLoader (Thread/currentThread))
96 "com/jme3/asset/Desktop.cfg")))
97 #+end_src
99 Normally, people just use the =AssetManager= inherited from
100 =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)= makes
103 object creation less tightly bound to a particular Application
104 Instance.
106 ** Exception Protection
107 #+name: exceptions
108 #+begin_src clojure
109 (in-ns 'cortex.world)
111 (defmacro no-exceptions
112 "Sweet relief like I never knew."
113 [& forms]
114 `(try ~@forms (catch Exception e# (.printStackTrace e#))))
116 (defn thread-exception-removal
117 "Exceptions thrown in the graphics rendering thread generally cause
118 the entire REPL to crash! It is good to suppress them while trying
119 things out to shorten the debug loop."
120 []
121 (.setUncaughtExceptionHandler
122 (Thread/currentThread)
123 (proxy [Thread$UncaughtExceptionHandler] []
124 (uncaughtException
125 [thread thrown]
126 (println "uncaught-exception thrown in " thread)
127 (println (.getMessage thrown))))))
129 #+end_src
131 Exceptions thrown in the LWJGL render thread, if not caught, will
132 destroy the entire JVM process including the REPL and slow development
133 to a crawl. It is better to try to continue on in the face of
134 exceptions and keep the REPL alive as long as possible. Normally it
135 is possible to just exit the faulty Application, fix the bug,
136 reevaluate the appropriate forms, and be on your way, without
137 restarting the JVM.
139 ** Input
140 #+name: input
141 #+begin_src clojure
142 (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-map
154 "Takes a class and creates a map of the static constant integer
155 fields with their names. This helps with C wrappers where they have
156 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-keys
165 "Uses reflection to generate a map of string names to jme3 trigger
166 objects, which govern input from the keyboard and mouse"
167 []
168 (let [inputs (constant-map KeyInput)]
169 (assoc
170 (zipmap (map (fn [field]
171 (.toLowerCase (.replaceAll field "_" "-"))) (vals inputs))
172 (map (fn [val] (KeyTrigger. val)) (keys inputs)))
173 ;;explicitly add mouse controls
174 "mouse-left" (MouseButtonTrigger. 0)
175 "mouse-middle" (MouseButtonTrigger. 2)
176 "mouse-right" (MouseButtonTrigger. 1))))
178 (defn initialize-inputs
179 "Establish key-bindings for a particular virtual world."
180 [game input-manager key-map]
181 (doall
182 (map (fn [[name trigger]]
183 (.addMapping
184 ^InputManager input-manager
185 name (into-array (class trigger)
186 [trigger]))) key-map))
187 (doall
188 (map (fn [name]
189 (.addListener
190 ^InputManager input-manager game
191 (into-array String [name]))) (keys key-map))))
193 #+end_src
195 These functions are for controlling the world through the keyboard and
196 mouse.
198 =constant-map= gets the numerical values for all the keys defined in
199 the =KeyInput= class.
201 #+begin_src clojure :exports both :results verbatim
202 (take 5 (vals (cortex.world/constant-map KeyInput)))
203 #+end_src
205 #+results:
206 : ("KEY_ESCAPE" "KEY_1" "KEY_2" "KEY_3" "KEY_4")
208 =(all-keys)= converts the constant names like =KEY_J= to the more
209 clojure-like =key-j=, and returns a map from these keys to
210 jMonkeyEngine =KeyTrigger= objects, which jMonkeyEngine3 uses as it's
211 abstraction over the physical keys. =all-keys= also adds the three
212 mouse button controls to the map.
214 #+begin_src clojure :exports both :results output
215 (clojure.pprint/pprint
216 (take 6 (cortex.world/all-keys)))
217 #+end_src
219 #+results:
220 : (["key-n" #<KeyTrigger com.jme3.input.controls.KeyTrigger@2ad82934>]
221 : ["key-apps" #<KeyTrigger com.jme3.input.controls.KeyTrigger@3c900d00>]
222 : ["key-pgup" #<KeyTrigger com.jme3.input.controls.KeyTrigger@7d051157>]
223 : ["key-f8" #<KeyTrigger com.jme3.input.controls.KeyTrigger@717f0d2d>]
224 : ["key-o" #<KeyTrigger com.jme3.input.controls.KeyTrigger@4a555fcc>]
225 : ["key-at" #<KeyTrigger com.jme3.input.controls.KeyTrigger@47d31aaa>])
227 ** World Creation
228 #+name: world
229 #+begin_src clojure :results silent
230 (in-ns 'cortex.world)
232 (defn no-op
233 "Takes any number of arguments and does nothing."
234 [& _])
236 (defn traverse
237 "apply f to every non-node, deeply"
238 [f node]
239 (if (isa? (class node) Node)
240 (dorun (map (partial traverse f) (.getChildren node)))
241 (f node)))
243 (defn world
244 "the =world= function takes care of the details of initializing a
245 SimpleApplication.
247 ,***** Arguments:
249 - root-node : a com.jme3.scene.Node object which contains all of
250 the objects that should be in the simulation.
252 - key-map : a map from strings describing keys to functions that
253 should be executed whenever that key is pressed.
254 the functions should take a SimpleApplication object and a
255 boolean value. The SimpleApplication is the current simulation
256 that is running, and the boolean is true if the key is being
257 pressed, and false if it is being released. As an example,
259 {\"key-j\" (fn [game value] (if value (println \"key j pressed\")))}
261 is a valid key-map which will cause the simulation to print a
262 message whenever the 'j' key on the keyboard is pressed.
264 - setup-fn : a function that takes a SimpleApplication object. It
265 is called once when initializing the simulation. Use it to
266 create things like lights, change the gravity, initialize debug
267 nodes, etc.
269 - update-fn : this function takes a SimpleApplication object and a
270 float and is called every frame of the simulation. The float
271 tells how many seconds is has been since the last frame was
272 rendered, according to whatever clock jme is currently
273 using. The default is to use IsoTimer which will result in this
274 value always being the same.
275 "
276 [root-node key-map setup-fn update-fn]
277 (let [physics-manager (BulletAppState.)]
278 (JmeSystem/setSystemDelegate (AurellemSystemDelegate.))
279 (doto
280 (proxy [SimpleApplication ActionListener] []
281 (simpleInitApp
282 []
283 (no-exceptions
284 ;; 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 mouse
290 (org.lwjgl.input.Mouse/setGrabbed false)
291 ;; add all objects to the world
292 (.attachChild (.getRootNode this) root-node)
293 ;; enable physics
294 ;; add a physics manager
295 (.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 physics
299 ;; manager if relevant.
300 ;;(traverse (fn [geom]
301 ;; (dorun
302 ;; (for [n (range (.getNumControls geom))]
303 ;; (do
304 ;; (cortex.util/println-repl
305 ;; "adding " (.getControl geom n))
306 ;; (.add (.getPhysicsSpace physics-manager)
307 ;; (.getControl geom n))))))
308 ;; (.getRootNode this))
309 ;; call the supplied setup-fn
310 ;; simpler !
311 (.addAll (.getPhysicsSpace physics-manager) root-node)
312 (if setup-fn
313 (setup-fn this))))
314 (simpleUpdate
315 [tpf]
316 (no-exceptions
317 (update-fn this tpf)))
318 (onAction
319 [binding value tpf]
320 ;; whenever a key is pressed, call the function returned
321 ;; from key-map.
322 (no-exceptions
323 (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 lost
328 ;; focus.
329 (.setPauseOnLostFocus false)
330 (.setSettings *app-settings*))))
332 #+end_src
335 =(world)= is the most important function here. It presents a more
336 functional interface to the Application life-cycle, and all its
337 arguments except =root-node= are plain immutable clojure data
338 structures. This makes it easier to extend functionally by composing
339 multiple functions together, and to add more keyboard-driven actions
340 by combining clojure maps.
344 * COMMENT code generation
345 #+begin_src clojure :tangle ../src/cortex/world.clj :noweb yes
346 <<header>>
347 <<settings>>
348 <<exceptions>>
349 <<input>>
350 <<world>>
351 #+end_src