first step: Ludus speaks turtle graphics, not p5 calls

This commit is contained in:
Scott Richmond 2024-07-21 19:22:42 -04:00
parent df85be3c1e
commit 121446c5c4
6 changed files with 141 additions and 153 deletions

View File

@ -3,23 +3,7 @@
& the goal is to output any global state held in Ludus & the goal is to output any global state held in Ludus
& this does not have base loaded into it, only prelude: must be pure Ludus & this does not have base loaded into it, only prelude: must be pure Ludus
if turtle_state () :visible? then render_turtle! () else nil print! ("running postlude")
reset_turtle! () store! (turtle_state, turtle_init)
store! (turtle_commands, [])
& let console_msgs = flush! ()
let (r, g, b, a) = unbox (bgcolor)
store! (bgcolor, colors :black)
let draw_calls = unbox (p5_calls)
store! (p5_calls, [])
#{
& :result result is provided elsewhere
& :errors [] & if we get here there are no errors
& :console console_msgs
:draw concat (
[(:background, r, g, b, a), (:stroke, 255, 255, 255, 255)]
draw_calls)
}

View File

@ -17,7 +17,6 @@ fn mod
fn neg? fn neg?
fn print! fn print!
fn some? fn some?
fn state/call
fn store! fn store!
fn string fn string
fn turn/rad fn turn/rad
@ -968,6 +967,15 @@ fn dist {
((x, y)) -> dist (x, y) ((x, y)) -> dist (x, y)
} }
fn heading/vector {
"Takes a turtle heading, and returns a unit vector of that heading."
(heading) -> {
& 0 is 90º/0.25T, 0.25 is 180º/0.5T, 0.5 is 270º/0.75T, 0.75 is 0º/0T
let a = add (neg (heading), 0.25)
(cos (a), sin (a))
}
}
&&& more number functions &&& more number functions
fn random { fn random {
"Returns a random something. With zero arguments, returns a random number between 0 (inclusive) and 1 (exclusive). With one argument, returns a random number between 0 and n. With two arguments, returns a random number between m and n. Alternately, given a collection (list, dict, set), it returns a random member of that collection." "Returns a random something. With zero arguments, returns a random number between 0 (inclusive) and 1 (exclusive). With one argument, returns a random number between 0 and n. With two arguments, returns a random number between m and n. Alternately, given a collection (list, dict, set), it returns a random member of that collection."
@ -1088,7 +1096,7 @@ let turtle_init = #{
:position (0, 0) & let's call this the origin for now :position (0, 0) & let's call this the origin for now
:heading 0 & this is straight up :heading 0 & this is straight up
:pendown? true :pendown? true
:pencolor colors :white :pencolor :white
:penwidth 1 :penwidth 1
:visible? true :visible? true
} }
@ -1096,102 +1104,91 @@ let turtle_init = #{
& turtle states: refs that get modified by calls & turtle states: refs that get modified by calls
& turtle_commands is a list of commands, expressed as tuples & turtle_commands is a list of commands, expressed as tuples
box turtle_commands = [] box turtle_commands = []
box turtle_state = turtle_init
& and a list of turtle states & fn reset_turtle! {
box turtle_states = [turtle_init] & "Resets the turtle to its original state."
& () -> store! (turtle_states, [turtle_init])
fn reset_turtle! { & }
"Resets the turtle to its original state."
() -> store! (turtle_states, [turtle_init])
}
& and a list of calls to p5--at least for now
box p5_calls = []
& ...and finally, a background color
& we need to store this separately because, while it can be updated later,
& it must be the first call to p5.
box bgcolor = colors :black
fn add_call! (call) -> update! (p5_calls, append! (_, call))
fn add_command! (command) -> { fn add_command! (command) -> {
update! (turtle_commands, append! (_, command)) update! (turtle_commands, append! (_, command))
let prev = do turtle_states > unbox > last let prev = unbox (turtle_state)
let curr = apply_command (prev, command) let curr = apply_command (prev, command)
update! (turtle_states, append! (_, curr)) store! (turtle_state, curr)
let call = state/call () & let call = state/call ()
if call then { add_call! (call); :ok } else :ok & if call then { add_call! (call); :ok } else :ok
:ok
} }
fn make_line ((x1, y1), (x2, y2)) -> (:line, x1, y1, x2, y2) & fn make_line ((x1, y1), (x2, y2)) -> (:line, x1, y1, x2, y2)
let turtle_radius = 20 & let turtle_radius = 20
let turtle_angle = 0.385 & let turtle_angle = 0.385
let turtle_color = (255, 255, 255, 150) & let turtle_color = (255, 255, 255, 150)
fn render_turtle! () -> { & fn render_turtle! () -> {
let state = do turtle_states > unbox > last & let state = do turtle_states > unbox > last
if state :visible? & if state :visible?
then { & then {
let (r, g, b, a) = turtle_color & let (r, g, b, a) = turtle_color
add_call! ((:fill, r, g, b, a)) & add_call! ((:fill, r, g, b, a))
let #{heading & let #{heading
:pencolor (pen_r, pen_g, pen_b, pen_a) & :pencolor (pen_r, pen_g, pen_b, pen_a)
:position (x, y) & :position (x, y)
pendown? & pendown?
...} = state & ...} = state
let origin = mult ((0, 1), turtle_radius) & let origin = mult ((0, 1), turtle_radius)
let (x1, y1) = origin & let (x1, y1) = origin
let (x2, y2) = rotate (origin, turtle_angle) & let (x2, y2) = rotate (origin, turtle_angle)
let (x3, y3) = rotate (origin, neg (turtle_angle)) & let (x3, y3) = rotate (origin, neg (turtle_angle))
add_call! ((:push)) & add_call! ((:push))
add_call! ((:translate, x, y)) & add_call! ((:translate, x, y))
add_call! ((:rotate, turn/rad (heading))) & add_call! ((:rotate, turn/rad (heading)))
add_call! ((:noStroke)) & add_call! ((:noStroke))
add_call! ((:beginShape)) & add_call! ((:beginShape))
add_call! ((:vertex, x1, y1)) & add_call! ((:vertex, x1, y1))
add_call! ((:vertex, x2, y2)) & add_call! ((:vertex, x2, y2))
add_call! ((:vertex, x3, y3)) & add_call! ((:vertex, x3, y3))
add_call! ((:endShape)) & add_call! ((:endShape))
& there's a happy bug here: the stroke will be the same width as the pen width. Keep this for now. Consider also showing the pen colour here? & & there's a happy bug here: the stroke will be the same width as the pen width. Keep this for now. Consider also showing the pen colour here?
add_call! ((:stroke, pen_r, pen_g, pen_b, pen_a)) & add_call! ((:stroke, pen_r, pen_g, pen_b, pen_a))
if pendown? then add_call! ((:line, 0, 0, x1, y1)) else nil & if pendown? then add_call! ((:line, 0, 0, x1, y1)) else nil
add_call! ((:pop)) & add_call! ((:pop))
:ok & :ok
} & }
else :ok & else :ok
} & }
fn state/call () -> { & fn state/call () -> {
let cmd = do turtle_commands > unbox > last > first & let cmd = do turtle_commands > unbox > last > first
let states = unbox (turtle_states) & let states = unbox (turtle_states)
let curr = last (states) & let curr = last (states)
let prev = at (states, sub (count (states), 2)) & let prev = at (states, sub (count (states), 2))
match cmd with { & match cmd with {
:forward -> if curr :pendown? & :forward -> if curr :pendown?
then make_line (prev :position, curr :position) & then make_line (prev :position, curr :position)
else nil & else nil
:back -> if curr :pendown? & :back -> if curr :pendown?
then make_line (prev :position, curr :position) & then make_line (prev :position, curr :position)
else nil & else nil
:home -> if curr :pendown? & :home -> if curr :pendown?
then make_line (prev :position, curr :position) & then make_line (prev :position, curr :position)
else nil & else nil
:goto -> if curr :pendown? & :goto -> if curr :pendown?
then make_line (prev :position, curr :position) & then make_line (prev :position, curr :position)
else nil & else nil
:penwidth -> (:strokeWeight, curr :penwidth) & :penwidth -> (:strokeWeight, curr :penwidth)
:pencolor -> { & :pencolor -> {
let (r, g, b, a) = curr :pencolor & let (r, g, b, a) = curr :pencolor
(:stroke, r, g, b, a) & (:stroke, r, g, b, a)
} & }
:clear -> (:background, 0, 0, 0, 255) & :clear -> (:background, 0, 0, 0, 255)
_ -> nil & _ -> nil
} & }
} & }
fn forward! { fn forward! {
"Moves the turtle forward by a number of steps. Alias: fd!" "Moves the turtle forward by a number of steps. Alias: fd!"
@ -1237,6 +1234,7 @@ let pd! = pendown!
fn pencolor! { fn pencolor! {
"Changes the turtle's pen color. Takes a single grayscale value, an rgb tuple, or an rgba tuple. Alias: pc!" "Changes the turtle's pen color. Takes a single grayscale value, an rgb tuple, or an rgba tuple. Alias: pc!"
(color as :keyword) -> add_command! ((:pencolor, color))
(gray as :number) -> add_command! ((:pencolor, (gray, gray, gray, 255))) (gray as :number) -> add_command! ((:pencolor, (gray, gray, gray, 255)))
((r as :number, g as :number, b as :number)) -> add_command! ((:pencolor, (r, g, b, 255))) ((r as :number, g as :number, b as :number)) -> add_command! ((:pencolor, (r, g, b, 255)))
((r as :number, g as :number, b as :number, a as :number)) -> add_command! ((:pencolor, (r, g, b, a))) ((r as :number, g as :number, b as :number, a as :number)) -> add_command! ((:pencolor, (r, g, b, a)))
@ -1253,9 +1251,10 @@ let pw! = penwidth!
fn background! { fn background! {
"Sets the background color behind the turtle and path. Alias: bg!" "Sets the background color behind the turtle and path. Alias: bg!"
(gray as :number) -> store! (bgcolor, (gray, gray, gray, 255)) (color as :keyword) -> add_command! ((:background, :color))
((r as :number, g as :number, b as :number)) -> store! (bgcolor, (r, g, b, 255)) (gray as :number) -> add_command! ((:background, gray, gray, gray, 255))
((r as :number, g as :number, b as :number, a as :number)) -> store! (bgcolor, (r, g, b, a)) ((r as :number, g as :number, b as :number)) -> add_command! ((:background, r, g, b, 255))
((r as :number, g as :number, b as :number, a as :number)) -> add_command! ((:background, r, g, b, a))
} }
let bg! = background! let bg! = background!
@ -1291,12 +1290,18 @@ fn hideturtle! {
() -> add_command! ((:hide)) () -> add_command! ((:hide))
} }
fn heading/vector { fn loadstate! {
"Takes a turtle heading, and returns a unit vector of that heading." "Sets the turtle state to a previously saved state. Returns the state."
(heading) -> { (state) -> {
& 0 is 90º/0.25T, 0.25 is 180º/0.5T, 0.5 is 270º/0.75T, 0.75 is 0º/0T let #{:position (x, y), heading, pendown?, pencolor, penwidth, visible?} = state
let a = add (heading, 0.25) let command = if tuple? (pencolor)
(cos (a), sin (a)) then {
let (r, g, b, a) = pencolor
(:loadstate, x, y, heading, visible?, pendown?, penwidth, r, g, b, a)
}
else (:loadstate, x, y, heading, visible?, pendown?, penwidth, pencolor)
add_command! (command)
state
} }
} }
@ -1329,49 +1334,37 @@ fn apply_command {
(:penwidth, pixels) -> assoc (state, :penwidth, pixels) (:penwidth, pixels) -> assoc (state, :penwidth, pixels)
(:pencolor, color) -> assoc (state, :pencolor, color) (:pencolor, color) -> assoc (state, :pencolor, color)
(:setheading, heading) -> assoc (state, :heading, heading) (:setheading, heading) -> assoc (state, :heading, heading)
(:loadstate, x, y, heading, visible?, pendown?, penwidth, pencolor) -> #{:position (x, y), heading, visible?, pendown?, penwidth, pencolor}
(:loadstate, x, y, heading, visible?, pendown?, penwidth, r, g, b, a) -> #{:position (x, y), heading, visible?, pendown?, penwidth, :pencolor (r, g, b, a)}
(:show) -> assoc (state, :visible?, true) (:show) -> assoc (state, :visible?, true)
(:hide) -> assoc (state, :visible?, false) (:hide) -> assoc (state, :visible?, false)
} }
} }
fn turtle_state {
"Returns the turtle's current state."
() -> do turtle_states > unbox > last
}
fn load_turtle_state! {
"Sets the turtle state to a previously saved state. Returns the state."
(state) -> {
update! (turtle_states, append! (_, state))
let call = state/call ()
if call then { add_call! (call); :ok } else :ok
}
}
& position () -> (x, y) & position () -> (x, y)
fn position { fn position {
"Returns the turtle's current position." "Returns the turtle's current position."
() -> turtle_state () :position () -> do turtle_state > unbox > :position
} }
fn heading { fn heading {
"Returns the turtle's current heading." "Returns the turtle's current heading."
() -> turtle_state () :heading () -> do turtle_state > unbox > :heading
} }
fn pendown? { fn pendown? {
"Returns the turtle's pen state: true if the pen is down." "Returns the turtle's pen state: true if the pen is down."
() -> turtle_state () :pendown? () -> do turtle_state > unbox > :pendown?
} }
fn pencolor { fn pencolor {
"Returns the turtle's pen color as an (r, g, b, a) tuple." "Returns the turtle's pen color as an (r, g, b, a) tuple or keyword."
() -> turtle_state () :pencolor () -> do turtle_state > unbox > :pencolor
} }
fn penwidth { fn penwidth {
"Returns the turtle's pen width in pixels." "Returns the turtle's pen width in pixels."
() -> turtle_state () :penwidth () -> do turtle_state > unbox > :penwidth
} }
box state = nil box state = nil
@ -1392,7 +1385,6 @@ pkg Prelude {
background! & turtles background! & turtles
between? & math between? & math
bg! & turtles bg! & turtles
bgcolor & turtles
bk! & turtles bk! & turtles
bool & bool bool & bool
bool? & bool bool? & bool
@ -1454,7 +1446,7 @@ pkg Prelude {
left! & turtles left! & turtles
list & lists list & lists
list? & lists list? & lists
load_turtle_state! & turtles loadstate! & turtles
lt! & turtles lt! & turtles
lt? & math lt? & math
lte? & math lte? & math
@ -1476,7 +1468,6 @@ pkg Prelude {
omit & set omit & set
or & bool or & bool
ordered? & lists tuples strings ordered? & lists tuples strings
p5_calls & turtles
pc! & turtles pc! & turtles
pd! & turtles pd! & turtles
pencolor & turtles pencolor & turtles
@ -1497,9 +1488,7 @@ pkg Prelude {
random & math dicts lists tuples sets random & math dicts lists tuples sets
random_int & math random_int & math
range & math lists range & math lists
render_turtle! & turtles
report! & environment report! & environment
reset_turtle! & turtles
rest & lists tuples rest & lists tuples
right! & turtles right! & turtles
round & math round & math
@ -1533,8 +1522,8 @@ pkg Prelude {
turn/deg & math turn/deg & math
turn/rad & math turn/rad & math
turtle_commands & turtles turtle_commands & turtles
turtle_init & turtles
turtle_state & turtles turtle_state & turtles
turtle_states & turtles
type & values type & values
unbox & boxes unbox & boxes
unwrap! & results unwrap! & results

View File

@ -15,11 +15,13 @@
(when (= :error prelude/pkg) (error "could not load prelude")) (when (= :error prelude/pkg) (error "could not load prelude"))
(def ctx @{:^parent prelude/ctx}) (def ctx @{:^parent prelude/ctx})
(def errors @[]) (def errors @[])
(def draw @[])
(var result @"") (var result @"")
(def console @"") (def console @"")
(setdyn :out console) (setdyn :out console)
(def out @{:errors errors :draw draw :result result :console console}) (def out @{:errors errors :result result
:io @{
:stdout @{:proto [:text-stream "0.1.0"] :data console}
:turtle @{:proto [:turtle-graphics "0.1.0"] :data @[]}}})
(def scanned (s/scan source)) (def scanned (s/scan source))
(when (any? (scanned :errors)) (when (any? (scanned :errors))
(each err (scanned :errors) (each err (scanned :errors)
@ -42,22 +44,23 @@
(break (-> out j/encode string)))) (break (-> out j/encode string))))
(setdyn :out stdout) (setdyn :out stdout)
(set (out :result) (b/show result)) (set (out :result) (b/show result))
(var post @{}) (set (((out :io) :turtle) :data) (get-in prelude/pkg [:turtle_commands :^value]))
(try (try
(set post (i/interpret prelude/post/ast ctx)) (i/interpret prelude/post/ast ctx)
([err] (e/runtime-error err))) ([err] (e/runtime-error err)))
(set (out :draw) (post :draw)) (-> out j/encode string))
# out
(-> out j/encode string)
)
(comment (comment
# (do # (do
# (def start (os/clock)) # (def start (os/clock))
(def source ` (def source `
box foo = :bar fd! (100)
store! (foo, :baz) rt! (0.25)
unbox (foo) fd! (100)
lt! (0.25)
fd! (100)
setheading! (0.75)
unbox (turtle_state)
`) `)
(def out (-> source (def out (-> source
ludus ludus

View File

@ -39,3 +39,4 @@
(def validation-errors (post-validated :errors)) (def validation-errors (post-validated :errors))
(when (any? validation-errors) (each err validation-errors (e/validation-error err)) (break :error)) (when (any? validation-errors) (each err validation-errors (e/validation-error err)) (break :error))
(post-parsed :ast))) (post-parsed :ast)))

View File

@ -765,7 +765,7 @@ Deferred until a later iteration of Ludus:
(defn- cleanup [validator] (defn- cleanup [validator]
(def declared (get-in validator [:status :declared] {})) (def declared (get-in validator [:status :declared] {}))
(when (any? declared) (when (any? declared)
(each declaration declared (each declaration (keys declared)
(array/push (validator :errors) {:node declaration :msg "declared fn, but not defined"}))) (array/push (validator :errors) {:node declaration :msg "declared fn, but not defined"})))
validator) validator)

View File

@ -41,7 +41,7 @@ Turtle graphics describe the movements and drawing behaviours of screen, robot,
- Shows the turtle. - Shows the turtle.
* `hide`, no arguments * `hide`, no arguments
- Hides the turtle. - Hides the turtle.
* `loadstate`, x: number, y: number, heading: number, pendown: boolean, width: number, color: string OR r: number, g: number, b: number, a: number * `loadstate`, x: number, y: number, heading: number, visible: boolean, pendown: boolean, width: number, color: string OR r: number, g: number, b: number, a: number
- Loads a turtle state. - Loads a turtle state.
* `clear`, no arguments * `clear`, no arguments
- Erases any paths drawn and sets the background color to the default. - Erases any paths drawn and sets the background color to the default.
@ -71,11 +71,22 @@ Colors should also be specifiable with strings corresponding to CSS basic colors
Ludus should have access to turtle states. Ludus should have access to turtle states.
This is important for push/pop situations that we use for L-systems. This is important for push/pop situations that we use for L-systems.
There are two ways to do this: Ludus does its own bookkeeping for turtle states, or it has a way to get the state from a turtle. There are two ways to do this: Ludus does its own bookkeeping for turtle states, or it has a way to get the state from a turtle.
The latter has the value of being instantaneous, and gives us an _expected_ state of the turtle after the commands are all processed. The latter has the value of being instantaneous, and gives us an _expected_ state of the turtle after the commands are all processed.
In particular, this will be necessary for the recursive L-systems that require pushing and popping turtle state. In particular, this will be necessary for the recursive L-systems that require pushing and popping turtle state.
The latter has the drawback of potentially allowing the turtle state and expected turtle state to fall out of synch. The latter has the drawback of potentially allowing the turtle state and expected turtle state to fall out of synch.
The former has the value of always giving us the correct, actual state of the turtle. The former has the value of always giving us the correct, actual state of the turtle.
It has the drawback of requiring such state reporting to be asynchronous, and perhaps wildly asynchronous, as things like moving robots and plotters will take quite some time to actually draw what Ludus tells it to. It has the drawback of requiring such state reporting to be asynchronous, and perhaps wildly asynchronous, as things like moving robots and plotters will take quite some time to actually draw what Ludus tells it to.
(Being able to wait until `eq? (expected, actual)` to do anything else may well be extremely useful.) (Being able to wait until `eq? (expected, actual)` to do anything else may well be extremely useful.)
That suggests, then, that both forms of turtle state are desirable and necessary. That suggests, then, that both forms of turtle state are desirable and necessary.
Thus: turtles should communicate states (and thus there ought to be a protocol for communicating state back to Ludus) and Ludus should always do the bookkeeping of calculating the expected state. Thus: turtles should communicate states (and thus there ought to be a protocol for communicating state back to Ludus) and Ludus should always do the bookkeeping of calculating the expected state.
**Turtles use Cartesian, rather than screen, coordinates.**
The starting position of the turtle is `(0, 0)`, which is the origin, and _centred_ in the field of view.
Increasing the x-coordinate moves the turtle to the right; increasing the y-coordinate moves the turtle _up_.
**Turtles use compass headings, not mathematical angles.**
Turtles start pointing vertially, at heading `0`.
Turning right _increases_ the heading; pointing due "east" is `0.25`; south `0.5`, and west, `0.75`.