# Falling Sand Physics Simulation – Advanced Cellular Automata This document describes the complete feature set, mechanics, and UI of a self-contained, high‑performance falling‑sand simulator built in a single HTML file. The simulation runs entirely in the browser, using vanilla JavaScript, CSS, and HTML – no external libraries. --- ## Visual & UI Requirements ### Layout & Styling - **Dark‑themed dashboard** with a sidebar on the left and a centered canvas. - The sidebar houses: - A header with the simulation title. - **Category buttons** (`Poudres`, `Liquides`, `Gaz`, `Solides`, `Botanique`, `Gens.`, `Gomme`) that filter the element palette. - A **grid of element buttons** (3 columns) showing each material’s color and name. - **Control panel** at the bottom with: - Three display mode toggles: `Couleur` (normal), `Chaleur` (thermal map), `Tension` (stress map). - **Brush size** slider (1–15). - **Simulation speed** slider (0.1× – 3×). - **Temperature input** (numeric field) and a **Heat mode** toggle button. - Action buttons: `Générer Monde` (random terrain), `⏸️ Pause` / `▶️ Reprendre`, and `↺ Vider` (clear canvas). ### Canvas - Fixed internal grid resolution of **200 × 200** pixels, rendered on a canvas that scales to fill the remaining viewport while preserving aspect ratio. - CSS `image-rendering: pixelated` ensures sharp, crisp visuals. - The canvas supports **mouse dragging** to paint streams of elements in real time. ### Color Palette & Visuals - Each of the **34 distinct materials** has a unique color (with three variants per element for subtle variation). - **Emission & glow effects** are applied to fire, lava, and hot metals via a separate glow canvas with blur and compositing. - **Thermal mode** maps temperature to a color gradient (cold = blue, hot = red/white). - **Stress mode** visualises structural tension as a red‑to‑green gradient. --- ## Simulation Mechanics & Physics Rules The simulation is built on a discrete 2D grid (`200 × 200`). Each cell holds an element type, a temperature, velocity vectors (for fluids and gases), and metadata (e.g., plant growth stage). The engine updates the grid in a frame‑by‑frame loop driven by `requestAnimationFrame`. ### Core Element Categories & Behaviours #### Solids (Static & Granular) - **Static solids** (`MUR`) are immovable and act as rigid boundaries. - **Granular materials** (`SABLE`, `TERRE`, `SEL`, `CENDRE`, `NEIGE`, `GRAVIER`, `METAL_FRAG`, `NEIGE_CARBONIQUE`): - Fall straight down if the cell below is empty. - If blocked, they attempt to slide diagonally down‑left or down‑right (randomised order) with a probability based on friction. - They can displace lighter fluids (liquids and gases) when their density is higher. #### Liquids - **Water**, **Oil**, **Acid**, **Lava**, and **Molten Metal**: - Fall downward under gravity, and spread horizontally when blocked. - Have a **dispersion** parameter that controls sideways spreading. - **Acid** dissolves any non‑wall/non‑crystal material it touches (turning both acid and the victim cell into empty space) and can release acidic gas. - **Water** reacts violently with **Lava**: it turns into steam (vapour) and cools lava into rock. - **Oil** is flammable – it ignites when in contact with fire. #### Gases - **Vapour**, **Acidic Gas**, **Smoke**, **Fire**, and **CO₂**: - Rise upward (negative gravity) and diffuse horizontally. - **Fire** behaves as a gas: it rises, spreads, and ignites flammable materials (wood, oil, TNT, plants, etc.). It has a finite lifetime and eventually extinguishes into smoke. - **Smoke** and **CO₂** gradually dissipate over time. #### Generators - **Water source**, **Lava source**, and **Acid source** continuously spawn their respective fluids into empty cells below them. #### Botanics - **Seeds** (`GRAINE`) that fall and, when they land on earth, grow into one of three plant types (tree, flower, or bush) with different growth patterns. - **Plants**, **Flowers**, and **Wood** are flammable and can be consumed by fire. ### Thermodynamics & Phase Transitions Every cell carries a temperature (in °C). The simulation includes: - **Heat diffusion** using a 4‑neighbour conductivity model (with ambient air as a heat sink). - **Phase changes**: - **Melting** (e.g., sand → lava, metal → molten metal) when temperature exceeds the material’s melting point. - **Freezing** (e.g., water → ice) below the freezing point. - **Boiling** (water → vapour) above 100 °C. - **Condensation** (vapour → water) below 95 °C. - **Sublimation** (dry ice → CO₂ gas). - **Extinction** (fire → smoke) when temperature drops below 300 °C. - **Inflammation**: Many materials (wood, oil, TNT, plants) ignite when their temperature exceeds their flash point, turning into fire. - **Reaction‑driven temperature changes** (e.g., water‑lava reaction raises water temperature and cools lava). ### Chemical Reactions - **Acid** dissolves sand, rock, metal, etc., and may produce acidic gas. - **Water + Lava** → steam + rock (rapid cooling). - **Oil + Fire** → immediate ignition. - **TNT** explodes when heated, igniting nearby flammable materials and producing smoke. - **Fire propagation** to adjacent flammable cells via thermal transfer and random chance. ### Structural Integrity - A stress map tracks accumulated tension on solid materials. - Unsupported solids (those with no stable neighbours below or sideways) accumulate stress and eventually fracture, turning into gravel or debris. - Plants and wood check for root support; unsupported ones collapse. ### Botany & Growth - Seeds planted in earth grow into: - **Trees** (which grow a trunk and then a canopy of leaves). - **Flowers** (which grow upward and then bloom). - **Bushes** (which spread horizontally). - Growth is driven by a metadata‑based state machine and happens in periodic ticks. --- ## Critical Implementation Rules (Performance & Correctness) ### Multi‑Pass / Directional Processing - The grid is divided into **16×16 chunks** for efficient wake‑up management. - Each frame, only chunks that have been “woken up” (cells changed or active) are processed. - Within a chunk, iteration is **bottom‑to‑top** to prevent particles from “teleporting” downward in one frame. - The scan direction (left‑to‑right or right‑to‑left) alternates each frame to avoid directional bias. ### Horizontal & Diagonal Shuffling - When moving diagonally or horizontally, the order of checking left vs. right is **randomised** for each particle, ensuring symmetric spreading and avoiding unnatural piling. ### Time Scaling - A **speed slider** controls the simulation’s time scale (0.1× to 3×). The engine accumulates delta time and executes the appropriate number of simulation steps to keep the game running at a consistent physics rate, independent of frame rate. ### Rendering Pipeline 1. **Background** is drawn once (sky, mountains, lake, clouds) and reused. 2. **Particle rendering** uses an `ImageData` buffer for fast pixel‑by‑pixel updates. 3. **Glow pass** (emissive materials) is rendered on a separate canvas with blur and blending, producing a realistic heat glow effect. ### User Input & Real‑time Painting - Mouse/touch events are mapped to simulation coordinates (accounting for canvas scaling and aspect ratio). - While the mouse is held and dragged, the current element (or heat) is painted continuously. - The **brush size** determines the radius of the circular stamp. --- ## Deliverable The complete simulation is packaged as a **single HTML file**. It includes: - All HTML structure, CSS styling, and JavaScript logic in one document. - No external dependencies – everything runs natively in the browser. - All 34 materials, their physical properties, and interactions are fully implemented. - The UI is fully wired: element selection, category filtering, brush size, speed, heat mode, display modes, pause, reset, and random world generation. - The simulation loop uses `requestAnimationFrame` with delta‑time accumulation for smooth, frame‑rate‑independent physics. - The code is production‑ready and works immediately when saved as `.html` and opened in any modern browser. --- ## Summary of Advanced Features | Feature | Description | |--------------------------|-----------------------------------------------------------------------------| | **34 element types** | Wide variety of solids, liquids, gases, generators, and botanicals. | | **Thermodynamics** | Temperature diffusion, phase changes, ignition, and extinction. | | **Chemical reactions** | Acid dissolving, water–lava explosion, TNT detonation, oil ignition. | | **Botany** | Seeds grow into trees, flowers, or bushes with distinct growth patterns. | | **Structural stress** | Unsupported solids break under tension. | | **Chunk‑based updates** | Performance optimisation using 16×16 chunks and wake‑up timers. | | **Glow & emissive FX** | Fire and lava emit light via a separate blur pass. | | **Thermal & stress maps**| Visualisation modes for temperature and structural stress. | | **Time scaling** | Adjustable simulation speed from slow‑motion to fast‑forward. | | **Multi‑pass scanning** | Bottom‑to‑top, randomised left/right checks for correct fluid dynamics. | This simulation provides a rich, interactive sandbox experience that goes far beyond a simple falling‑sand demo, incorporating realistic physical, chemical, and biological behaviours.