diff --git a/src/engine.clj b/src/engine.clj index 93c7763..cc3bbb6 100644 --- a/src/engine.clj +++ b/src/engine.clj @@ -4,11 +4,32 @@ [rl :as rl] [watch :as w])) +(defprotocol IBuffered + (cells [this]) + (snapshot! [this]) + (restore! [this])) + +(deftype IntGrid [^ints cells ^ints backup] + IBuffered + (cells [_] cells) + (snapshot! [_] (System/arraycopy cells 0 backup 0 (alength cells))) + (restore! [_] (System/arraycopy backup 0 cells 0 (alength cells)))) + +(deftype RawIntGrid [^ints cells] + IBuffered + (cells [_] cells) + (snapshot! [_]) + (restore! [_])) + (defonce last-error (atom nil)) (defonce game-state (atom nil)) (defonce game-config (atom nil)) (defonce texture-cache (atom {})) ;; (reset! texture-cache {}) +(defonce buffered-objs (atom [])) + +;; TODO: Setup release flags and get this to work with make-int-grid +;; (def debug? (not= "false" (System/getProperty "siam.debug"))) (defn load-texture-once [id path] (or (@texture-cache path) @@ -16,11 +37,10 @@ (swap! texture-cache assoc path t) t))) -(defn load-texture-once [id path] - (or (@texture-cache path) - (let [t (assoc (rl/load-texture path) :name id)] - (swap! texture-cache assoc path t) - t))) +(defn make-int-grid [n empty-val] + (let [g (->IntGrid (int-array n empty-val) (int-array n empty-val))] + (swap! buffered-objs conj g) + g)) (defn report-exception! "Stash the exception and print a marker line. Emacs watches the REPL output @@ -59,16 +79,22 @@ (report-exception! t))) (while (not (rl/window-should-close?)) (if @last-error - (Thread/sleep 50) + (do (rl/with-drawing!) + (Thread/sleep 50)) (let [config (:config @game-config)] + (try + (doseq [buf @buffered-objs] (snapshot! buf)) + (swap! game-state #(update config %)) + (catch Throwable t + (doseq [buf @buffered-objs] + (restore! buf)) + (report-exception! t))) (rl/with-drawing! (try - (swap! game-state #(update config %)) (draw config @game-state) (w/watch! (watch-fn config @game-state)) (catch Throwable t - (report-exception! t) - (w/watch! (merge (watch-fn config @game-state) {:error t})))))))) + (report-exception! t))))))) (try (when unload (doseq [[_ tex] @texture-cache] @@ -77,6 +103,7 @@ (catch Throwable t (report-exception! t))) (rl/close-window!) + (reset! buffered-objs []) (reset! texture-cache {}) (reset! last-error nil) (reset! game-state nil)