"""
ga-arch.studio - Parametric grid (GhPython)
============================================

The geometry behind the homepage of https://ga-arch.studio, rebuilt for
Grasshopper. Same parameters, same random generator: with the same seed you
get the same cubes you see on the website.

Setup (Rhino 8, Grasshopper):
  1. Add a "Python 3 Script" component.
  2. Create these inputs (all optional, type hint float/int):
       size_x, size_y, size_z   box size            (0.1 - 1.0)
       count_x, count_y         grid count           (1 - 20)
       seed                     random seed          (1 - 100)
       wave_amp                 ripple amplitude     (0 - 1)
       twist                    twist angle factor   (-0.5 - 0.5)
       jitter                   random height offset (0 - 2)
       cull                     share of boxes removed (0 - 0.9)
       float_amp                vertical wave offset (0 - 3)
       attractor_x, attractor_y attractor position on the grid (0 - 1, like the MD Slider)
       attractor_strength       attractor intensity  (0 - 1)
       time                     animation phase in seconds (0 = static)
  3. Create two outputs: boxes, info
  4. Paste this script, connect sliders and bake "boxes".

Units follow the document; the website uses metres. Z is up.
Feel free to use and adapt it in your own projects.
"""

import math
import Rhino.Geometry as rg

M32 = 0xFFFFFFFF


def _value(name, default):
    """Unconnected inputs fall back to the homepage defaults."""
    v = globals().get(name)
    return default if v is None else v


def _imul(a, b):
    return ((a & M32) * (b & M32)) & M32


def mulberry32(seed):
    """Port of the JavaScript mulberry32 used on the website."""
    state = int(seed) & M32

    def rnd():
        nonlocal state
        state = (state + 0x6D2B79F5) & M32
        t = state
        t = _imul(t ^ (t >> 15), t | 1)
        t ^= (t + _imul(t ^ (t >> 7), t | 61)) & M32
        return ((t ^ (t >> 14)) & M32) / 4294967296.0

    return rnd


sx = float(_value("size_x", 0.8))
sy = float(_value("size_y", 0.8))
sz = float(_value("size_z", 0.8))
nx = max(1, int(_value("count_x", 10)))
ny = max(1, int(_value("count_y", 10)))
seed_value = int(_value("seed", 1))
wave = float(_value("wave_amp", 0.1))
tw = float(_value("twist", 0.0))
jit = float(_value("jitter", 0.0))
cull_share = float(_value("cull", 0.0))
flt = float(_value("float_amp", 0.0))
attr_u = float(_value("attractor_x", 0.5))
attr_v = float(_value("attractor_y", 0.5))
attr_s = float(_value("attractor_strength", 0.0))
t_now = float(_value("time", 0.0))

GAP = 0.2
FREQUENCY = 0.5
SPEED = 2.0
ATTR_GAIN = 2.0

random = mulberry32(seed_value)
step_x = sx + GAP
step_y = sy + GAP
offset_x = (nx - 1) * step_x / 2.0
offset_y = (ny - 1) * step_y / 2.0
half_x = offset_x + sx / 2.0
half_y = offset_y + sy / 2.0
# Attractor: MD Slider (u, v) mapped onto the grid extents, same as the website
att_x = (attr_u * 2 - 1) * half_x
att_y = -((attr_v * 2 - 1) * half_y)
radius = max(1.0, math.hypot(half_x, half_y))

boxes = []
for i in range(nx):
    for j in range(ny):
        # Same loop order as the website, so the random sequence matches
        r = random()
        px = i * step_x - offset_x
        py = -(j * step_y - offset_y)  # website Z axis -> Rhino -Y (Y-up to Z-up)
        distance = math.hypot(px, py)

        if r < cull_share:
            continue

        ripple = math.sin(distance * FREQUENCY - t_now * SPEED)
        height = max(0.01, sz * (1 + ripple * wave) + (r - 0.5) * 2 * jit)
        if attr_s > 0:
            falloff = max(0.0, 1 - math.hypot(px - att_x, py - att_y) / radius)
            height *= 1 + ATTR_GAIN * attr_s * falloff
        elevation = math.cos(distance * FREQUENCY * 1.5 - t_now * SPEED * 0.8) * flt
        angle = tw + distance * tw

        plane = rg.Plane(rg.Point3d(px, py, elevation), rg.Vector3d.ZAxis)
        plane.Rotate(angle, rg.Vector3d.ZAxis)
        box = rg.Box(plane,
                     rg.Interval(-sx / 2.0, sx / 2.0),
                     rg.Interval(-sy / 2.0, sy / 2.0),
                     rg.Interval(0, height))
        boxes.append(box)

info = "{} boxes | seed {} | grid {}x{} | ga-arch.studio".format(len(boxes), seed_value, nx, ny)
