Compare commits

...

2 Commits

Author SHA1 Message Date
61625aa58c wip 2025-07-01 13:27:23 +01:00
223d6b4929 clamp angle to -pi..pi 2025-07-01 13:27:13 +01:00
2 changed files with 45 additions and 4 deletions

View File

@ -211,6 +211,24 @@ label.readout {
(when (not (. tbl k))
(tiles.fetch cq x y zoom #(tset tbl k $1)))))))
;; iso 9899:1999 says
;; "The atan2 functions return arctan y/x in the interval [−π , +π ] radians"
(fn clamp-angle [rad]
(let [circle (* 2 math.pi)]
(if
(< rad (- math.pi)) (clamp-angle (+ circle rad))
(> rad math.pi) (clamp-angle (- rad circle))
rad)))
(define-tests :clamp-angle
(expect= (clamp-angle 2) 2)
(expect= (clamp-angle (+ (* 4 math.pi) 2)) 2)
(expect= (clamp-angle (- 2 (* 4 math.pi))) 2))
(fn deg->rad [deg]
(* math.pi (/ deg 180)))
(fn draw-onto-map-surface [surface bounds zoom]
(let [{ : num-tiles-x : num-tiles-y } bounds
road-width 14
@ -228,7 +246,7 @@ label.readout {
(g:fill)
(g:translate (+ (// bounds.pixels.x 2)) (+ (// bounds.pixels.y 2)))
(g:rotate (* (/ (- app-state.orientation-target) 180) math.pi))
(g:rotate (deg->rad (- app-state.orientation-target)))
(g:translate (- (// bounds.pixels.x 2)) (- (// bounds.pixels.y 2)))
(cairo-roads g lines bounds)
@ -248,8 +266,31 @@ label.readout {
(g:save)
(g:move_to x y)
(g:rotate angle)
(g:rel_move_to (- (// w 2)) 3)
;; we are rendering the map rotated by -orientation.
;; the road angles are against north.
;; if orientation = 30 then rotation is -30
;; if the road angle is 70 then
;; when the map is pointing north, an angle 0 < n < 180
;; will be pointing rightwards
;; when the orientation is 30 degrees, the map is pointing
;; -30 degrees, so an angle 30 < n < (+ 180 30) is rightwards
(let [theta (clamp-angle (+ angle (deg->rad app-state.orientation-target)))]
(if (and (> theta 0) (< theta math.pi))
(do
(g:rotate (- angle))
(g:rel_move_to (- (// w 2)) 3))
(do
(g:rotate angle)
(g:rel_move_to (+ (// w 2)) 3))))
(g:text_path n)
(g:fill)
(g:restore))))))

View File

@ -77,7 +77,7 @@
(set biggest-n (- i 1)))))
(let [[x y] (. points biggest-n)
[nx ny] (. points (+ 1 biggest-n))
angle (math.atan (- ny y) (- nx x))]
angle (math.atan (- y ny) (- nx x))]
[(/ (+ nx x) 2) (/ (+ ny y) 2) angle]))