Configuration Manual
Access the HUD via the ⚙ icon (bottom-right). Click the 📌 pin icon to keep it open.
System Control
Atom Count
Range: 10 – 1200 particles
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.
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
- Frame Rate Capping: 60 FPS hard limit, skips frames if elapsed < 16.67ms
- 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 after 300 frames of lag (> 20ms/frame for 90
consecutive frames)
- Grid-Based Culling: Only checks particles in adjacent cells (9-cell neighborhood)
- Early Exit: Bond formation checks bail early if valency full or rejoin cooldown active
- Rearrangement Cap: All reactive rearrangement systems (stabilization, hydronium,
acid-base) share a hard limit of 5 events per frame
Memory Management
Particle Pool
Array of objects (not classes).
Properties: x, y, vx, vy, type, bonds[], trail[], ...
Typical size: 250–600 particles = ~50–120 KB.
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.
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)
Advanced Features & Tips
Configuration Export/Import System
The engine supports full state serialization using Base64-encoded JSON snapshots.
{
"version": "28.9",
"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.