; Mandelbrot — fixed-point ASCII render.
; Runs identically on Python, C, and asm WASM tiers.
; The asm tier has no float support so we scale all coords by 1024.

(define SCALE 1024)
(define SCALE4 4096)            ; 4 * SCALE (escape threshold |z|^2)
(define WIDTH  32)
(define HEIGHT 12)
(define MAXITER 12)

(define (escape-count cx cy)
  (define (loop zr zi n)
    (let ((zr2 (/ (* zr zr) SCALE))
          (zi2 (/ (* zi zi) SCALE)))
      (cond ((>= n MAXITER) MAXITER)
            ((> (+ zr2 zi2) SCALE4) n)
            (else
              (loop (+ (- zr2 zi2) cx)
                    (+ (/ (* 2 (/ (* zr zi) SCALE)) 1) cy)
                    (+ n 1))))))
  (loop 0 0 0))

(define (shade n)
  (cond ((>= n MAXITER) (display "#"))
        ((> n 12) (display "@"))
        ((> n 7)  (display "*"))
        ((> n 4)  (display "+"))
        ((> n 2)  (display "."))
        (else     (display " "))))

(define (row py)
  (define cy (- (/ (* py 2048) HEIGHT) 1024))
  (define (col px)
    (if (< px WIDTH)
        (begin
          (shade (escape-count (- (/ (* px 3072) WIDTH) 2048) cy))
          (col (+ px 1)))
        (newline)))
  (col 0))

(define (render py)
  (if (< py HEIGHT)
      (begin (row py) (render (+ py 1)))
      (print "done")))

(render 0)
