Clojure2D/clojure2d

get-state returns nil

rrrnld opened this issue · 3 comments

Hi! I have the following sketch:

(ns heyarne.line-us.doodles.one
  (:require [clojure2d.core :as c2d]
            [thi.ng.geom.line :as l]))

(defn setup [canvas]
  {:lines []})

(defn draw-state [canvas state]
  (c2d/set-color canvas :white)
  (c2d/rect canvas 0 0 (:w canvas) (:h canvas)))

(defn update-state [canvas state]
  state)

(defn -main [& args]
  (let [canvas (c2d/canvas 400 400)]
    (c2d/show-window
     {:window-name "Doodle One"
      :canvas canvas
      :draw-state (setup canvas)
      :draw-fn (fn [canvas _window _frame state]
                 (draw-state canvas state)
                 (update-state canvas state))})))

(def sketch (-main))

When I'm calling get-state on sketch it returns nil instead of {:lines []}. Am I misunderstanding something?

PS: Thanks for the library, it's super enjoyable!

Thanks for using library! Glad you enjoy it.

Regarding your question. It's common misunderstanding about states in Clojure2d.
There are two of them actually.

The first one is a state passed through draw-fn and initialized by draw-state. Before starting the draw loop draw-state function is called and this is passed to the first invocation of draw-fn. Loop is started and what is returned by draw-fn is passed to the next call. You have no direct access from outside to this state.

The second one is global state attached to the window and can be set or accessed by calling set-state and get-state explicitly. Calls are synchronized via atom and initialized by setting state key during window creation. This state is used to interact with events.

So. If you want to access drawing state you have explicitly call set-state in draw. Then you have access to it from REPL for example.

Here is the example where I use global state to interact with user (via events): https://github.com/Clojure2D/clojure2d-examples/blob/master/src/ex44_diatoms.clj

Thanks for the quick reply! The example helped a lot.