;; Cell Pattern effect - custom patterns within cells
;;
;; Demonstrates building arbitrary per-cell visuals from primitives.
;; Uses local coordinates within cells to draw patterns scaled by luminance.

(require-primitives "xector")

(define-effect cell_pattern
  :params (
    (cell-size :type int :default 16 :range [8 48] :desc "Cell size")
    (pattern :type string :default "diagonal" :desc "Pattern: diagonal, cross, ring")
  )
  (let* (
         ;; Pool to get cell colors
         (pooled (pool-frame frame cell-size))
         (cell-r (nth pooled 0))
         (cell-g (nth pooled 1))
         (cell-b (nth pooled 2))
         (cell-lum (α/ (nth pooled 3) 255))

         ;; Cell indices for each pixel
         (cell-idx (cell-indices frame cell-size))

         ;; Look up cell values for each pixel
         (pix-r (gather cell-r cell-idx))
         (pix-g (gather cell-g cell-idx))
         (pix-b (gather cell-b cell-idx))
         (pix-lum (gather cell-lum cell-idx))

         ;; Local position within cell [0, 1]
         (lx (local-x-norm frame cell-size))
         (ly (local-y-norm frame cell-size))

         ;; Pattern mask based on pattern type
         (mask
           (cond
             ;; Diagonal lines - thickness based on luminance
             ((= pattern "diagonal")
              (let* ((diag (αmod (α+ lx ly) 0.25))
                     (thickness (α* pix-lum 0.125)))
                (α< diag thickness)))

             ;; Cross pattern
             ((= pattern "cross")
              (let* ((cx (αabs (α- lx 0.5)))
                     (cy (αabs (α- ly 0.5)))
                     (thickness (α* pix-lum 0.25)))
                (αor (α< cx thickness) (α< cy thickness))))

             ;; Ring pattern
             ((= pattern "ring")
              (let* ((dx (α- lx 0.5))
                     (dy (α- ly 0.5))
                     (dist (αsqrt (α+ (α² dx) (α² dy))))
                     (target (α* pix-lum 0.4))
                     (thickness 0.05))
                (α< (αabs (α- dist target)) thickness)))

             ;; Default: solid
             (else (α> pix-lum 0)))))

    ;; Apply mask: show cell color where mask is true, black elsewhere
    (rgb (where mask pix-r 0)
         (where mask pix-g 0)
         (where mask pix-b 0))))
