What is the Chemical Chaos Engine?
The Chemical Chaos Engine is a real-time physics sandbox that simulates emergent
molecular behavior by combining rigid-body dynamics, fluid turbulence, and stochastic organic chemistry.
Built from scratch in vanilla JavaScript with zero external dependencies, it achieves 180 FPS at 250 particles
and 65+ FPS at 1200 particles (internal benchmarking, uncapped desktop; normally hardware-capped to monitor refresh rate like 60 FPS) using a custom SoA physics kernel,
spatial hash grid, and a highly optimized batched Canvas2D rendering pipeline.
🎯 Design Philosophy: This is a creative visualization of chemistry, not a
quantum-mechanically accurate simulator. It uses normalized pseudo-units and simplified reaction models to
create emergent, visually compelling molecular behavior.
Core Capabilities
- Real-Time Physics: 250 particles @ 180 FPS · 1200 particles @ 65 FPS (desktop, uncapped) — 80–570 @ 60 FPS (mobile)
- Massive Organic Chemistry Suite v28.9 — 30 full organic
reactions including SN1, SN2, Polymerizations, Diels-Alder, Michael Addition, and Wittig Reaction
- Valency-Constrained Chemistry: Enforces electron shell rules (C=4, N=3, O=2, H=1)
- Quantum Visualizations v28.8 — Full sp³, sp², sp molecular
orbital rendering and R/S Chirality labels
- Molecule Achievements v28.5 — Built-in detection for 14
specific molecules with progression tracking
- Electronegativity & Bond Polarity v28.0 — real EN values
drive bond polarization and visual gradient rendering
- Formal Charges & Radicals v28.1 — per-atom FC calculation
with automatic radical detection and stabilization
- Acid-Base Reactions v28.3 — neutralization, proton
donation, autoionization, and strong-acid dissociation
- pH Tracking & Hydronium/Hydroxide v28.0 — live pH derived
from H₃O⁺ / OH⁻ species counts
- Intelligent Probe System: Autonomous particles that form temporary connections with
atoms
- Structural Detection: Automatic recognition of aromatic rings, conjugated systems, and
cumulenes
- Hydrogen Bonding: Directional weak forces between H and electronegative atoms
- Interactive Modes: 6 cursor tools (Grab, Push, Pull, Cut, Destroy, Push+Destroy)
- Flow Field Visualization: Curl noise-based turbulence with logarithmic scaling
- Configuration Export/Import: Save and share exact simulation states
Real-Time Benchmarks v32.0
Desktop (Ryzen 5600X) — internal benchmark
250 particles @ 180 FPS (if uncapped; normally capped at monitor refresh rate e.g., 60 FPS)
1200 particles @ 65 FPS ✓
3000 particles @ ~20 FPS (engine max)
Mobile (Snapdragon 8 Gen 3)
80 particles @ 60 FPS
570 particles @ 60 FPS ✓
1000 particles @ ~25 FPS
HPC Kernel Telemetry (1048P, desktop)
Total physics latency: ~5ms/frame
ChemistryAndGrid: ~2ms (38%)
Constraints × 6: ~1.3ms (26%)
Compute bound: 87% · Memory: 9% · IO: 4%
Technical Highlights
- SoA Physics Kernel: Structure-of-Arrays TypedArrays (Float64/Uint16) for cache-coherent particle data — eliminates per-frame GC pressure
- Batched Canvas2D Rendering: Bond coordinates are pre-calculated into Float32Array buffers and grouped by atom type, reducing ~400 individual
stroke() calls to ~8 batched calls per frame
- Spatial Hash Grid: O(N) collision detection with 4096 buckets and bitmask hash
- Semi-Implicit Euler: Symplectic integration for energy conservation
- Disjoint Set Union: Near-constant O(α(N)) molecular identity tracking
- Bitmask Flags:
FLAG_IS_AROMATIC and ring state encoded as Uint32Array bits — faster than property lookups
- HPC Profiler: Built-in per-kernel telemetry (ALU/BW/CPU/XFER tags) with 150-frame rolling averages
- Deterministic PRNG: 32-bit xorshift-multiply for reproducible seeds
- Temporal Amortization Scheduler: Heavy chemistry workloads (pH, stabilization, organic reactions, structure detection) are frame-sliced across a 60-frame cycle to maintain a strict render budget
- Double-Buffered Graph State: Aromaticity and molecular ring detection use isolated
tempFlags buffers during DFS traversal, committing state atomically to prevent visual flickering
- Adaptive Performance: 2-second rolling FPS window triggers automatic quality scaling
- Configurable FPS Cap: Runtime-adjustable via
CHAOS_API.fpsLimit (0 = uncapped)
Known Limitations
- Not quantum mechanically accurate (classical approximation)
- Uses normalized pseudo-units, not SI
- Temperature = kinetic energy proxy (not thermodynamic)
- Stochastic reactions (not activation energy-based)
- Physics on main thread — full Web Worker and OffscreenCanvas migration pending for deep parallelization
Configuration Manual
Access the HUD via the ⚙ icon (bottom-right). Click the 📌 pin icon to keep it open.
System Control
Atom Count
Range: 10 – 3000 particles (engine max)
Default: 250 (desktop), 150 (mobile)
Note: Requires system reset (Flip Table) to apply.
Time Dilation
Range: 0.1x – 2.0x
Default: 1.0x
Controls global delta-time multiplier.
Low (0.1): Slow motion for observation.
High (2.0): Fast-forward for quick reactions.
Mouse Interaction
Interaction Tool
Dropdown selector with 6 modes:
Grab: Spring-force tool — picks up nearest atom (80px search radius)
Push: Radial repulsion (gentle)
Push + Destroy: Crusher field (repels + deletes at center)
Pull: Gravitational attractor
Cut: Severs all bonds in 50px radius
Destroy: Deletes atoms + triggers shockwave
Cursor Force
Range: 1 – 20
Default: 6.5
Multiplies mouse interaction strength by 4.5x internally ("God Mode").
Probe Range (Blast Radius)
Range: 1 – 50 atoms
Default: 10
Chain reaction depth when high-energy probes detonate.
Determines how many neighboring atoms are destroyed in cascade.
Environment
Temperature
Range: 0 – 400 K (Kelvin)
Default: 100 K (0.5 internal)
Effects:
• Increases particle velocity
• Accelerates reaction rates — including acid-base transfers
• Triggers thermal elimination (> 300 K)
• Influences flow field evolution speed
Viscosity
Range: 0 – 0.1
Default: 0.01
Atmospheric drag coefficient.
0.0: Perfect vacuum (no damping).
High (0.1): Thick fluid/gel medium.
Turbulence
Range: 0 – 0.05
Default: 0.012
Controls curl noise flow field strength.
Hidden multiplier: 50x amplification internally.
Aromatic rings and conjugated systems are immune to turbulence shear.
Thermal Zones v28.4
Range: Min / Max (0 – 400 K)
Default: Ambient Temp
Creates localized temperature gradients (hot/cold spots) within the grid.
Reactions and movement speed dynamically scale between minimum and maximum bounds depending on
where particles are located in the fluid field.
Crowding
Range: 0 – 0.1
Default: 0.01
Lennard-Jones-style intermolecular repulsion.
Prevents spatial overlap between different molecules.
150px separation radius enforced.
Advanced Chemistry
Reactivity
Range: 0 – 3.0
Default: 1.0
Probability multiplier for all chemical events — organic reactions, acid-base transfers, and
autoionization all scale with this value.
0: Bonds are permanent (no reactions).
High (3.0): Aggressive bond breaking/forming.
Bond Stiffness
Range: 0.1 – 1.0
Default: 0.5
Spring constant for covalent bonds.
Rings use 8x multiplier (force 1.0) for rigidity.
Low: Floppy, rubber-like structures.
High: Rigid, crystalline geometry.
H-Bond Strength
Range: 0 – 0.5
Default: 0.0005
Magnitude of directional hydrogen bonding forces.
Only forms between H-N or H-O pairs.
Requires 160–300px distance and proper angular alignment (cosθ > 0.3).
H-Bond Limit
Range: 1 – 6 bonds per atom
Default: 3
Maximum simultaneous H-bonds per acceptor atom.
Determines if structures form linear strands or 3D webs.
Expansion Force
Range: 0 – 1.0
Default: 0.1
Intramolecular repulsion that unfolds crumpled structures.
Prevents atoms in same molecule from overlapping.
200px effective radius.
Probe Velocity
Range: 0.1 – 5.0
Default: 2.0
Base movement speed of autonomous Probe particles.
Probes use steering behavior (heading + turn speed).
Probe Energy
Range: 0 – 10%
Default: 2%
Chance of creating "high-energy" probe connections.
High-energy probes glow cyan and can trigger 10% chance detonations.
Atom Composition
Spawn Ratios
Individual sliders for each particle type.
Ratios auto-balance to 100% total.
Default: C(27%), H(20%), O(14%), N(9%), P(3%), S(2%), Cl(2%), Br(0%), Probe(23%)
High Carbon: Favors long chains and rings.
High Cl: More HCl available for strong-acid dissociation.
High Probe: Creates volatility and measurement effects.
Chemistry Visualization v28.0+
Show Electronegativity
Default: OFF
Overrides normal bond gradients with an electronegativity-based color map. The brighter end of
each bond indicates the more electronegative atom, showing where electron density
accumulates.
Show Formal Charges
Default: OFF
Displays calculated formal charge (+1, −1, etc.) as a label next to each charged atom. Uses the
formula FC = V − N − B/2.
Show Radicals
Default: ON
Renders a pulsing red dot on any atom that has an unpaired electron (odd number of non-bonding
electrons). Radicals are highly reactive and trigger automatic stabilization attempts.
Show Molecule Names
Default: OFF
Labels recognized molecular formulas at their center of mass. Also enables H₃O⁺ and OH⁻ labels on
hydronium and hydroxide ions.
Show Chirality v28.8
Default: OFF
Calculates Cahn-Ingold-Prelog (CIP) priorities for all sp³ carbons and draws 'R' or 'S'
stereocenter indicators based on 3D depth approximation.
Show Orbitals v28.8
Default: OFF
Calculates atom hybridization (sp³, sp², sp) and dynamically renders pulsing electron probability
clouds / pi-systems around bonds instead of standard lines.
Show pH Background
Default: OFF
Tints the canvas background according to the current live pH value — red for acidic, blue for
basic, neutral for pH 7.
Debug & Visualization
Show FPS
Default: OFF
Real-time performance monitor.
Displays: FPS, Avg/P95 frame times, histogram.
Diagnostics: Atom/Probe count, active interactions, grid buckets.
Spatial Grid
Default: OFF
Visualizes spatial hash grid overlay.
Shows 150px² buckets (adjustable).
Heatmap
Default: OFF
Color-codes particles by velocity.
Blue (slow) → Red (fast).
Based on magnitude: √(vx² + vy²).
Trails FX
Default: OFF
Shows particle path history (60 points max).
Updates every 4 frames for performance.
Flow Field
Default: OFF
Visualizes active turbulence vector field.
Logarithmic scaling: log(windScale × 1000 + 1) × 12.
50px grid spacing.
Show Stress
Default: OFF
Colors bonds by strain.
Green = ideal length, Red = overstretched/compressed.
Strain = |distance − target| × 0.5.
Grid Cell Size
Range: 50 – 300px
Default: 150px
Adjusts spatial hash bucket dimensions.
Warning: Small values (< 100px) can destabilize physics.
Events Overlay v28.5
Default: OFF (Persists in localStorage)
Turns on the Evolution Tracking HUD. Dynamically loads the `chaos-events-complete.js` payload and
displays trophies as specific molecules form.
Simulation Controls
Pause / Resume
Freezes physics integration.
Rendering continues (allows inspection).
Flip Table (Reset)
Clears simulation and respawns particles.
Reads configuration code from input box if present.
Always spawns one benzene molecule at center.
Configuration Export/Import
Save Code
Click "Copy" to export current state.
Generates Base64-encoded snapshot containing:
• All parameter values
• Exact particle positions & velocities
• Bond topology
• Seed value
Load Code
Paste code into input box, then click "Flip Table".
Accepts: Full snapshot codes OR simple seed numbers.
Restores exact simulation state.
Mouse Interaction System
Select a mode from the Interaction Tool dropdown to change cursor behavior. Left-clicking
always spawns 12 cyan sparks for visual feedback.
Interaction Modes
- Grab: Spring-force pickup tool. Finds the nearest atom within 80px of the cursor,
then applies a spring-like force (max 40 units) to drag it. Includes 0.8× friction damping for
stability.
Release to fling the atom with mouse velocity.
- Push: Soft radial repulsion within 180px range. Force scales as (1 − dist/180) × Force
× 4.5. Useful for gentle molecular separation without destruction.
- Push + Destroy: "Crusher" mode. Repels particles beyond 60px, but deletes any atom that
enters the 60px danger zone. Triggers chain reactions and plasma sparks.
- Pull: High-gravity attractor within 180px. Pulls particles toward cursor with force (1
− dist/180) × Force × 4.5. Forces collisions and rapid bonding.
- Cut: Precision severing tool. Breaks all bonds within 50px radius. Atoms
within 75px also have bonds severed. Creates plasma effects at cut sites.
- Destroy: Mass deletion within 80px radius. Triggers shatterMolecule() on all atoms,
causing chain reactions that propagate to bonded neighbors. Creates large ripple effects.
Force Mechanics
God Mode Multiplier
All mouse forces use hidden 4.5x amplification.
Actual force = CursorForce × 4.5 × (1 − distance/range)
Ensures user input feels responsive despite mass scaling.
Probe Range (Blast Radius)
Controls chain reaction depth for Destroy mode.
Uses stochastic propagation: 50% chance to continue each layer.
Can affect 1–50 atoms depending on setting and luck.
Interaction Range
Fixed at 120px × Scale for particle detection.
Mouse force extends to 180px (1.5× range).
Ensures smooth falloff at boundaries.
Visual Feedback
- Plasma Sparks: 12 particles spawn at click location, velocity (−0.5 to 0.5) × 4,
lifetime 50 frames
- Click Nodes: Pulsing circles (30 frame lifetime) mark interaction points
- Ripples: Expanding rings created by shattering events, fade over 50 frames
- Shockwaves: Impulse forces (4.0 – 8.0 magnitude) applied to shattered atoms
⚠️ Mobile Considerations: Touch interactions use e.touches[0] coordinates. Force scaling is
identical to desktop but effective range feels larger due to lower particle counts.
The Chemistry Engine
Reactions are evaluated stochastically every 10 frames (6 times/second at 60 FPS) to decouple reaction rates
from frame rate.
Valency & Oxidation Rules
The simulation enforces strict electron shell constraints:
- Fixed Valency: C=4, N=3, O=2, H=1, Cl=1, Br=1
- Dynamic Hypervalency:
- Sulfur: 2 bonds normally, expands to 8 if bonded to Oxygen (sulfates, sulfonyl)
- Phosphorus: 3 bonds normally, expands to 5 if bonded to Oxygen (phosphates)
- Nitrogen: 3 bonds normally, can accept 4 if bonded only to H/O (ammonium)
- Oxygen Rule: Cannot form chains > 2 atoms (O-O-O forbidden, prevents infinite
peroxides)
- Nitrogen/Phosphorus Rule: Cannot form homonuclear chains (N-N-N or P-P-P forbidden)
Electronegativity & Bond Polarity v28.0
Every atom carries a fixed electronegativity (EN) value based on the Pauling scale. When two atoms share a
bond, the engine calculates the EN difference to classify the bond and — when the visualization toggle is on
— to color it accordingly.
Electronegativity Table
H: 2.20 | C: 2.55 | N: 3.04
O: 3.44 | P: 2.19 | S: 2.58
Cl: 3.16 | Br: 2.96 | Probe: 2.50
Bond Classification
Covalent: ΔEN < 0.4 (electrons shared equally)
Polar: 0.4 ≤ ΔEN ≤ 1.7 (unequal sharing)
Ionic: ΔEN > 1.7 (electron transfer)
Visual Rendering
When Show Electronegativity is ON, bond gradients shift so the brighter end points toward
the more electronegative atom — showing where electron density accumulates.
Overrides stress-mode and default gradients.
Each atom's formal charge (FC) is continuously recalculated using the standard chemistry formula based on
true bond orders rather than geometric bond counts.
📐 Formula: FC = V − N − (TotalBondOrder) where V = valence
electrons,
N = non-bonding electrons. Result is clamped to the range [−3, +3].
Valence Electron Table
H: 1 | C: 4 | N: 5 | O: 6
P: 5 | S: 6 | Cl: 7
Common Results
O with 1 bond → FC = −1 (hydroxide / alkoxide)
O with 3 bonds → FC = +1 (hydronium / oxonium)
N with 4 bonds → FC = +1 (ammonium)
N with 2 bonds → FC = −1 (amide)
Radical Detection v28.0
An atom is flagged as a radical when it has an odd number of non-bonding electrons. Radicals
are highly reactive — the stabilization system actively tries to pair them with other radicals or
open-valence neighbors.
Detection
Non-bonding electrons = V − (bonds × 2)
Radical = nonBonding % 2 !== 0
Recalculated every 30 frames during structure detection.
Visual
When Show Radicals is ON: a pulsing red dot appears on radical atoms.
Pulse: alpha oscillates via sin(time).
Stabilization
Radicals search within 100px for another radical or any atom with open valence.
On successful bond: red spark burst + ripple.
Capped at 5 stabilizations per frame system-wide.
Intelligent Stabilization System v28.0
Every 60 frames, the engine scans all molecules for instability. If any atom carries a non-zero formal charge
or is a radical, the system attempts automatic rearrangement to restore neutrality.
Charge Rearrangement
Negative FC atoms seek: free H⁺ ions or nearby positively charged atoms.
Positive FC atoms seek: negatively charged atoms, or O/N with open
valence.
On success: new bond forms, green spark + ripple.
Radical Rearrangement
Radical atoms seek: other radicals first, then any open-valence atom within 100px.
On success: bond forms, red spark + ripple.
Two radicals bonding = singlet product (both stabilized).
Rate Limiting
Cap: MAX_REORDER_PER_FRAME = 5
Shared with autoFormHydronium and solveAcidBase.
Prevents runaway cascade in dense systems.
pH System & Hydronium / Hydroxide v28.0
The engine continuously tracks the concentration of H₃O⁺ (hydronium) and OH⁻ (hydroxide) ions and derives a
live pH value from them.
Species Detection
H₃O⁺: Oxygen with exactly 3 hydrogen bonds. Flagged
isHydronium = true, charge = +1.
OH⁻: Oxygen with exactly 1 hydrogen bond (and nothing else). Flagged
isHydroxide = true, charge = −1.
pH Calculation
Concentrations = species count / total atoms.
Acidic: pH = 7 − log₁₀(acid × 100 + 1) × 2
Basic: pH = 7 + log₁₀(base × 100 + 1) × 2
Neutral: exponential decay toward 7.
Auto-Formation
Free H atoms near water (O with 2 H bonds) can spontaneously attach, forming H₃O⁺.
Probability: 30% × temperature per check.
Visual: cyan spark burst on formation.
Acid-Base Reactions v28.3
The solveAcidBase() system implements four distinct proton-transfer reaction types. All are
proximity- and orientation-driven, respect the shared rearrangement cap, and run every 45 frames alongside
autoFormHydronium().
🧪 New in v28.3: Acid-base reactions are the first system where the engine actively
transfers an existing bonded atom between two molecules. The pH readout now responds dynamically to
real chemical equilibria rather than just counting species.
A — Neutralization: H₃O⁺ + OH⁻ → 2 H₂O
H₃O⁺ + OH⁻ → H₂O + H₂O
Probability: 30% × temp | Range: 100px | Spark: orange
The most thermodynamically favorable reaction in the engine. When a hydronium oxygen comes within range of a
hydroxide oxygen, one H is broken from H₃O⁺ and bonded to OH⁻. Both become neutral water. The two new water
molecules receive a gentle velocity kick apart to prevent immediate re-interaction.
B — Generic Proton Donation: H-X + :B → X⁻ + H-B
H–X + :B → X⁻ + H–B
Strong base: 12% | Weak base: 3% | Range: 80px | Spark: orange
Any H bonded to an electronegative atom (O or N) can donate to a nearby base — an O or N in a
different molecule that has an open valence slot. The system classifies bases by strength:
- Strong base: O with ≤ 1 bond, or N with < 3 bonds → 12% × temp probability
- Weak base: All other qualifying O/N → 3% × temp probability
Geometry matters: the engine picks the H that is physically closest to the acceptor base, ensuring the
transferred proton takes the most plausible path.
C — Autoionization: H₂O + H₂O → H₃O⁺ + OH⁻
H₂O + H₂O ⇌ H₃O⁺ + OH⁻
Probability: 0.08% × temp × reactivity | Range: 90px | Spark: magenta
Two clean water molecules (each O with exactly 2 H bonds, in separate molecules) near each other have a tiny
chance of spontaneously exchanging a proton. One becomes H₃O⁺, the other OH⁻. This is the engine's
equilibrium mechanism — it continuously seeds the ion pool that neutralization then consumes, keeping pH
dynamic even in pure water.
D — HCl Strong Acid Dissociation: H-Cl + :B → Cl⁻ + H-B
H–Cl + :B → Cl⁻ + H–B
Probability: 25% × temp | Range: 70px | Spark: orange
HCl is a strong acid — its dissociation probability is much higher than generic O-H or N-H donation. When an
H-Cl molecule encounters any base (O or N with open valence) in a different molecule, the H transfers and
Cl⁻ is released as a free ion. To prevent immediate re-capture, Cl⁻ receives a 90-frame rejoin
cooldown and a velocity kick away from the reaction site.
💡 Equilibrium Tip: Autoionization (C) and neutralization (A) form a natural feedback loop.
In a pure-water system, autoionization generates ions that neutralization destroys, keeping pH oscillating
around 7. Adding Cl atoms (high Cl ratio) shifts this equilibrium acidic because HCl dissociation floods the
system with H⁺.
Advanced Organic Synthesis v28.5+
The engine implements a suite of 26 distinct organic reactions that evaluate stochastically every 10 frames
based on atomic geometry, temperature, and electronegativity characteristics.
1. Substitution & Elimination
- SN1 (Unimolecular): Tertiary carbons lose a leaving group (Cl), forming a carbocation
which is later attacked by a nucleophile (requires high temperature).
- SN2 (Bimolecular): Strong nucleophiles attack primary/secondary carbons with a leaving
group, resulting in a single concerted step (inversion visualized via repulsion).
- E1 / E2 Elimination: Thermal elimination (> 300 K) strips adjacent H and Cl atoms to
form C=C double bonds. Driven by strong bases.
2. Radical Chain Reactions
- Initiation: Weak bonds (like peroxides O-O) break homolytically under high heat,
creating two radicals.
- Propagation: A radical rips a hydrogen off a stable molecule, transferring the radical
state to the carbon chain.
- Termination: Two radicals collide and bond, creating a singlet state.
3. Addition Modifications
- Electrophilic Addition (Markovnikov): Radicals or ions attack C=C double bonds. The
engine attempts to place the nucleophile on the more substituted carbon.
- Hydrogenation: Free H₂ molecules attack double bonds under high pressure/crowding,
reducing them to single bonds.
- Hydrolysis: Esters break apart in the presence of H₂O (aided by acidic environments)
into an acid and an alcohol.
- Dehydration: Alcohols bounded to neighboring H-bearing carbons eject H₂O to form C=C
bonds (temperature dependent).
4. Advanced Synthetic Mechanisms
- Aldol Condensation: Enolate attacks a carbonyl carbon forming a beta-hydroxy ketone,
which can further dehydrate into a conjugated enone.
- Diels-Alder Cycloaddition: A conjugated diene reacts with a dienophile (alkene) to form
a new six-membered ring simultaneously.
- Esterification: Carboxylic acids and alcohols merge to form esters, releasing water.
- Michael Addition: Conjugate 1,4-addition where a nucleophile attacks the beta-carbon of
an alpha,beta-unsaturated carbonyl.
- Wittig Reaction: Phosphorus ylides swap with carbonyl oxygens to form specific C=C
geometries.
- Amide/Peptide Bonding: Amines condense with carboxylic acids to form rigid amide bonds.
- Disulfide Bridging: Two S-H groups oxidize to form an S-S bridge, cross-linking
polymers.
5. Isomerization & Rearrangements
- Keto-Enol Tautomerism: Hydrogen rapidly shifts between alpha-carbons and carbonyl
oxygens.
- Sigmatropic Rearrangements: Concerted movement of pi-bonds within a conjugated system
(e.g., Claisen or Cope).
- Aromatic Substitution: Electrophiles replace hydrogens on benzene rings without
breaking the aromaticity.
Geometric Strain & Topology
Triangle Purge (Baeyer Strain)
3-membered rings are detected and destabilized. With 70% probability (reduced to 5% for aromatic),
one bond randomly breaks. Atoms receive 2.0 unit impulse forces to separate. Creates red sparks.
Simulates angle strain (~60° vs ideal 109.5°/120°).
Square Strain
4-membered rings experience torsional strain. With 1% probability per check and 10% final chance, one
bond breaks. Aromatic squares have 80% resistance. Simulates deviation from ideal tetrahedral/planar
angles (~90° vs 109.5°/120°).
Cumulene Instability
Consecutive double bonds (C=C=C) are thermally unstable. With probability 1% × Temperature ×
Reactivity, the central bond breaks. Creates yellow sparks. Simulates steric and orbital overlap strain.
Bond Mechanics
Target Lengths
H bonds: 40px
C bonds: 60px
O bonds: 55px
S bonds: 70px
Aromatic: 0.90× (resonance shortening)
Double: 0.85×, Triple: 0.75×
Stiffness Scaling
Base: 0.4 × BondStiffness
Rings: 8.0 × BondStiffness (capped at 1.0)
Cumulenes: 8.0 × BondStiffness
Disulfide (S-S): 0.85 (slightly weaker)
Multiple Bonds
Detected by counting duplicate indices in bonds[] array.
Single: 1 occurrence
Double: 2 occurrences
Triple: 3 occurrences
💡 Mesomeric Protection: Aromatic rings and conjugated systems are completely
immune to turbulence shear (0.0× flow multiplier). This prevents benzene rings from being torn apart
by fluid forces.
Probe Particle System
Probes are autonomous non-chemical particles that form temporary connections with atoms and each other,
simulating "measurement" effects from external fields.
Probe Behavior
Movement
Steering-based AI (heading + turn speed).
Turn speed: ±0.02 × TimeScale random walk.
Velocity: 90% previous + 10% directional (ProbeVelocity × Temp).
No viscosity damping (retain momentum).
Appearance
Blue triangular "ship" shape (8px × 8px).
Points in heading direction.
Color: hsla(220, 100%, 50%, 0.9) in dark mode.
Connection Mechanics
Atom Connections (Temporary)
- Formation: 5% chance per frame when within 130px of atom
- Lifetime: 60 frames (1 second @ 60 FPS)
- Decay: −1.0 per frame
- Rule: Probes can only connect to ONE atom at a time
- Visual: Dashed lines (5px dash, 5px gap), thickness 0.66px
- Effect: If atom is isolated (0 bonds), probe applies drag force: 0.5 × Temperature
- High Energy: 2% chance × 4.0 (ProbeEnergy) to create glowing cyan connection with
detonation capability
Probe-Probe Connections (Permanent)
- Formation: 5% chance per frame when within 130px of another probe
- Lifetime: 9999 frames (permanent until range exceeded)
- No Decay: Life value stays constant
- Rule: Unlimited probe-probe connections allowed
- Visual: Dashed lines, thickness 0.66px, alpha 1.0 (no fade)
- High Energy: Cannot be high-energy (safety rule)
Range & Cooldown System
Connection Range
Strict 130px limit (16900px²).
Connections beyond this are instantly deleted.
Cooldown
After connection breaks: 45 frames.
After high-energy detonation: 60 frames.
Prevents immediate reconnection.
Visual: Darker gray overlay (rgba(100,100,100,0.5)).
High-Energy Detonation
High-energy probe connections (glowing cyan) have a 10% chance per frame to trigger when connected to an
atom:
- Calls triggerChainReaction() on target atom
- Chain depth determined by Blast Radius setting (50% propagation chance per layer)
- Creates plasma spark burst (12 particles)
- Connection consumed (deleted)
- 60-frame cooldown applied to probe
⚠️ Design Note: This simulates quantum measurement effects where external observation
(probe) can influence system state. High-energy probes represent energetic measurement techniques that can
ionize or break bonds.
Visual Rendering
Standard Connection
Color: rgba(0, 140, 255, 0.8) dark mode
Line width: 0.66px
Dash pattern: [5, 5]
Fades based on life: alpha × (life / maxLife)
High-Energy Connection
Color: rgba(0, 255, 255, 0.9)
Line width: 1.33px
Shadow: blur 10px, color cyan
Dash pattern: [5, 5]
Fades same as standard
Visual Legend
Particle Colors
Colors shift between dark and light themes. Values shown are HSL (Hue, Saturation, Lightness):
Dark Theme
Carbon: hsla(190,
100%, 50%)
Oxygen: hsla(280,
100%, 60%)
Hydrogen: hsla(200,
10%, 80%)
Nitrogen: hsla(140,
100%, 30%)
Sulfur: hsla(55,
100%, 50%)
Phosphorus: hsla(0,
100%, 60%)
Chlorine: hsla(120,
100%, 70%)
Probe: hsla(220,
100%, 50%)
Light Theme
Carbon: hsla(190,
100%, 30%)
Oxygen: hsla(280,
100%, 40%)
Hydrogen: hsla(200,
10%, 30%)
Nitrogen: hsla(140,
100%, 25%)
Sulfur: hsla(55,
100%, 40%)
Phosphorus: hsla(0,
100%, 45%)
Chlorine: hsla(120,
100%, 30%)
Probe: hsla(220,
100%, 40%)
Structure Overlays
Aromatic Rings
Cyan rotating electrons (1 per atom).
15% contraction toward ring center.
Speed: 2.7 seconds/revolution.
Indicates stable π-electron resonance (5–6 atom cycles).
Conjugated Systems
Flowing cyan electrons along chain.
4-atom minimum (C=C-C=C pattern).
Electrons flow linearly, not in loops.
Indicates alternating single/double bonds.
Hydrogen Bonds
Thin dashed lines (2px dash, 4px gap).
Color: rgba(200, 255, 255, 0.5) dark mode.
Thickness scales with H-Bond Strength × 10.
Only visible between H-N or H-O pairs at proper angle.
Cumulenes (C=C=C)
Static glowing dots at bond midpoints.
2.0px radius, cyan color.
Pulsing alpha: 0.5 ± 0.3 × sin(time/100).
Shadow blur: 2px cyan.
Indicates unstable consecutive double bonds.
Quantum Visualizations v28.8+
When Orbitals and Chirality are toggled on, the engine dynamically processes atomic hybridization geometries
(sp³, sp², sp) and stereocenters.
sp³ Hybridization (Tetrahedral)
Renders as 4 glowing lobes forming a tetrahedron around the central atom.
sp² Hybridization (Trigonal Planar)
Renders as 3 in-plane sigma lobes and one large perpendicular p-orbital (π-bond
participant).
sp Hybridization (Linear)
Sigma bonds render linearly with two intersecting perpendicular π-electron clouds.
R/S Chirality Labels
Cahn-Ingold-Prelog (CIP) priority is executed up to depth 4. Displays `(R)` or `(S)` labels next
to sp³ stereocenters.
Bond Rendering
Single Bonds
One line at bond center.
Gradient from atom1 color to atom2 color.
Alpha fades with distance (1.0 at 0px, 0.0 at 100px).
Double Bonds
Two parallel lines, ±3px offset perpendicular to bond.
Suppressed visually inside aromatic rings for visual clarity (v28.7).
Triple Bonds
Three parallel lines: center, ±5px offset.
Rare (requires high bond stiffness + stability).
Stress Mode
Overrides gradients with strain color.
Green (0) → Yellow (0.5) → Red (1.0).
Strain = |actual_length − target_length| × 0.5.
Electronegativity & Charge Overlays v28.0+
Electronegativity Bonds
Activated via Show Electronegativity toggle.
Bond gradient shifts: the brighter terminus is the more electronegative atom.
Overrides default atom-color gradients and stress mode.
Useful for visually tracing polar bonds (e.g. C–O, N–H).
Formal Charge Labels
Activated via Show Formal Charges toggle.
Renders +1 or −1 (etc.) next to charged atoms.
Color: red for positive, blue for negative.
Font: 10px monospace, offset from atom center.
Radical Indicators
Activated via Show Radicals toggle.
A small pulsing red dot appears on any atom with an unpaired electron.
Pulse driven by sin(time × 8) for a fast heartbeat effect.
Size: ~2px radius, positioned at atom edge.
Spark Color Reference
Different chemical events produce color-coded spark bursts for instant visual identification:
Reaction Sparks
Red — Peroxide
instability / radical bond
Cyan — Nucleophilic
attack
Orange — Thermal
elimination / acid-base proton transfer
Green — Charge
neutralization (stabilization)
New in v28.3
Orange — Acid-base
proton transfer (neutralization, generic donation, HCl dissociation)
Magenta — Water
autoionization (H₂O + H₂O → H₃O⁺ + OH⁻)
Sky blue — Hydronium
auto-formation (free H⁺ + H₂O → H₃O⁺)
Special Effects
- Plasma Sparks: Small glowing particles (1–4px radius) that fly outward from interaction
sites. Color varies by event type.
- Ripples: Expanding circles from shattering events. White/black depending on theme, 1px
stroke, fade over 50 frames.
- Valency Ghosts: Small dots orbiting atoms with unfilled valence shells (8px orbit,
1.5px size).
- Charge Labels: '+' or '−' symbols near charged atoms (10px monospace font, red for +,
blue for −).
Heatmap Mode
When enabled, particle colors are replaced by velocity-based heatmap:
- Intensity = min(1, speed / 5.0)
- Hue = 240 × (1 − intensity)
- Blue (240°) = stationary
- Cyan (180°) = slow
- Green (120°) = medium
- Yellow (60°) = fast
- Red (0°) = very fast (> 5 units/frame)
Architecture & Algorithms
Core Systems
Deterministic PRNG
32-bit xorshift-multiply algorithm.
Seed: User-configurable or random.
Formula: t = seed + 0x6D2B79F5; t = imul(t ^ (t >>> 15), t | 1); ...
Enables reproducible simulations from seed alone.
Perlin Noise (3D)
Gradient noise for turbulence.
256-element permutation table (shuffled at init).
Fade function: t³(t(6t − 15) + 10)
Trilinear interpolation of 8 gradient vectors.
Spatial Hash Grid
4096 fixed buckets (2¹² = 4096).
Hash: ((x × 73856093) ^ (y × 19349663)) & 4095
Cell size: 150px default (adjustable 50–300px).
9-cell neighborhood search (3×3 grid).
Reduces collision checks from O(N²) to O(N).
Disjoint Set Union (DSU)
Tracks molecular identity.
Path compression: findRoot() flattens tree.
Union by rank: Always attach smaller to larger.
Amortized O(α(N)) ≈ O(1) operations.
Physics Integration
Semi-Implicit Euler
Symplectic integrator.
Update order: forces → velocity → position.
Preserves energy better than explicit Euler.
Timestep: dt = 1.0 × TimeScale × Temperature
Constraint Solver
4 iterations per frame for bond constraints.
Positional correction + velocity damping.
Mass-weighted displacement: Δx ∝ m₂/(m₁+m₂)
Edge Repulsion
100px margin from boundaries.
Quadratic force: F = 0.08 × Temp × ((margin − dist) / margin)²
Prevents particles from clustering at edges.
Structural Detection
Cycle Detection (DFS)
Depth-first search with backtracking.
Max depth: 6 atoms.
Valid rings: 5–6 atoms (only C or N).
Validation: All atoms must have ≤3 unique neighbors.
Conjugation Detection
Scans for C=C-C=C patterns.
Starts from double-bonded carbons.
Follows single-bond → checks for next double.
Min length: 4 atoms.
Cumulene Detection
Identifies C=C=C (consecutive doubles).
Checks atoms with exactly 2 neighbors.
Both neighbors must have 2+ bonds to current atom.
Geometry Enforcement
VSEPR (Ghost Struts)
Enforces ideal bond angles.
2 neighbors: 180° (linear) or 105° (bent for O/S)
3 neighbors: 120° (trigonal) or 107° (pyramidal for N/P)
4 neighbors: 109.5° (tetrahedral) enforced as 90°
Uses virtual spring forces between non-bonded neighbors.
Ring Optimization
Centers ring atoms around centroid.
Target radius: R = bond_length / (2 × sin(π/n))
Force: 0.8 × radial deviation.
Creates perfectly regular polygons.
Linearity Enforcement
For atoms with 2 neighbors bonded by 2–3 bonds each.
Pulls atom toward midpoint of neighbors.
Force: 0.1 × deviation.
Creates straight C=C=C or C≡C geometries.
Update Scheduling v28.0+
Systems run at different intervals to balance accuracy against performance. All intervals are in frames at 60
FPS.
Every Frame (60 Hz)
Physics integration (forces → vel → pos)
Bond constraint solving (4 iterations)
Hybridization / steric hindrance
Hydrogen bonding forces
Lennard-Jones intermolecular repulsion
Probe connection range checks
Every 10 Frames (6 Hz)
Organic reactions (peroxide, carbonyl, elimination)
Triangle purge / square strain
Aromatic seek (ring closure)
Cumulene instability checks
Every 30 Frames (2 Hz)
Full structure detection (rings, conjugation, cumulenes)
Formal charge + radical recalculation
pH update (H₃O⁺ / OH⁻ scan)
Every 45 Frames (~1.3 Hz)
autoFormHydronium() — free H⁺ + H₂O → H₃O⁺
solveAcidBase() — neutralization, proton donation, autoionization, HCl
dissociation
Every 60 Frames (1 Hz)
Stabilization system — scans all molecules, attempts charge and radical
rearrangement
Molecule name detection — formula matching against database
- Configurable FPS Cap: Server-side via
CHAOS_FPS_CAP constant — or live at runtime via CHAOS_API.fpsLimit = 0 (0 = uncapped)
- SoA Physics Kernel: All particle state in flat TypedArrays — sequential memory access eliminates GC and maximizes cache hit rate
- Pre-allocated Scratch Buffers: Ring solver uses
Uint16Array(64) / Float64Array(64) per-frame — zero allocations in hot path
- WebGL2 Instanced Bond Draw: Single
drawArraysInstanced() replaces N gradient stroke calls
- Bitmask Aromatic Flags:
(_flagsBuf[i] & FLAG_IS_AROMATIC) — bitwise op vs object property lookup
- Task Breaking (TBT): Physics dispatched via
setTimeout(0) after draw — splits render and physics into separate browser tasks, reducing Total Blocking Time
- Reaction Throttling: Chemistry evaluated every 10 frames (6 Hz)
- Structure Detection: Runs every 30 frames (2 Hz)
- Trail Subsampling: Records position every 4 frames, max 60 points
- High Performance Mode: Auto-engages below 24 FPS (2-second window)
- Grid-Based Culling: Only checks particles in adjacent 9-cell neighborhood
- Rearrangement Cap: All reactive systems share a hard limit of 5 events per frame
Memory Architecture v32.0
SoA Physics Buffers
Particle state split into flat TypedArrays: Float64Array for x/y/vx/vy, Uint16Array for bond indices, Uint32Array for bitmask flags.
Sequential memory layout — cache-line friendly for all inner loops.
Max capacity: 3000 particles pre-allocated at init.
Ring Solver Scratch Buffers
Pre-allocated Uint16Array(64) (_rsIdx) and Float64Array(64) (_rsFx, _rsFy).
Reused every frame — zero GC pressure in constraint hot path.
Grid Buckets
4096 arrays of particle references. Cleared and rebuilt every frame.
Memory: ~16 KB for pointers.
Spark/Ripple Arrays
Transient effects stored separately.
Auto-delete when alpha ≤ 0 or life ≤ 0.
Typical count: < 50 objects.
Batched Rendering Architecture v32.0
To bypass the high CPU overhead of the Canvas2D API's createLinearGradient and individual stroke() calls, the engine utilizes a custom data-oriented batching system.
Architecture
Bond coordinates are computed and pushed into 1D Float32Array memory pools.
Bonds are grouped by elemental type (e.g., all C-C bonds, all O-O bonds) to minimize context switching.
Batched Draw Call
The renderer executes a single continuous beginPath() / moveTo() / lineTo() / stroke() sequence per element type, utilizing a unified semi-transparent color.
Reduces draw call overhead by over 95%, keeping the render loop well under 2ms.
HPC Kernel Profiler v32.0
A built-in telemetry system measures every physics sub-system over a 150-frame rolling window and prints a formatted ASCII table to the browser console.
Kernel Tags
ALU — Arithmetic-intensive loops (movement, constraints, ring solver)
CPU — Branch-heavy control flow (chemistry, structure detection)
BW — Memory bandwidth (intermolecular SoA scan)
XFER — Bus sync (SoA ↔ particle object round-trips)
RAM — Pointer-chasing latency (spatial hash, probe interactions)
Output
Triggered automatically every 150 frames when CHAOS_DEBUG_PERF = true — or live via CHAOS_API.debugPerformance = true.
Reports per-kernel avg time, % share, bar chart, and bottleneck classification (COMPUTE BOUND / MEMORY BOUND).
Rendering Pipeline
- Clear canvas
- Draw grid (if enabled)
- Draw flow field vectors (if enabled)
- Update particle colors (heatmap or type-based)
- Draw trails (if enabled)
- Draw bonds — gradient mode selects between: default color, stress, or electronegativity (v28.0)
- Draw hydrogen bonds (dashed lines)
- Draw probe connections (dashed, fading)
- Draw aromatic electrons (rotating)
- Draw conjugated electrons (flowing)
- Draw cumulene glow (pulsing)
- Draw particles (atoms as circles, probes as triangles)
- Draw formal charge labels (v28.1, if toggle ON)
- Draw radical indicators (v28.0, if toggle ON)
- Draw molecule name labels (if toggle ON, including H₃O⁺/OH⁻)
- Draw valency ghosts (orbiting dots)
- Draw sparks/ripples/click nodes
- Draw pH background tint (if toggle ON)
Engine Internals
This section documents the modular subsystems that support the core simulation — the gamification engine,
the scripted showcase theater, and the HUD architecture.
Event System & Gamification v28.5+
A comprehensive achievement engine tracks over 120 discrete events across
15 categories, powered by a statistics model that records every meaningful interaction in the simulation.
Tier Color System
Common — Gray badge, no glow. ~40% of events.
Uncommon — Green badge, subtle glow. ~25% of events.
Rare — Blue badge, moderate glow. ~15% of events.
Epic — Purple badge, strong glow + gradient background.
Mythic — Gold badge, animated shimmer + particle effect.
Transcendent — Cyan/plasma badge, pulsing aura.
Cosmic — Rainbow gradient, full-screen flash on unlock.
Chemical Showcase Theater
The scripted reaction demonstration system powers the interactive chemistry showcase,
displaying 24 real chemical reactions with deterministic visual outcomes.
Reaction Categories (5)
Organic (14 reactions)
SN1, SN2, E1, E2, Diels-Alder, aldol condensation, esterification, hydrolysis,
Michael addition, Wittig reaction, keto-enol tautomerism, dehydration, amide bonding,
radical polymerization.
Ionic (4 reactions)
Neutralization, proton donation, HCl dissociation, autoionization.
Radical (4 reactions)
Homolytic cleavage, radical propagation, termination, disulfide bridging.
Pericyclic (2 reactions)
Cope rearrangement, sigmatropic shifts.
Redox (2 reactions)
Peroxide decomposition, electronegativity-driven electron transfer.
Phase-State Machine (FSM)
WAIT Phase
Duration: 1–2 seconds.
Engine initializes with per-reaction seed parameters.
Reactant atoms are pre-positioned at calculated spawn points.
APPROACH Phase
Directed velocity impulses push reactants toward each other.
Proximity watchdog polls every 400ms.
If atoms drift apart, nudging forces re-engage.
Director fallback fires if approach exceeds 4–7 second window.
FIRE Phase
Chemistry hooks in the engine handle the actual reaction.
If natural chemistry doesn't trigger, director forces bond changes.
Spark effects and visual feedback confirm reaction occurred.
OBSERVE Phase
Simulation freezes at timeScale = 0.005 (near-pause).
Soft-spring camera pan (4% per frame) centers the product cluster.
BFS-walked product overlay: pulsing dashed-ring highlighting.
Transparent overlay canvas renders product labels.
Isolation Architecture
- iframe Sandbox: Each reaction runs in a dedicated
<iframe> with its
own Chaos Engine instance — fully isolated from the main simulation.
- Per-Reaction Configuration: Temperature, atom ratios, pH, seed, and particle count are
set independently for each reaction to guarantee optimal viewing conditions.
- Spawn Geometry: Reactant atoms are placed at calculated distances with directed
velocities,
guaranteeing collisions within 3–8 seconds regardless of seed.
- Proximity Watchdog: A 400ms polling interval monitors inter-atom distances. If
reactants
drift beyond threshold, gentle corrective forces re-engage.
- Director Fallback: If the engine's stochastic chemistry hasn't triggered the reaction
within the scheduled window, the director programmatically forces approach phase — ensuring every
showcase completes reliably.
🎬 Design Philosophy: The showcase system is designed to always produce a visible
reaction, even under adverse stochastic conditions. The layered fallback approach (natural chemistry →
proximity nudging → director override) ensures 100% completion rate while maintaining visual authenticity.
HUD & UI Architecture
The Head-Up Display is a modular control panel that exposes 50+ engine parameters
via an on-demand lazy-loaded architecture.
Loading Architecture
Lazy Injection
UI module (chaos-engine-ui-org.js) loads on-demand.
Triggered by first ⚙ gear button click.
Initial bundle contains zero UI code — only the gear button.
Script injection uses dynamic <script> with nonce for CSP compliance.
Initialization Sequence
1. Create HUD container with all slider/toggle DOM elements.
2. Bind each control to CHAOS_API.state properties.
3. Restore collapse states from sessionStorage.
4. Attach resize listener for responsive layout switching.
Control Groups
Physics Controls
Temperature, viscosity, turbulence, bond stiffness, crowding,
expansion force, time dilation, atom count.
Chemistry Controls
Reactivity, H-bond strength/limit, probe velocity/energy,
probe blast radius, thermal zones.
Visualization Controls
Show FPS, spatial grid, heatmap, trails, flow field, stress,
electronegativity, formal charges, radicals, molecule names,
chirality, orbitals, pH background, events overlay.
Atom Ratios
Individual sliders for C, H, O, N, P, S, Cl, Br, Probe.
Auto-balancing: all ratios always sum to 100%.
FPS Display
Current FPS (1-second rolling average).
Average frame time (ms) over 60-frame window.
P95 frame time — 95th percentile worst-case.
Frame Histogram
60-bar histogram of recent frame times.
Green bars: < 17ms (60 FPS target).
Yellow bars: 17–33ms (30+ FPS).
Red bars: > 33ms (below 30 FPS).
pH Meter
Gradient bar: red (pH 0) → green (pH 7) → blue (pH 14).
Sliding triangle indicator tracks live pH value.
Numeric readout with 1-decimal precision.
Responsive Behavior
- 1400px+: Full side panel with all controls visible.
- 1200px–1400px: Compressed layout, smaller slider labels.
- 1024px–1200px: Two-column grid for parameter groups.
-
< 1024px (mobile): Bottom-sheet overlay with enlarged touch targets (34px),
simplified diagnostics (histogram only), and swipe-to-dismiss.
- Pin Toggle (📌): Keeps HUD open when mouse leaves the panel area.
- Collapsible Groups: Each control group remembers its collapse state per session.
Hit Testing
Rate-limited at 50ms (20 checks/second max).
Searches nearest particle within 40px of cursor.
Only displays for recognized molecules (database match).
Tooltip Content
Molecular formula (Hill notation).
Common name from database.
Displays on transparent floating <div> with CSS pointer-events: none.
Advanced Features & Tips
Configuration Export/Import System
The engine supports full state serialization using Base64-encoded JSON snapshots.
{
"version": "32.0",
"timestamp": 1704067200000,
"settings": {
"seed": 12345,
"atomCount": 250,
"temp": 0.5,
"ratios": { "C": 25, "H": 20, ... },
"showElectronegativity": false,
"showFormalCharges": false,
"showRadicals": false,
...
},
"particles": [
{
"x": 512.3, "y": 384.7,
"vx": 0.12, "vy": -0.34,
"type": "C", "isAtom": true,
"bonds": [1, 5, 12], "id": 0,
"ringState": 6, "isAromatic": true,
"formalCharge": 0, "isRadical": false,
"isHydronium": false, "isHydroxide": false,
...
},
...
],
"uidCounter": 256
}
Import Behavior
- Seed-Only: If input is pure digits (e.g., "12345"), treats as seed and generates new
random simulation
- Full Snapshot: If Base64-encoded JSON, restores exact particle positions, velocities,
bonds, and all settings
- Validation: Invalid codes show alert "Invalid Configuration Code"
- UI Refresh: Automatically updates all sliders to match imported settings
Hidden Mechanics & Easter Eggs
Benzene Spawn
Every reset spawns 1 benzene molecule at center.
6 carbons in hexagon (50px radius).
6 hydrogens at 90px radius.
All velocities set to zero (stable seed structure).
Central Gravity
Inactive atoms far from center (> 500px) experience weak pull.
Activates if velocity < 0.5 units/frame.
Force: 15.0 × Temp / distance²
Prevents permanent edge clustering.
Thermal Wandering
All atoms receive sine wave forces.
Angle = (time × 0.2) + (moleculeID % 100)
Magnitude: 0.002 × Temperature
Prevents complete stillness at low temps.
Flow Field Boost
Hidden 50× amplification on turbulence slider.
Actual wind = windScale × 50 × 500 magnitude
Without this, fluid effects would be imperceptible.
Debugging & Development
Evolution Achievement Tracker
The engine secretly tracks 14 target molecules in the background.
Targets include: `H2`, `O2`, `N2`, `CO2`, `H2O`, `CH4`, `NH3`, `C2H6`, `C2H4`, `C2H2`, `C6H6`,
`HCl`, `HBr`, `C3H8`.
Detected formations are beamed directly to the `window.CHAOS_EVENTS` API for UI overlays and
trophy tracking. All 30 organic reaction triggers are also piped to this tracker.
Console API
window.CHAOS_API.state — Access all parameters
window.CHAOS_API.initParticles(seed) — Reset with seed
window.CHAOS_API.exportConfig() — Get Base64 code
window.CHAOS_API.importConfig(code) — Load snapshot
window.CHAOS_API.getDiagnostics() — Real-time stats
Performance Monitoring
FPS display shows: Current FPS, Avg frame time, P95 frame time
Histogram: Green (< 17ms), Yellow (17–33ms), Red (> 33ms)
Diagnostics panel: Atom count, Probe count, Interactions, Grid buckets
High Performance Mode
Triggers via 2-second rolling FPS window below 30 FPS (sustained)
Disabled by default
Effects: Simplified bond rendering, disabled valency ghosts, no cumulene glow
Mobile Optimizations
- Auto-Scaling: 0.55× scale multiplier for all distances and radii
- Reduced Particles: Default 150 atoms (vs 250 desktop)
- Slower Flow Morphing: 0.4× time factor for turbulence evolution
- UI Adjustments: Larger touch targets (34px gear button), bottom-centered menu
- Diagnostics Hidden: FPS panel hides detailed diagnostics on mobile (histogram only)
Common Workflows
Creating Stable Molecules
Set Temperature to 50 K (low kinetic energy)
Set Viscosity to 0.05 (high damping)
Set Turbulence to 0.001 (minimal flow)
Set Reactivity to 0.5 (moderate bonding)
Use Pull mouse mode to bring atoms together slowly
Once bonded, increase Bond Stiffness to 0.9
Observing Acid-Base Equilibrium
Set O ratio to 20%, H ratio to 25% (water-rich)
Set Temperature to 120 K (moderate motion)
Enable Show pH Background and Show Molecule Names
Watch pH oscillate as autoionization creates ions and neutralization destroys them
Increase Cl ratio to 5%+ to shift pH acidic via HCl dissociation
Observing Aromatic Formation
Set high Carbon ratio (40%+)
Set Nitrogen to 10% (helps close rings)
Set Temperature to 150 K (moderate motion)
Wait for 4–5 carbon chains to form
Aromatic Seek may pull endpoints together
Watch for cyan rotating electrons when ring closes
High-Energy Chaos Mode
Set Temperature to 400 K (maximum)
Set Probe Energy to 10%
Set Probe ratio to 40%
Set Blast Radius to 50
Use Destroy mouse mode for manual detonations
Enable Heatmap to see velocity distribution
Watch cascade reactions propagate
⚠️ Performance Warning: Cell sizes below 100px can cause physics instability due to
particles occupying multiple cells. Stick to 150–200px for best results.
Known Quirks & Gotchas
- Rejoin Cooldown: After thermal elimination, ejected H/Cl atoms have 120-frame cooldown.
They can't rebond immediately. HCl dissociation gives Cl⁻ a 90-frame cooldown separately.
- Aromatic Immunity: Benzene rings resist 80% of triangle purge attempts and 100% of
turbulence shear.
- Probe Cooldown Visualization: Gray overlay means probe is in cooldown (can't form new
connections).
- Grid Reset Required: Changing atom count doesn't take effect until "Flip Table" is
pressed.
- Configuration Persistence: Settings are NOT saved to localStorage (unlike theme
preference). Use export code to save states.
- Seed Determinism: Same seed = same initial positions, but reactions are still
stochastic. Two runs may diverge after ~10 seconds.
- Acid-Base Rate Limiting: Neutralization, proton donation, autoionization, and HCl
dissociation all share the 5-rearrangements-per-frame cap with the stabilization system. In very dense
ion-heavy systems, some reactions queue for the next cycle.
- pH Smoothing: At neutral balance, pH exponentially decays toward 7 (factor 0.95/frame)
rather than jumping. This prevents flickering.
Accessibility & Motion Safety
The Chaos Engine implements a comprehensive accessibility layer that respects user preferences
and ensures the simulation never causes discomfort or unwanted resource consumption.
Motion Safety (prefers-reduced-motion)
OS Preference Detection
Queries prefers-reduced-motion: reduce media query at startup.
When active: animation loop does not start — zero CPU consumed.
Canvas remains blank until user explicitly opts in.
No background timers, requestAnimationFrame calls, or physics ticks run.
Opt-In Banner
A non-dismissible banner appears: "Animations are paused (prefers-reduced-motion)."
Contains a single "Enable Animation" button.
Only clicking this button starts the simulation loop.
Banner cannot be removed via DOM manipulation (re-injects on removal).
Zero-CPU Halt
When motion is reduced, the engine enters a true halt state:
• No requestAnimationFrame loop running.
• No setTimeout or setInterval timers.
• No event listeners polling for state changes.
• Battery impact: effectively zero.
⚠️ Design Decision: The banner is intentionally non-dismissible. Users with
motion sensitivity set this preference for medical reasons (vestibular disorders, epilepsy).
The simulation should never auto-play for these users — opt-in is the only safe pattern.
- Visibility API: Animation loop pauses when the browser tab is not visible
(
document.hidden), eliminating background CPU usage.
- 60 FPS Cap: Hard frame-rate limit prevents unnecessary GPU cycles on
high-refresh-rate displays (120Hz, 144Hz).
- Adaptive Quality: High Performance Mode automatically reduces visual fidelity
on low-end devices before battery drain becomes significant.
- Idle Startup:
requestIdleCallback with 30ms budget chunks ensures
engine initialization never blocks Largest Contentful Paint or First Input Delay.