Animation · project 31 of 37

Living Dough.

Inside one real dough at true scale: every ingredient, what happens to it at each step, every number traced to a measurement.

Open the project ↗Get the skill and the code
After: Inside one real dough at true scale: starch, gluten, water, yeast, sugar, salt, fat and gas, and what happens to each at every step, with the numbers sourced. Before: A recipe card that says "let rise in a warm place until doubled, 1 to 2 hours" and nothing about why.

BeforeA recipe card that says "let rise in a warm place until doubled, 1 to 2 hours" and nothing about why.

AfterInside one real dough at true scale: starch, gluten, water, yeast, sugar, salt, fat and gas, and what happens to each at every step, with the numbers sourced.

What it is worthYou see what each step does to the dough, with every number tagged measured, lab study, calculated or estimate and linked to its paper, so the next loaf is a decision, not luck. Instead of guessing why the dough did not rise.

More like this: explain hard things in a minute ›

How to use it

  1. Open it. On your first visit a seven-beat walk-through plays by itself; press ▶ Walk me through at the top to see it again.
  2. Tap a step (Mix, First rise, Shape, Proof, Bake, Cool) or press play and drag the timeline. On the left is the bread itself (drag to turn it); the zoom lines lead from the marked spot to the close-up of its inside on the right.
  3. Watch the bars under the close-up: sugar left, yeast working or dead, gluten forming, starch raw or gel, water, salt, fat and gas share, all for this 500 g piece.
  4. Tap an ingredient in the picture or a bar to follow it: the rest fades and the panel opens its amount, its state and where the number comes from.
  5. Open All sources for the full list of papers, with how fully each was read.

Where it helps most

  • Teaching what each ingredient does in bread, with numbers people can check.
  • A kitchen or classroom demo that runs on any phone without an install.
  • A template for showing a process from the inside: one real experiment as the spine, lab studies filling the gaps, every value tagged by how it was obtained.

The idea

I wanted to see the chemistry of dough: what is alive in it, how much of it is yeast, sugar and gluten, and what happens to the whole system over time. Earlier versions were either a convoluted particle cloud or only the outside of the loaf. I asked for it to be scientific and practical: see the inside, see what happens at each point, and show each main ingredient.

The build

Claude rebuilt it around one published lab bake (Puhr & D'Appolonia, Cereal Chemistry 1992: a straight dough of flour, water, sugar, yeast, shortening and salt, divided into 500 g pieces, weighed and measured an hour after baking) and filled in the inside from lab studies: X-ray tomography of bubbles, starch granule sizes (13–35 µm and 2–6 µm), yeast cell size and count (4–10 µm, 8–10 billion per gram), sucrose split within 5 min of mixing, the rate yeast eat sugar (0.32 g per g of yeast per hour) and what it becomes, the dough-to-crumb transition at 55–70 °C, thermocouples in baking bread, pH through a bake. model.js holds every value with a tag and a ledger of 22 sources noting whether each was read in full or only as an abstract. dough.js draws a close-up that is deliberately not to scale for the items (each one is drawn big enough to read, with its real size on its label) but is to scale for gas: the gas cells are sized by bisection until they cover exactly the dough's real gas share, neighbouring cells meet at flat walls, and every ingredient is pushed out of the cells into the walls. Live yeast send CO₂ into the nearest cell, sugar dots disappear as it is eaten, granules swell into gel between 55 and 70 °C. Labels are placed beside the item they name with no overlaps; tapping an item, a bar or a row follows that ingredient. The bread itself sits beside the close-up as a three.js cut-away sized to its real volume (bowl, pan, oven, rack), with a marked spot and zoom lines showing where the close-up is. One six-step rail drives everything and a seven-beat walk-through.

Free to take

Build your own.

Copy the skill, paste it into your own AI, and say what you want different. How to use a skill, step by step ›

Get the skillThe instructions your AI follows. Works in Claude, ChatGPT, Gemini or any other

# Master prompt: Living Dough, one real dough followed step by step

You are a careful researcher and a creative coder. Build a single web page (index.html, one CSS file, a data module and a drawing module; three.js from your own server; no CDN, no inline scripts or styles) that follows ONE real bread dough from mixing to cooling and shows its condition at every step, in 3D, on a phone. Every number on screen must come from a published measurement, be calculated from one, or be labelled as an estimate.

## 1. Pick the spine: one real bake
- Find one lab bake that reports the whole process with numbers: formula, fermentation time and temperature, piece weight, proof, bake time and temperature, loaf weight and volume after baking, crumb moisture. (Used here: Puhr & D'Appolonia 1992, Cereal Chemistry 69:582, straight dough: flour 100, water 69.1, sugar 5, yeast 3, shortening 3, salt 2; 3 h at 30 °C, knocked back at 95 and 145 min; 500 g pieces; 55 min proof at 43 °C; 25 min at about 204 °C; 423.0 g and 2,231 cm³ one hour later; crumb 49.8% water, water activity 0.991.)
- Follow one piece (500 g) all the way, so weight, volume and density stay consistent.

## 2. Fill the gaps with lab studies of similar dough, and tag everything
- Inside the dough: X-ray tomography. After mixing: dough 25 ± 1 °C, density 1.2 g/mL against 1.25 g/mL gas-free (so about 4% air), median bubble radius 22 µm, 600–2,350 bubbles per mm³. Rising: gas share follows an S-curve toward about 0.7 (steepest near 0.27), mean bubble 160 → 980 µm, largest 1.6 mm, cells connect after 30–80 min, walls about 250 µm. Proof: cells 400–830 µm at 64% gas, films under 5 µm at the end.
- Gas and acid: CO₂ and ethanol up to 60 mmol per 100 g flour, nearly linear in time; the pH drop comes from succinic acid, not CO₂. pH through a bake: about 5.3 after mixing, 5.0 after proofing, 5.4 after baking; bread 5.3–5.8.
- Oven: core slow for 10 min, fastest (11.6 °C/min) at 16 min, held at 98 °C; surface to 120 °C then follows the oven; yeast die at 56 °C; crust about 5 mm and 5–10% water; crumb gains 0.4–2.3 points of water.
- Give every value one or more tags: measured (in the spine bake), lab study (similar dough elsewhere), calculated (from measured numbers, show the formula), estimate (joins measurements), not measured (say so, show no number). Keep a source ledger: citation, link, read in full or abstract only, and what each source is used for.
- Use simple, stated relations: volume = weight ÷ (1.25 × (1 − gas share)); gas share of the loaf = 1 − (weight ÷ 1.25) ÷ volume; CO₂ litres from mmol at 24.9 L/mol (30 °C).

## 3. What people see
- The main view is a close-up of one patch of dough, drawn large to read (say so on it): four gas cells sized by bisection until they cover exactly the real gas share, meeting at flat walls (clip each cell by the half-planes it shares with its neighbours); 16 starch granules (shaded lens shapes, swelling into soft gel between 55 and 70 °C), a gluten net of curved links between neighbouring granules that grows with mixing development and stays purple as films round the cells, 7 yeast cells (each standing for about 10 billion; grey once dead) sending CO₂ dots into the nearest cell, dissolved sugar dots whose number follows the sugar left, fat drops that smear as they melt, sugar and salt crystals dissolving early. Every item is pushed out of the gas cells into the walls. A one-line headline per moment says what is happening.
- Under the close-up, a row of eight ingredient bars with the value now (sugar g left, yeast working/dead, gluten %, starch raw/gel, water g, salt, fat solid/melted, gas %); tapping one follows that ingredient.
- Label one example of each ingredient with a leader line; tap one in the view or the list to follow it (everything else fades).
- The bread beside the close-up: a 3D cut-away of the whole dough (half bowl, half pan, oven, rack), sized to its volume, with a marked square on the cut face, dashed zoom lines from it to the close-up, and a tag with temperature and volume.
- A panel: what is happening now and what to check (each check tagged), the ingredients (amount, state, tags, source on tap: starch ≈200 g, gluten-forming protein 19–41 g, water ≈234 g, yeast 66–82 billion cells, sugar left and used with CO₂ and alcohol made, salt 5.5 g, fat 8.2 g, gas share and bubble size), then the whole dough (temperature, size, pH, weight).
- A step rail (Mix, First rise, Shape, Proof, Bake, Cool) with play and a timeline; each step gets the same width.

## 4. Walk-through and finish
- A seven-beat walk-through that moves the real timeline and highlights the row being explained; it plays by itself on a first visit (remember in localStorage inside try/catch) and not when the user prefers reduced motion.
- Dark theme; on phones the scene on top and the card below; no sideways scrolling at 320 px. Check every step for NaN, and that weight, volume and gas agree with each other.
Get the code4 files, exactly as they run on this site · free under the MIT license

Four files, exactly as they run at sghadimi.com/dough, plus three.js from the site's own /vendor folder. model.js holds the bake, the sources, the ingredient amounts and every value with its tag (it runs in Node too); dough.js draws the magnified inside view, the 3D corner view, the panel and the walk-through.

model.js355 lines

Raw file

// Living Dough: the data. One real bake (Puhr & D'Appolonia 1992) followed step by step,
// with the inside of the dough filled in from lab studies of similar lean doughs.
// Every value carries a tag: M measured in this bake, L measured in a lab study of a similar dough,
// C calculated from measured numbers, E estimate that joins measurements. Runs in Node too.

export const SRC = {
  P92: { c: "Puhr, D'Appolonia (1992). Effect of baking absorption on bread yield, crumb moisture, and crumb water activity. Cereal Chemistry 69(5), 582–586.",
    u: "https://www.cerealsgrains.org/publications/cc/backissues/1992/Documents/69_582.pdf", read: "full text",
    what: "The bake we follow: formula, 3 h at 30 °C with knock-backs at 95 and 145 min, 500 g pieces, 55 min proof at 43 °C, 25 min bake at about 204 °C; loaf weight 423.0 g and volume 2,231 cm³ one hour after baking; crumb moisture 49.8% and water activity 0.991 at 2 h." },
  TO15: { c: "Turbin-Orger, Babin, Boller, Chaunier, Chiron, Della Valle, Dendievel, Réguerre, Salvo (2015). Growth and setting of gas bubbles in a viscoelastic matrix imaged by X-ray microtomography: the evolution of cellular structures in fermenting wheat flour dough. Soft Matter 11, 3373.",
    u: "https://doi.org/10.1039/C5SM00100E", read: "full text (accepted manuscript)",
    what: "X-ray scans of lean doughs fermenting for 3 h: dough 25 ± 1 °C after mixing; dough density 1.2 g/mL, starch–gluten matrix 1.25 g/mL; gas share rises on an S-curve toward about 0.7 with its steepest point at 22 to 65 min (gas share about 0.27); mean bubble size 160 → 980 µm, largest about 1.6 mm; bubbles start connecting at 30 to 80 min; cell walls about 250 µm after 1 h; at gas share 0.64 mean cells 400–830 µm." },
  TO12: { c: "Turbin-Orger, Boller, Chaunier, Chiron, Della Valle, Réguerre (2012). Kinetics of bubble growth in wheat flour dough during proofing studied by computed X-ray micro-tomography. Journal of Cereal Science 56(3), 676–683.",
    u: "https://doi.org/10.1016/j.jcs.2012.08.008", read: "abstract",
    what: "From 40 to 180 min of proofing, mean cell width 410 → 675 µm, walls 200 → 230 µm; at the end most cells are connected through films thinner than 5 µm." },
  K16: { c: "Koksel, Aritan, Strybulevych, Page, Scanlon (2016). The bubble size distribution and its evolution in non-yeasted wheat flour doughs investigated by synchrotron X-ray microtomography. Food Research International 80, 12–18.",
    u: "https://doi.org/10.1016/j.foodres.2015.12.005", read: "abstract",
    what: "Median bubble radius 22.1 ± 0.7 µm, 36 min after the end of mixing (dough without yeast)." },
  K15: { c: "Koksel, Aritan, Strybulevych, Page, Scanlon (2015). The bubble size distribution and its evolution in wheat flour doughs investigated by synchrotron X-ray microtomography. AACCI Annual Meeting abstract.",
    u: "https://www.cerealsgrains.org/meetings/mtgpresentations/Pages/2015Abstracts.aspx?LID=2", read: "abstract",
    what: "600 to 2,350 bubbles per mm³ of freshly mixed dough." },
  J13: { c: "Jayaram, Cuyvers, Lagrain, Verstrepen, Delcour, Courtin (2013). Mapping of Saccharomyces cerevisiae metabolites in fermenting wheat straight-dough reveals succinic acid as pH-determining factor. Food Chemistry 136(2), 301–308.",
    u: "https://doi.org/10.1016/j.foodchem.2012.08.039", read: "abstract",
    what: "Ethanol and CO₂ reached up to 60 mmol per 100 g flour; most metabolites rose almost linearly with fermentation time; the pH drop comes mainly from succinic acid made by the yeast, not from CO₂." },
  J14: { c: "Jayaram, Cuyvers, Verstrepen, Delcour, Courtin (2014). Succinic acid in levels produced by yeast during fermentation strongly impacts wheat bread dough properties. Food Chemistry 151, 421–428.",
    u: "https://doi.org/10.1016/j.foodchem.2013.11.025", read: "abstract",
    what: "Yeast make succinic acid up to 1.6 mmol per 100 g flour during fermentation; it makes dough less extensible." },
  PY: { c: "Pyler, as summarised in “Pyler says: the role of pH in bread baking”, Baking & Snack / bakingbusiness.com.",
    u: "https://bakingbusiness.com/articles/48661-pyler-says-the-role-of-ph-in-bread-baking", read: "full article",
    what: "Measured through a sponge-and-dough bake: about pH 5.3 after dough mixing, about 5.0 after floor time and proofs, 5.4 after 30 min of baking." },
  ASPH: { c: "American Society of Baking. pH (analytical methods).", u: "https://asbe.org/?p=12381", read: "full page",
    what: "Typical pH of baker’s yeast bread: 5.3 to 5.8." },
  ASTP: { c: "American Society of Baking. Thermal profiling for baking.", u: "https://asbe.org/?p=12397", read: "full page",
    what: "Dough enters the oven at about 35 °C (proofing temperature); yeast are inactivated at 56 °C; the loaf centre should reach about 93 °C for the crumb to set." },
  PS1: { c: "Purlis, Salvadori (2009). Bread baking as a moving boundary problem. Part 1: Mathematical modelling. Journal of Food Engineering 91, 428–433.",
    u: "https://core.ac.uk/download/516005872.pdf", read: "full text (accepted manuscript)",
    what: "Thermocouples in baking bread: the core warms slowly for 10 min, heats fastest (11.6 °C/min) at 16 min and holds at 98 °C from about 20 min; the surface climbs to 120 °C and then follows the oven; crust ends at 5–10% water; the central crumb gains 0.4 to 2.3 percentage points of water." },
  PS2: { c: "Purlis, Salvadori (2009). Bread baking as a moving boundary problem. Part 2: Model validation and numerical simulation. Journal of Food Engineering 91, 434–442.",
    u: "https://core.ac.uk/download/516035874.pdf", read: "full text (accepted manuscript)",
    what: "Crust about 5 mm thick at the end of baking." },
  J22: { c: "Jha, Sadot, Chevallier, Rawson, Le-Bail (2022). Impact of overhead pressure during mixing on dough and bread. Food and Bioprocess Technology 15, 1896–1906.",
    u: "https://doi.org/10.1007/s11947-022-02846-9", read: "abstract",
    what: "A comparable white bread at 4.29 mL/g had a void fraction of 83%." },
  TI: { c: "Techniques de l’Ingénieur. Production of baker’s yeast by biotechnology, section 1: Saccharomyces cerevisiae yeast (J6013).", u: "https://techniques-ingenieur.fr/en/resources/article/ti452/production-of-baker-s-yeast-by-biotechnology-j6013/v1/saccharomyces-cerevisiae-yeast-1", read: "summary page",
    what: "Yeast cells are ovoid, 4 to 10 µm across; one gram of pressed yeast holds 8 to 10 billion cells." },
  PO94: { c: "Potus, Poiffait, Drapron (1994). Influence of dough-making conditions on the concentration of individual sugars and their utilization during fermentation. Cereal Chemistry 71, 505–508.", u: "https://cerealsgrains.org/publications/cc/backissues/1994/Documents/CC1994a127.html", read: "abstract",
    what: "With yeast, the sucrose in dough falls to zero after 5 min of mixing (split by the yeast’s invertase into glucose and fructose); maltose rises 47-fold after 5 min and 59-fold after 15 min of mixing, depending on the flour’s damaged starch." },
  BJ: { c: "Bakers Journal. Technical talk: how yeast ferments sugar.", u: "https://www.bakersjournal.com/technical-talk-664/", read: "full article",
    what: "Glucose is fermented before fructose; in normal fermentation 1 g of yeast ferments 0.32 g of glucose and fructose per hour; 100 g of glucose gives 48.6 g of alcohol and 46.4 g of CO₂." },
  KK17: { c: "Kumar, Khatkar (2017). Thermal, pasting and morphological properties of starch granules of wheat (Triticum aestivum L.) varieties. Journal of Food Science and Technology 54, 2403–2410.", u: "https://pmc.ncbi.nlm.nih.gov/articles/PMC5502034", read: "full text",
    what: "Large A-type starch granules are lens-shaped, 13–35 µm across; small B-type granules are round, 2–6 µm." },
  HBW: { c: "Figoni. How Baking Works, chapter 5: Wheat flour (Wiley, sample chapter).", u: "https://catalogimages.wiley.com/images/db/pdf/0471268569.excerpt.pdf", read: "sample chapter",
    what: "Starch makes up 68–76% of flour, as granules held in place by chunks of protein; glutenin and gliadin form gluten." },
  CG3: { c: "Cereals & Grains Association. Wheat Flour, chapter 3: Composition of commercial flour.", u: "https://cerealsgrains.org/publications/onlinebooks/handbookseries/wheat/Pages/Chapter3Abstract.aspx", read: "abstract",
    what: "Protein is usually 7–15% of common flour (14% moisture basis)." },
  R10: { c: "Rouillé, Chiron, Colonna, Della Valle, Lourdin (2010). Dough/crumb transition during French bread baking. Journal of Cereal Science 52(2), 161–169.", u: "https://doi.org/10.1016/j.jcs.2010.04.008", read: "abstract",
    what: "Inside baking bread, the dough turns into crumb between 55 and 70 °C, at the moment of maximum loaf expansion; starch gelatinises through that transition and the dough stiffens more than tenfold between 60 and 70 °C." },
  MD22: { c: "Struyf et al., as cited in: Sugar levels determine fermentation dynamics during yeast pastry making (2022). Foods 11, 1388.", u: "https://www.ncbi.nlm.nih.gov/pmc/articles/PMC9140867/", read: "full text",
    what: "White wheat flour carries its own sugars: sucrose 2.16, fructose 0.91, glucose 0.54 and maltose 0.53 mg per g of flour; yeast prefer glucose over fructose and maltose." },
  FG: { c: "Simsek, S. Farinograph (NDSU wheat quality notes).", u: "https://www.ndsu.edu/faculty/simsek/wheat/farinograph.html", read: "full page",
    what: "Peak (development) time: the point of maximum dough consistency, just before the dough starts to weaken." }
};

export const STEPS = [
  { id: "mix",   name: "Mix",        dur: 12,  sub: "12 min · to 25 °C",
    cap: "Flour meets water. Mixing hydrates the gluten proteins, folds in air as tiny bubbles, and warms the dough to about 25 °C." },
  { id: "rise",  name: "First rise", dur: 180, sub: "3 h · 30 °C",
    cap: "Yeast turn sugar into CO₂ and alcohol. The gas cannot start new bubbles, it inflates the ones mixing folded in. The dough is knocked back at 95 and 145 min." },
  { id: "shape", name: "Shape",      dur: 10,  sub: "500 g log",
    cap: "Cut to 500 g and rolled into a log. Shaping presses gas out and splits big cells into many smaller ones." },
  { id: "proof", name: "Proof",      dur: 55,  sub: "55 min · 43 °C",
    cap: "55 min in a warm, humid cabinet. Cells grow until they touch, separated only by thin films, and the dough fills the pan." },
  { id: "bake",  name: "Bake",       dur: 25,  sub: "25 min · 204 °C",
    cap: "Gas expands and the loaf springs up. At 56 °C the yeast die, the crumb sets, the core holds near 98 °C while water boils off and the crust browns." },
  { id: "cool",  name: "Cool",       dur: 60,  sub: "1 h · weighed",
    cap: "Out of the pan. An hour later: 423 g and 2,231 cm³, about 15% lighter and 5.3 times bigger than the dough it came from." }
];
export const START = STEPS.reduce((a, s, i) => (a.push(i ? a[i - 1] + STEPS[i - 1].dur : 0), a), []);
export const TOTAL = START[5] + STEPS[5].dur;

// constants straight from the sources
export const K = {
  mass: 500,          // g, one piece (P92)
  rhoM: 1.25,         // g/cm³ gas-free matrix (TO15)
  rhoD: 1.2,          // g/cm³ mixed dough (TO15)
  loafV: 2231,        // cm³ (P92)
  loafW: 423.0,       // g, 1 h after baking (P92)
  flour: 500 * 100 / 182.2, // g flour in a 500 g piece, from the formula (P92)
  co2: 60,            // mmol per 100 g flour (J13)
  Pmax: 0.7, b: 2.86, c: 0.0263, // S-curve of gas share (TO15 shape: ~0.7 asymptote, ~0.27 at the steepest point)
  proofEnd: 0.69
};
const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));
const lerp = (a, b, t) => a + (b - a) * t;
const smooth = t => { t = clamp(t); return t * t * (3 - 2 * t); };
export const G = t => K.Pmax * Math.exp(-K.b * Math.exp(-K.c * t)); // Gompertz: inflection at Pmax/e ≈ 0.26
const P0 = 1 - K.rhoD / K.rhoM; // 0.04 gas after mixing
const tAt = P => -Math.log(-Math.log(P / K.Pmax) / K.b) / K.c;   // time on the S-curve for a gas share
const KB = 0.2; // gas share just after a knock-back (estimate)
function riseP(m) {
  const a = tAt(KB);
  if (m < 95) return G(m);
  if (m < 97) return lerp(G(95), KB, smooth((m - 95) / 2));
  if (m < 145) return G(m - 97 + a);
  if (m < 147) return lerp(G(145 - 97 + a), KB, smooth((m - 145) / 2));
  return G(m - 147 + a);
}
const PROOF_T0 = tAt(0.1), PROOF_SPEED = (tAt(K.proofEnd) - PROOF_T0) / 55;
const bakeCore = m => 35 + 63 / (1 + Math.exp(-0.737 * (m - 16))); // shape from PS1: slow 10 min, 11.6 °C/min at 16 min, 98 °C plateau
const volFrom = (mass, P) => mass / (K.rhoM * (1 - P));
const Vproof = volFrom(K.mass, K.proofEnd);
const massBake = m => K.mass - (K.mass - K.loafW) * clamp(m / 85);  // between the two weighings
const dRise = P => 160 + 820 * clamp((P - P0) / (K.Pmax - 0.04));  // µm, TO15 160 → 980
const dProof = P => 250 + 350 * clamp((P - 0.1) / (0.64 - 0.1));   // µm, TO15 400–830 at 0.64
const ratio = P => P / (1 - P);

// u: 0..6000, 1000 per step
export function stateAt(u) {
  u = clamp(u, 0, 5999.999);
  const si = Math.floor(u / 1000), f = (u - si * 1000) / 1000, st = STEPS[si], m = f * st.dur;
  const s = { si, f, m, id: st.id, clock: START[si] + m };
  let P, mass = K.mass, V, D, core, pH, bake = 0, crust = 0, rough = 0, gl = 1;
  switch (st.id) {
    case "mix":
      P = P0 * smooth(f / 0.8); D = 44; core = lerp(21, 25, f); rough = lerp(1, 0.05, smooth(f / 0.85)); gl = f; pH = 5.3; break;
    case "rise":
      P = riseP(m); D = dRise(P); core = lerp(25, 30, clamp(m / 60)); pH = lerp(5.3, 5.0, m / 245); break;
    case "shape": {
      const p0 = riseP(180); P = lerp(p0, 0.1, smooth(f / 0.6)); D = lerp(dRise(p0), 250, smooth(f / 0.6)); core = 27; pH = lerp(5.3, 5.0, (180 + m) / 245); break;
    }
    case "proof":
      P = G(PROOF_T0 + m * PROOF_SPEED); D = dProof(P); core = lerp(27, 35, clamp(m / 40)); pH = lerp(5.3, 5.0, (190 + m) / 245); break;
    case "bake": {
      mass = massBake(m);
      V = lerp(Vproof, K.loafV, smooth(m / 14));
      P = 1 - (mass / K.rhoM) / V;
      D = dProof(K.proofEnd) * Math.cbrt(ratio(P) / ratio(K.proofEnd));
      core = bakeCore(m); pH = lerp(5.0, 5.4, m / 25); bake = clamp(m / 25); crust = smooth(m / 20); break;
    }
    case "cool": {
      mass = massBake(25 + m); V = K.loafV; P = 1 - (mass / K.rhoM) / V;
      D = dProof(K.proofEnd) * Math.cbrt(ratio(P) / ratio(K.proofEnd));
      core = lerp(98, 40, smooth(m / 60)); pH = 5.4; bake = 1; crust = 1; break;
    }
  }
  if (V == null) V = volFrom(mass, P);
  Object.assign(s, { P, mass, V, D, core, pH, bake, crust, rough, gl });
  return s;
}

const r0 = (x, d = 0) => x.toLocaleString("en-US", { minimumFractionDigits: d, maximumFractionDigits: d });
export const fmtClock = min => { min = Math.round(min); const h = Math.floor(min / 60), mm = min % 60; return h ? h + " h " + String(mm).padStart(2, "0") + " min" : mm + " min"; };

// The condition card: ordered rows {k,label,v,sub,tags:[{t,s}],why}
export function condition(s) {
  const rows = [], id = s.id, m = s.m;
  const T = (t, ...src) => ({ t, src });
  // temperature
  {
    let v, sub = "", tags, why;
    if (id === "mix") { v = s.f < 0.98 ? "Warming toward 25 °C" : "25 ± 1 °C"; sub = "at the end of mixing"; tags = [T("L", "TO15")]; why = "The lab study measured 25 ± 1 °C at the end of mixing (4 min slow, 8 min fast). Mixing work warms the dough; the starting temperature depends on the water and flour, which were not reported."; }
    else if (id === "rise") { v = "Cabinet 30 ± 1 °C"; sub = "80% humidity"; tags = [T("M", "P92")]; why = "The bake we follow fermented in a cabinet held at 30 ± 1 °C. The dough’s own core temperature was not logged; it drifts from about 25 °C toward the cabinet."; }
    else if (id === "shape") { v = "Not logged"; sub = "bench, room temperature"; tags = [T("N")]; why = "Nobody recorded the dough temperature while dividing and moulding."; }
    else if (id === "proof") { v = "Cabinet 43 ± 1 °C"; sub = "90% humidity"; tags = [T("M", "P92")]; why = "Proofed for 55 min at 43 ± 1 °C and 90% humidity. Dough usually enters the oven at about 35 °C (American Society of Baking)."; }
    else if (id === "bake") {
      v = "Core " + r0(s.core) + " °C"; sub = "oven ≈ 204 °C" + (s.core >= 56 ? " · yeast dead (56 °C)" : "");
      tags = [T("L", "PS1", "ASTP"), T("M", "P92")];
      why = "Oven setting from the bake we follow. The core curve is the measured one from Purlis & Salvadori: slow for 10 min, fastest (11.6 °C/min) at 16 min, then held at 98 °C because water boils off around it. Start at 35 °C and yeast death at 56 °C from the American Society of Baking. Their loaves were smaller and baked at 180 °C, so read the timing as a close guide, not this exact loaf.";
    }
    else { v = "Falling (not logged)"; sub = "from 98 °C toward the room"; tags = [T("N")]; why = "The loaf was weighed and measured one hour after baking; its cooling temperature was not recorded."; }
    rows.push({ k: "temp", label: "Temperature", v, sub, tags, why });
  }
  // surface (bake only)
  if (id === "bake") {
    const sv = Math.min(120, 35 + 85 * m / 14);
    rows.push({ k: "surf", label: "Surface", v: sv >= 120 ? "Above 120 °C" : r0(sv) + " °C", sub: sv >= 120 ? "now following the oven; crust browning" : "climbing steadily", tags: [T("L", "PS1")], why: "Measured at the loaf surface: it climbs almost steadily to 120 °C, then follows the oven. Once the surface is dry and above about 120 °C it can brown." });
  }
  // size
  {
    const x = s.V / volFrom(K.mass, P0);
    let tags = [T("C", "TO15")], why = "Volume = weight ÷ (1.25 g/cm³ × (1 − gas share)). 1.25 g/cm³ is the measured density of the gas-free dough (TO15); the drawing is sized to this volume.";
    if (id === "bake") { tags = [T("M", "P92"), T("E")]; why = "Starts from the proofed volume and ends at the measured loaf, 2,231 cm³. How fast it springs in the first 14 minutes is an estimate."; }
    if (id === "cool") { tags = [T("M", "P92")]; why = "Measured by seed displacement one hour after baking: 2,231 cm³."; }
    rows.push({ k: "size", label: "Size", v: r0(Math.round(s.V / 10) * 10) + " cm³", sub: x < 1.05 ? "about a fist" : "× " + r0(x, 1) + " the mixed dough", tags, why });
  }
  // gas share
  {
    let tags, why, sub = "of the volume is gas";
    if (id === "mix") { tags = [T("C", "TO15")]; why = "Mixed dough weighs 1.2 g/mL and the gas-free matrix 1.25 g/mL, so about 4% of the mixed dough is air folded in by the mixer."; }
    else if (id === "rise") { tags = [T("L", "TO15"), T("E")]; why = "S-curve measured by X-ray: the gas share climbs toward about 0.7 and grows fastest at about 0.27. Each knock-back presses it down; the 20% right after a knock-back is an estimate."; sub = m > 95 ? "after knock-back" + (m > 145 ? "s at 95 and 145 min" : " at 95 min") : sub; }
    else if (id === "shape") { tags = [T("E")]; why = "Moulding degasses the dough; nobody measured by how much. Drawn down to 10%."; }
    else if (id === "proof") { tags = [T("L", "TO15", "TO12"), T("E")]; why = "Fully proofed lean dough reaches about 0.64 to 0.7 gas in X-ray studies. The path from 10% to there in 55 min is the same S-curve, sped up for 43 °C (estimate)."; }
    else { tags = [T("C", "P92"), T("L", "J22")]; why = "Gas = 1 − (weight ÷ 1.25) ÷ volume, from the measured weight and volume. A comparable lab bread at 4.29 mL/g measured 83%."; }
    rows.push({ k: "gas", label: "Gas", v: r0(s.P * 100) + "%", sub, tags, why });
  }
  // bubbles
  {
    let v, sub = "", tags, why;
    if (id === "mix") { v = "≈ 44 µm across"; sub = "600–2,350 bubbles per mm³"; tags = [T("L", "K16", "K15")]; why = "Synchrotron X-ray: median bubble radius 22 µm half an hour after mixing, and 600 to 2,350 bubbles in every cubic millimetre. Too small to see on the cut face; the lens shows them at true size."; }
    else if (id === "rise") { v = "≈ " + r0(Math.round(s.D / 10) * 10) + " µm average"; sub = m < 95 ? "largest about 1.6 mm" : "knock-backs split the big ones"; tags = [T("L", "TO15"), T("E")]; why = "Measured by X-ray: the average bubble grows from 160 to 980 µm over 3 h, the largest reach 1.6 mm, and bubbles start connecting after 30 to 80 min. Drawn in step with the gas share; the split at each knock-back is an estimate."; }
    else if (id === "shape") { v = "≈ " + r0(Math.round(s.D / 10) * 10) + " µm average"; sub = "many small cells again"; tags = [T("E")]; why = "Moulding splits large cells into many small ones. Not measured; drawn."; }
    else if (id === "proof") { v = "≈ " + r0(Math.round(s.D / 10) * 10) + " µm average"; sub = "walls ≈ 230 µm, films under 5 µm"; tags = [T("L", "TO15", "TO12")]; why = "X-ray of proofing dough: mean cells 400–830 µm at 64% gas, walls about 230 µm, and by the end most cells touch through films thinner than 5 µm."; }
    else { v = "≈ " + r0(Math.round(s.D / 10) * 10) + " µm average"; sub = id === "cool" ? "the crumb you slice" : "cells stretch, then set"; tags = [T("C", "TO15"), T("E")]; why = "The X-ray studies found the cell pattern is set at the end of proofing and changes little in the oven. The cells are drawn growing with the gas per gram of dough (calculated), not measured in this loaf."; }
    rows.push({ k: "bub", label: "Bubbles", v, sub, tags, why });
  }
  // CO2 (rise and proof)
  if (id === "rise") {
    const made = K.co2 * (m / 180) * K.flour / 100 * 24.9 / 1000;   // litres at 30 °C
    const held = s.V * s.P / 1000;
    rows.push({ k: "co2", label: "CO₂ made", v: "≈ " + r0(made, 1) + " L so far", sub: r0(held, 2) + " L held in the dough", tags: [T("L", "J13"), T("C")],
      why: "Yeast in a straight dough made up to 60 mmol of CO₂ (and as much alcohol) per 100 g flour, rising almost in a straight line. This piece holds 274 g flour, so about 4 L of gas over 3 h; most dissolves in the dough water or escapes, especially at the knock-backs. Held = volume × gas share." });
  }
  // pH
  {
    let tags = [T("L", "PY", "J13", "J14"), T("E")], why = "Measured through a sponge-and-dough bake: about pH 5.3 after mixing, about 5.0 by the end of the proofs, 5.4 after baking. Drawn as a straight line between. The drop comes mainly from succinic acid made by the yeast (up to 1.6 mmol per 100 g flour), not from CO₂ (Jayaram).";
    if (id === "cool") { tags = [T("L", "PY", "ASPH")]; why = "pH 5.4 after baking in the measured series; baker’s-yeast bread usually sits between 5.3 and 5.8 (American Society of Baking)."; }
    rows.push({ k: "ph", label: "Acidity", v: "pH " + r0(s.pH, 1), sub: id === "cool" ? "bread: 5.3–5.8 is typical" : (id === "bake" ? "rises as heat drives off acid" : "slightly sour, from yeast acids"), tags, why });
  }
  // weight
  {
    let v = r0(s.mass) + " g", sub = "", tags = [T("M", "P92")], why = "The dough was divided into 500 g pieces.";
    if (id === "mix" || id === "rise") { sub = "the share that becomes one loaf"; why = "We follow the 500 g that will become one loaf (the bake divided its dough into 500 g pieces)."; }
    if (id === "bake") { v = "≈ " + r0(s.mass) + " g"; sub = "water leaving as steam"; tags = [T("M", "P92"), T("E")]; why = "500 g in, 423.0 g one hour after baking. In between it is drawn as a straight line; the paper weighed only the ends."; }
    if (id === "cool") { v = (s.f > 0.98 ? "423.0" : "≈ " + r0(s.mass)) + " g"; sub = "lost " + r0(K.mass - s.mass) + " g (" + r0((K.mass - s.mass) / 5, 1) + "%)"; tags = [T("M", "P92")]; why = "Weighed one hour after baking: 423.0 g from a 500 g piece, 15.4% lost, mostly as water."; }
    rows.push({ k: "wt", label: "Weight", v, sub, tags, why });
  }
  // water
  {
    let v = "≈ 46% water", sub = "by weight", tags = [T("C", "P92")], why = "From the formula: 69.1 parts water plus the flour’s own moisture (taken as 14%, the farinograph basis) in 182.2 parts of dough.";
    if (id === "bake") { v = "Crumb ≈ 46%, crust drying"; sub = "crust heading to 5–10%"; tags = [T("L", "PS1")]; why = "In the oven the crust dries to 5–10% water while the centre gains 0.4 to 2.3 points, because steam is pushed inward as well as out (Purlis & Salvadori)."; }
    if (id === "cool") { v = "Crumb 49.8%"; sub = "crust 5–10% · water activity 0.991"; tags = [T("M", "P92"), T("L", "PS1")]; why = "Crumb moisture 49.8% and water activity 0.991 measured 2 h after baking. That is wetter than the ≈46% estimated for the dough; the paper does not give the flour’s own moisture, so part of the gap may be our estimate."; }
    rows.push({ k: "water", label: "Water", v, sub, tags, why });
  }
  // gluten
  {
    let v, sub = "", tags = [T("L", "TO15")], why;
    if (id === "mix") { v = s.f < 0.35 ? "Hydrating" : "Developing a network"; sub = "mixed to peak consistency"; tags = [T("M", "P92"), T("L", "FG")]; why = "Water lets the gluten proteins move; mixing stretches and links them into a network that can hold gas. The bake set its water at the farinograph value minus 3.5 (72.6 − 3.5 = 69.1 parts) and mixed to peak, the most resistant point before the dough starts to weaken."; }
    else if (id === "rise") { v = m > 95 ? "Relaxed, then stretched again" : "Stretched around growing cells"; sub = "walls ≈ 250 µm after 1 h"; why = "Cell walls of starch and gluten thin as the bubbles grow; X-ray measured about 250 µm after an hour. A knock-back relaxes the network and evens out the cells."; }
    else if (id === "shape") { v = "Tightened by moulding"; sub = "a taut skin holds the shape"; tags = [T("E")]; why = "Rolling the log stretches the outer layer into a skin. Not measured."; }
    else if (id === "proof") { v = "Stretched to thin films"; sub = "under 5 µm between touching cells"; tags = [T("L", "TO12")]; why = "By the end of proofing most cells are connected through films thinner than 5 µm; the dough is a sponge of gas, liquid films and a starch–gluten matrix."; }
    else if (id === "bake") { v = s.core < 56 ? "Still stretching" : "Setting with heat"; sub = s.core < 56 ? "oven spring" : "crumb sets, yeast inactivated"; tags = [T("L", "ASTP")]; why = "Until the yeast die at 56 °C and the crumb sets, the warm gas and steam keep stretching the network (oven spring). After that, heat fixes starch and gluten into crumb."; }
    else { v = "Set"; sub = "starch and gluten hold the crumb"; tags = [T("L", "TO15")]; why = "The crumb keeps the cell pattern set in the oven."; }
    rows.push({ k: "glu", label: "Gluten", v, sub, tags, why });
  }
  return rows;
}

// ---------- ingredients: what each one is doing now (per 500 g piece) ----------
export const RECIPE = { flour: K.flour, water: 69.1 * K.flour / 100, sugar: 5 * K.flour / 100, yeast: 3 * K.flour / 100, fat: 3 * K.flour / 100, salt: 2 * K.flour / 100 };
const TOTAL_WATER = RECIPE.water + 0.14 * RECIPE.flour + 0.70 * RECIPE.yeast;   // added + flour (14%) + fresh yeast (70%)
const POOL = RECIPE.sugar * 360 / 342 + (0.54 + 0.91) / 1000 * RECIPE.flour;  // glucose + fructose once the sucrose is split
const RATE = 0.32 * RECIPE.yeast;   // g of sugar per hour (BJ)
const KILL = 15.1;                  // bake minute when the core passes 56 °C
export function extra(s) {
  const id = s.id, m = s.m;
  let H; // hours the yeast have been working
  if (id === 'mix') H = m / 60; else if (id === 'rise') H = (12 + m) / 60; else if (id === 'shape') H = (192 + m) / 60;
  else if (id === 'proof') H = (202 + m) / 60; else if (id === 'bake') H = (257 + Math.min(m, KILL)) / 60; else H = (257 + KILL) / 60;
  const used = Math.min(POOL, RATE * H);
  const alive = !(id === 'cool' || (id === 'bake' && s.core >= 56));
  let rate = 0;
  if (id === 'mix') rate = 0.5; else if (id === 'rise' || id === 'shape') rate = 1; else if (id === 'proof') rate = 1.3; else if (id === 'bake') rate = alive ? 1.3 + 0.5 * clamp((s.core - 35) / 10) : 0;
  const gel = id === 'cool' ? 1 : id === 'bake' ? clamp((s.core - 55) / 15) : 0;
  const fatMelt = id === 'cool' ? 1 : id === 'bake' ? clamp((s.core - 35) / 15) : 0;
  const sucrose = id === 'mix' ? clamp(1 - m / 5) : 0;          // gone after 5 min of mixing (PO94)
  const saltXtal = id === 'mix' ? clamp(1 - m / 2) : 0;         // drawn dissolving in the first 2 min (estimate)
  const dev = id === 'mix' ? smooth(s.f / 0.85) : 1;
  const water = TOTAL_WATER - (K.mass - s.mass);
  return { H, used, left: POOL - used, co2g: used * 0.464, co2L: used * 0.464 / 44 * 24.9, eth: used * 0.486, alive, rate, gel, fatMelt, sucrose, saltXtal, dev, water };
}

export const ING = [
  { k: 'starch', label: 'Starch', col: '#f4ecd8' },
  { k: 'gluten', label: 'Gluten', col: '#9a7cf0' },
  { k: 'water', label: 'Water', col: '#6fb4e6' },
  { k: 'yeast', label: 'Yeast', col: '#e5a53a' },
  { k: 'sugar', label: 'Sugar', col: '#ef6fae' },
  { k: 'salt', label: 'Salt', col: '#cfd8e3' },
  { k: 'fat', label: 'Fat', col: '#f2d64b' },
  { k: 'gas', label: 'Gas', col: '#2c4a6e' }
];

export function ingredients(s) {
  const e = extra(s), id = s.id, T = (t, ...src) => ({ t, src }), rows = [];
  const g = x => r0(x, x < 10 ? 1 : 0) + ' g';
  // starch
  {
    let sub = 'granules held in the gluten', why = 'Starch is 68–76% of flour, so about 190–210 g in this piece. It sits in the dough as granules: large lens-shaped A-type (13–35 µm) and small round B-type (2–6 µm).', tags = [T('L', 'HBW', 'KK17')];
    if (id === 'mix') { sub = 'granules soak up water; broken ones feed sugar'; why += ' Granules damaged in milling are cut by the flour’s own enzymes: maltose in the dough rises about 50-fold in the first 5–15 min of mixing.'; tags.push(T('L', 'PO94')); }
    if (id === 'bake') { sub = e.gel <= 0 ? 'intact, warming' : e.gel < 1 ? 'swelling: dough is turning into crumb' : 'gelatinised: the crumb is set'; why += ' Inside baking bread the dough turns into crumb between 55 and 70 °C: the starch swells and gelatinises and the dough stiffens more than tenfold, which ends the rise.'; tags.push(T('L', 'R10')); }
    if (id === 'cool') { sub = 'gelatinised: it is the crumb'; why += ' It gelatinised between 55 and 70 °C in the oven and now forms the crumb walls.'; tags.push(T('L', 'R10')); }
    rows.push({ k: 'starch', v: '≈ 200 g', sub, tags, why });
  }
  // gluten
  {
    let v = id === 'mix' ? (s.f < 0.35 ? 'Hydrating' : 'Forming a network') : id === 'rise' ? 'Stretched around cells' : id === 'shape' ? 'Tightened' : id === 'proof' ? 'Thin films' : id === 'bake' ? (s.core < 60 ? 'Still stretching' : 'Setting') : 'Set';
    let sub = '19–41 g of protein', tags = [T('L', 'CG3')], why = 'Flour is 7–15% protein, so about 19–41 g here; most of it is gliadin and glutenin, which form gluten once wet.';
    if (id === 'mix') { why += ' Mixing stretches and links them into a network that can hold gas. This bake set its water at the farinograph value minus 3.5 and mixed to peak, the most resistant point before the dough weakens.'; tags.push(T('M', 'P92'), T('L', 'FG')); }
    if (id === 'rise') { why += ' As bubbles grow the gluten stretches into the walls between them; X-ray measured walls about 250 µm thick after an hour.'; tags.push(T('L', 'TO15')); }
    if (id === 'shape') { why += ' Moulding stretches the outer layer into a tight skin. Not measured.'; tags.push(T('E')); }
    if (id === 'proof') { why += ' By the end of proofing most cells touch through films thinner than 5 µm.'; tags.push(T('L', 'TO12')); }
    if (id === 'bake' || id === 'cool') { why += ' Heat stiffens the dough more than tenfold between 60 and 70 °C, setting the network with the starch.'; tags.push(T('L', 'R10')); }
    rows.push({ k: 'gluten', v, sub, tags, why });
  }
  // water
  {
    let sub = 'carries the dissolved sugar and salt', tags = [T('C', 'P92')], why = '69.1 parts water per 100 flour (190 g here), plus the flour’s own moisture (taken as 14%) and the water in fresh yeast (about 70%): about ' + r0(TOTAL_WATER) + ' g in all. Starch and gluten hold part of it; the rest dissolves the sugar, salt and CO₂.';
    if (id === 'bake') { sub = s.core > 95 ? 'boiling off as steam; core held near 98 °C' : 'warming; steam inflates the bubbles'; why += ' In the oven the weight lost is mostly water leaving as steam (a little is CO₂ and alcohol), so it is counted here as water. The crust dries to 5–10% while the centre gains 0.4–2.3 points.'; tags.push(T('L', 'PS1')); }
    if (id === 'cool') { sub = 'crumb 49.8% water (measured at 2 h)'; tags = [T('M', 'P92'), T('C')]; why += ' The crumb measured 49.8% water and water activity 0.991 two hours after baking.'; }
    rows.push({ k: 'water', v: '≈ ' + g(e.water), sub, tags, why });
  }
  // yeast
  {
    const v = e.alive ? '66–82 billion cells' : 'Dead';
    let sub = e.alive ? (id === 'mix' ? 'splitting the sugar' : id === 'proof' ? 'working fastest (warm)' : 'turning sugar into CO₂ and alcohol') : (id === 'cool' ? 'killed in the oven' : 'killed at 56 °C');
    const why = '3 parts fresh yeast per 100 flour is about 8.2 g here; a gram of pressed yeast holds 8 to 10 billion ovoid cells, 4 to 10 µm across. They stop at 56 °C in the oven, about 15 min into this bake.';
    rows.push({ k: 'yeast', v, sub, tags: [T('M', 'P92'), T('L', 'TI', 'ASTP')], why });
  }
  // sugar
  {
    let v = '≈ ' + g(e.left) + ' left', sub = 'used ' + g(e.used) + ' → ' + r0(e.co2L, 1) + ' L CO₂, ' + g(e.eth) + ' alcohol';
    if (id === 'mix' && e.sucrose > 0) { v = g(RECIPE.sugar) + ' sucrose'; sub = 'being split into glucose and fructose'; }
    const why = '5 parts sugar per 100 flour is 13.7 g of sucrose here. With yeast it is all split into glucose and fructose within 5 min of mixing; the flour adds a little of its own. Yeast eat glucose first, about 0.32 g per gram of yeast per hour (2.6 g/h here), and every 100 g gives 46.4 g of CO₂ and 48.6 g of alcohol. Not counted: maltose released from damaged starch, which also feeds them. Warmth speeds this up, so the proof figure is a floor.';
    rows.push({ k: 'sugar', v, sub, tags: [T('M', 'P92'), T('L', 'PO94', 'MD22'), T('C', 'BJ')], why });
  }
  // salt
  rows.push({ k: 'salt', v: g(RECIPE.salt), sub: id === 'mix' && e.saltXtal > 0 ? 'dissolving' : 'dissolved: 2.9% of the added water', tags: [T('M', 'P92'), T('C')], why: '2 parts salt per 100 flour is 5.5 g here, about 2.9% of the 190 g of added water once dissolved. The crystals are drawn dissolving in the first two minutes (estimate).' });
  // fat
  rows.push({ k: 'fat', v: g(RECIPE.fat), sub: e.fatMelt <= 0 ? 'small solid flakes in the dough' : e.fatMelt < 1 ? 'melting' : 'melted, spread through the walls', tags: [T('M', 'P92'), T('E')], why: '3 parts shortening per 100 flour is 8.2 g here, about 2% of the dough by volume. How it sits and when it melts are drawn, not measured.' });
  // gas
  {
    const c = condition(s), gas = c.find(r => r.k === 'gas'), bub = c.find(r => r.k === 'bub');
    rows.push({ k: 'gas', v: gas.v + ' of the volume', sub: bub.v.replace('≈ ', 'bubbles ≈ ').replace(' across', ''), tags: [...gas.tags, ...bub.tags.filter(t => !gas.tags.some(x => x.t === t.t))], why: gas.why + ' ' + bub.why });
  }
  return rows.map(r => ({ ...r, label: ING.find(i => i.k === r.k).label }));
}

export function practical(s) {
  const T = (t, ...src) => ({ t, src });
  return {
    mix: { what: 'Water reaches the flour. Starch granules soak some up, the gluten proteins hydrate and mixing pulls them into a network. The yeast split all the sugar within 5 minutes, and air is folded in as tiny bubbles.',
      check: [{ t: 'Mix to peak: the most resistant point, before the dough starts to weaken.', tags: [T('M', 'P92'), T('L', 'FG')] }, { t: 'Aim for about 25 °C dough at the end of mixing.', tags: [T('L', 'TO15')] }] },
    rise: { what: 'The yeast turn sugar into CO₂ and alcohol, about 2.6 g of sugar an hour in this piece. The CO₂ dissolves in the water first, then inflates the bubbles already there, and the gluten stretches around them.',
      check: [{ t: 'Keep it at 30 °C; it is about twice its mixed size by 95 min.', tags: [T('M', 'P92'), T('C')] }, { t: 'Knock it back at 95 and 145 min.', tags: [T('M', 'P92')] }] },
    shape: { what: 'Pressing and rolling push gas out and split big cells into many small ones. That sets how fine the crumb will be.',
      check: [{ t: 'Cut 500 g pieces and roll into a log for the pan.', tags: [T('M', 'P92')] }] },
    proof: { what: 'Warm and humid, so the yeast work fastest. Cells grow until they touch, and the films between them thin to under 5 µm.',
      check: [{ t: '55 min at 43 °C and 90% humidity.', tags: [T('M', 'P92')] }, { t: 'Ready at about 3 times its mixed size, about 70% gas.', tags: [T('C'), T('L', 'TO15')] }] },
    bake: { what: 'Heat expands the gas and turns water to steam, so the loaf springs. The yeast die at 56 °C. Between 55 and 70 °C the starch gelatinises and the dough becomes crumb, which ends the rise. Then the core holds near 98 °C while water leaves.',
      check: [{ t: 'The centre should reach about 93 °C.', tags: [T('L', 'ASTP')] }, { t: '25 min at about 204 °C.', tags: [T('M', 'P92')] }] },
    cool: { what: 'Steam keeps leaving the loaf. The crumb holds the bubble pattern that was set in the oven.',
      check: [{ t: 'After an hour: 423 g from 500 g, 15.4% lighter.', tags: [T('M', 'P92')] }, { t: 'Crumb at 2 h: 49.8% water.', tags: [T('M', 'P92')] }] }
  }[s.id];
}
dough.js761 lines

Raw file

// Living Dough v4: inside one real 500 g dough, ingredient by ingredient, from mixing to cooling.
// The numbers live in model.js. This file draws the magnified inside view (true scale, about 0.4 mm across),
// the whole dough in 3D in the corner, the step-by-step panel and the walk-through.
import * as THREE from '../vendor/three/three.module.min.js';
import { SRC, STEPS, stateAt, condition, ingredients, practical, extra, ING, fmtClock } from './model.js';

const $ = id => document.getElementById(id);
const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));
const lerp = (a, b, t) => a + (b - a) * t;
const smooth = t => { t = clamp(t); return t * t * (3 - 2 * t); };
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
const SHORT = { P92: "Puhr & D’Appolonia 1992", TO15: "Turbin-Orger et al. 2015", TO12: "Turbin-Orger et al. 2012", K16: "Koksel et al. 2016", K15: "Koksel et al. 2015",
  J13: "Jayaram et al. 2013", J14: "Jayaram et al. 2014", PY: "Pyler (Baking Science)", ASPH: "American Society of Baking, pH", ASTP: "American Society of Baking, thermal profiling",
  PS1: "Purlis & Salvadori 2009, part 1", PS2: "Purlis & Salvadori 2009, part 2", J22: "Jha et al. 2022", FG: "Farinograph notes (NDSU)",
  TI: "Techniques de l’Ingénieur, baker’s yeast", PO94: "Potus, Poiffait & Drapron 1994", BJ: "Bakers Journal, yeast and sugar", KK17: "Kumar & Khatkar 2017",
  HBW: "Figoni, How Baking Works", CG3: "Cereals & Grains Assoc., Wheat Flour ch. 3", R10: "Rouillé et al. 2010", MD22: "Foods 2022 (flour sugars)" };
const TAGN = { M: "measured", L: "lab study", C: "calculated", E: "estimate", N: "not measured" };
const COL = Object.fromEntries(ING.map(i => [i.k, i.col]));

/* ---------------- renderer, scene, lights ---------------- */
const stage = $('stage'), inset = $('inset'), cv = $('scene'), hud = $('hud'), hx = hud.getContext('2d');
let renderer;
try { renderer = new THREE.WebGLRenderer({ canvas: cv, antialias: true, alpha: true }); }
catch (e) { $('insetCap').textContent = 'This browser could not start 3D graphics.'; }
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(34, 1, 0.5, 400);
if (renderer) {
  renderer.setPixelRatio(Math.min(devicePixelRatio || 1, 2));
  renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.05;
  renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFShadowMap;
}
scene.add(new THREE.HemisphereLight(0xfff1dc, 0x241a28, 1.15));
const sun = new THREE.DirectionalLight(0xfff0dd, 2.4);
sun.position.set(-14, 30, 18); sun.castShadow = true; sun.shadow.mapSize.set(1024, 1024);
Object.assign(sun.shadow.camera, { left: -25, right: 25, top: 25, bottom: -25, near: 1, far: 90 }); sun.shadow.bias = -0.0006; sun.shadow.normalBias = 0.05;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xbcd3ff, 0.55); fill.position.set(-20, 8, -14); scene.add(fill);
const ovenLight = new THREE.PointLight(0xff7a2e, 0, 60, 1.4); ovenLight.position.set(5, 18, 2); scene.add(ovenLight);

const bench = new THREE.Mesh(new THREE.CircleGeometry(60, 48), new THREE.MeshStandardMaterial({ color: 0x3a2c2a, roughness: 0.9 }));
bench.rotation.x = -Math.PI / 2; bench.receiveShadow = true; scene.add(bench);

/* ---------------- props: bowl, pan, oven, rack ---------------- */
const bowl = new THREE.Mesh(new THREE.LatheGeometry([
  [0, 0], [6.6, 0], [8.7, 1.6], [10.4, 5], [11.4, 8.6], [11.7, 8.9], [11.0, 8.8], [10.0, 5.3], [8.2, 2.1], [6.2, 0.45], [0, 0.45]
].map(p => new THREE.Vector2(p[0], p[1])), 64, 0, Math.PI), new THREE.MeshStandardMaterial({ color: 0xd8dde3, roughness: 0.32, metalness: 0.05, side: THREE.DoubleSide }));
bowl.castShadow = true; bowl.receiveShadow = true; scene.add(bowl);

const pan = new THREE.Group();
{
  const mat = new THREE.MeshStandardMaterial({ color: 0x9aa0a8, roughness: 0.38, metalness: 0.45, side: THREE.DoubleSide });
  const part = (sx, sy, sz, x, y, z) => { const m = new THREE.Mesh(new THREE.BoxGeometry(sx, sy, sz), mat); m.position.set(x, y, z); m.castShadow = m.receiveShadow = true; pan.add(m); };
  part(10.5, 0.2, 10.8, 5.25, 0.1, 0); part(10.5, 7, 0.2, 5.25, 3.5, 5.3); part(10.5, 7, 0.2, 5.25, 3.5, -5.3); part(0.2, 7, 10.8, 10.4, 3.5, 0);
  // rolled rim
  part(10.5, 0.3, 0.5, 5.25, 7, 5.45); part(10.5, 0.3, 0.5, 5.25, 7, -5.45);
}
scene.add(pan);

const oven = new THREE.Group();
const heatMat = new THREE.MeshStandardMaterial({ color: 0x3a1a10, emissive: 0xff5a1e, emissiveIntensity: 0, roughness: 0.6 });
for (const y of [19, 21]) { const rod = new THREE.Mesh(new THREE.CylinderGeometry(0.35, 0.35, 26, 12), heatMat); rod.rotation.x = Math.PI / 2; rod.position.set(y === 19 ? 3 : 9, 18, 0); oven.add(rod); }
const ovenWall = new THREE.Mesh(new THREE.PlaneGeometry(60, 40), new THREE.MeshStandardMaterial({ color: 0x24140f, roughness: 0.95, emissive: 0x3a1206, emissiveIntensity: 0 }));
ovenWall.position.set(22, 12, 0); ovenWall.rotation.y = -Math.PI / 2; oven.add(ovenWall);
scene.add(oven);

const rack = new THREE.Group();
{
  const mat = new THREE.MeshStandardMaterial({ color: 0x6f747c, roughness: 0.4, metalness: 0.6 });
  for (let z = -7; z <= 7; z += 1.4) { const c = new THREE.Mesh(new THREE.CylinderGeometry(0.08, 0.08, 15, 6), mat); c.rotation.z = Math.PI / 2; c.position.set(5, 1.05, z); rack.add(c); }
  for (const x of [-1.5, 11.5]) { const c = new THREE.Mesh(new THREE.CylinderGeometry(0.12, 0.12, 15, 6), mat); c.rotation.x = Math.PI / 2; c.position.set(x, 0.95, 0); rack.add(c); }
  rack.children.forEach(c => { c.castShadow = true; });
}
scene.add(rack);

/* ---------------- the dough: a lofted half-solid plus its cut face ---------------- */
const NX = 34, NP = 72;
const geo = new THREE.BufferGeometry();
const pos = new Float32Array((NX + 1) * NP * 3), col = new Float32Array((NX + 1) * NP * 3);
{
  const idx = [];
  for (let i = 0; i < NX; i++) for (let j = 0; j < NP; j++) {
    const a = i * NP + j, b = i * NP + (j + 1) % NP, c = (i + 1) * NP + j, d = (i + 1) * NP + (j + 1) % NP;
    idx.push(a, b, c, b, d, c);
  }
  geo.setIndex(idx);
  geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
  geo.setAttribute('color', new THREE.BufferAttribute(col, 3));
}
const doughMat = new THREE.MeshPhysicalMaterial({ vertexColors: true, roughness: 0.62, sheen: 0.5, sheenRoughness: 0.8, sheenColor: new THREE.Color(0xfff4e0), side: THREE.DoubleSide });
const dough = new THREE.Mesh(geo, doughMat); dough.castShadow = true;
const capGeo = new THREE.BufferGeometry();
const capPos = new Float32Array((NP + 1) * 3), capUv = new Float32Array((NP + 1) * 2), capNrm = new Float32Array((NP + 1) * 3);
for (let j = 0; j <= NP; j++) capNrm[j * 3] = -1;
{ const idx = []; for (let j = 0; j < NP; j++) idx.push(NP, (j + 1) % NP, j); capGeo.setIndex(idx); }
capGeo.setAttribute('position', new THREE.BufferAttribute(capPos, 3));
capGeo.setAttribute('uv', new THREE.BufferAttribute(capUv, 2));
capGeo.setAttribute('normal', new THREE.BufferAttribute(capNrm, 3));
const capCanvas = document.createElement('canvas'); capCanvas.width = 1024; capCanvas.height = 1024;
let capTex = new THREE.CanvasTexture(capCanvas); capTex.colorSpace = THREE.SRGBColorSpace; capTex.anisotropy = 4;
const capMat = new THREE.MeshStandardMaterial({ map: capTex, emissive: 0xffffff, emissiveMap: capTex, emissiveIntensity: 0.5, roughness: 0.92, side: THREE.DoubleSide });
const cap = new THREE.Mesh(capGeo, capMat); cap.receiveShadow = true;
const doughG = new THREE.Group(); doughG.add(dough, cap); scene.add(doughG);

// cross-section and taper
const ring = new Float32Array(NP * 2);
function profile(p) { // fills ring[] with (z, yRel) for the full cross-section
  for (let j = 0; j < NP; j++) {
    const th = j / NP * Math.PI * 2, c = Math.cos(th), s = Math.sin(th), n = s >= 0 ? p.nt : p.nb;
    ring[j * 2] = p.W * Math.sign(c) * Math.pow(Math.abs(c), 2 / n);
    ring[j * 2 + 1] = (s >= 0 ? p.Ht : p.Hb) * Math.sign(s) * Math.pow(Math.abs(s), 2 / n);
  }
}
const tau = (u, ne) => Math.pow(Math.max(0, 1 - Math.pow(u, ne)), 1 / ne);
function volumeOf(p) { // full (both halves) volume, cm³
  profile(p);
  let A = 0; for (let j = 0; j < NP; j++) { const k = (j + 1) % NP; A += ring[j * 2] * ring[k * 2 + 1] - ring[k * 2] * ring[j * 2 + 1]; }
  A = Math.abs(A) / 2;
  let I = 0; const n = 60; for (let i = 0; i < n; i++) { const u = (i + 0.5) / n; I += tau(u, p.ne) ** 2 / n; }
  return 2 * p.L * A * I;
}
const SHAPES = {
  round: { L: 1, W: 1, Hb: 0.3, Ht: 0.62, nb: 3.4, nt: 2.1, ne: 2.1 },
  pan: { L: 9.8, W: 5.0, Hb: 0.6, Ht: 0.4, nb: 12, nt: 2.6, ne: 8 }
};
function fitAll(base, V) { const v = volumeOf(base), k = Math.cbrt(V / v); return { ...base, L: base.L * k, W: base.W * k, Hb: base.Hb * k, Ht: base.Ht * k }; }
function fitY(base, V) { const v = volumeOf(base), k = V / v; return { ...base, Hb: base.Hb * k, Ht: base.Ht * k }; }
function mix(a, b, t) { const o = {}; for (const k in a) o[k] = lerp(a[k], b[k], t); return o; }
function shapeFor(s) {
  if (s.id === 'mix' || s.id === 'rise') return { p: fitAll(SHAPES.round, s.V), y: 0.5, where: 'bowl' };
  const LOG = { L: 9.2, W: 4.4, Hb: 4.0, Ht: 3.9, nb: 2.6, nt: 2.2, ne: 3.2 };
  if (s.id === 'shape') {
    const t = smooth(s.f / 0.7);
    const p = fitAll(mix(fitAll(SHAPES.round, s.V), fitAll(LOG, s.V), t), s.V);
    return { p, y: lerp(0.5, 0.2, t), where: t < 0.25 ? 'bowl' : 'pan' };
  }
  if (s.id === 'proof' && s.f < 0.3) {
    const t = smooth(s.f / 0.3);
    return { p: fitAll(mix(fitAll(LOG, s.V), fitY(SHAPES.pan, s.V), t), s.V), y: 0.2, where: 'pan' };
  }
  const p = fitY(SHAPES.pan, s.V);
  return { p, y: s.id === 'cool' ? 1.2 : 0.2, where: s.id === 'cool' ? 'rack' : 'pan' };
}
const noise = (x, y, z) => Math.sin(x * 1.7 + 1.3) * Math.sin(y * 2.1 + 0.7) * Math.sin(z * 1.9 + 2.1)
  + 0.55 * Math.sin(x * 4.3 + y * 3.1 + 0.2) * Math.sin(z * 3.9 - y * 2.7)
  + 0.3 * Math.sin(x * 8.9 - z * 7.7 + y * 6.1) + 0.2 * Math.sin(x * 15.1 + z * 13.3 - y * 11.9);
const cDough = new THREE.Color('#e7d2ab'), cFlour = new THREE.Color('#f5efe3'), cCrustA = new THREE.Color('#bf7a35'), cCrustB = new THREE.Color('#7a3a14'), cPale = new THREE.Color('#e9cf9b');
const tmpC = new THREE.Color();
let dims = { W: 5, H: 5, L: 5, Hb: 1, Ht: 1 };
function buildDough(s) {
  const sh = shapeFor(s), p = sh.p;
  profile(p);
  const rough = s.rough, H = p.Hb + p.Ht, roughAmp = rough * Math.max(p.W, H) * 0.16;
  for (let i = 0; i <= NX; i++) {
    const u = Math.sin(Math.PI / 2 * i / NX), x = p.L * u, t = tau(u, p.ne);
    for (let j = 0; j < NP; j++) {
      const z0 = ring[j * 2] * t, yr = ring[j * 2 + 1] * t;
      let y = p.Hb + yr, z = z0, xx = x;
      if (roughAmp > 0.002) {
        const n = noise(x * 0.9, y * 0.9, z * 0.9) * roughAmp + Math.abs(noise(x * 2.6 + 3, y * 2.6, z * 2.6)) * roughAmp * 0.6;
        const L = Math.hypot(z0, yr, u * p.L * 0.3) || 1;
        z += z0 / L * n; y += yr / L * n; if (i > 0) xx += (u * p.L * 0.3) / L * n;
      }
      y = Math.max(0, y);
      const o = (i * NP + j) * 3; pos[o] = xx; pos[o + 1] = y; pos[o + 2] = z;
      // colour
      const top = clamp(yr / (p.Ht || 1)), inPan = sh.where === 'pan' || s.id === 'cool';
      tmpC.copy(cDough);
      if (s.id === 'mix') tmpC.lerp(cFlour, (1 - s.gl) * 0.85 * clamp(0.5 + noise(x * 3, y * 3, z * 3)));
      if (s.crust > 0) {
        const k = s.crust * (inPan ? lerp(0.55, 1, top) : 1);
        tmpC.lerp(cPale, clamp(k * 1.6)).lerp(cCrustA, clamp(k * 1.4 - 0.25)).lerp(cCrustB, clamp(k * top * 1.5 - 0.35) * s.crust);
      }
      col[o] = tmpC.r; col[o + 1] = tmpC.g; col[o + 2] = tmpC.b;
    }
  }
  geo.attributes.position.needsUpdate = true; geo.attributes.color.needsUpdate = true; geo.computeVertexNormals(); geo.computeBoundingSphere();
  // cut face from ring i = 0
  const m = 0.4, w = 2 * p.W + 2 * m, h = H + 2 * m;
  let cy = 0, cz = 0;
  for (let j = 0; j < NP; j++) {
    const zz = pos[j * 3 + 2], yy = pos[j * 3 + 1];
    capPos[j * 3] = 0; capPos[j * 3 + 1] = yy; capPos[j * 3 + 2] = zz; cy += yy; cz += zz;
    capUv[j * 2] = (zz + p.W + m) / w; capUv[j * 2 + 1] = (yy + m) / h;
  }
  cy /= NP; cz /= NP;
  capPos[NP * 3 + 1] = cy; capPos[NP * 3 + 2] = cz; capUv[NP * 2] = (cz + p.W + m) / w; capUv[NP * 2 + 1] = (cy + m) / h;
  capGeo.attributes.position.needsUpdate = true; capGeo.attributes.uv.needsUpdate = true; capGeo.computeBoundingSphere();
  doughG.position.y = sh.y;
  dims = { W: p.W, H, L: p.L, Hb: p.Hb, Ht: p.Ht, m, w, h, where: sh.where, y: sh.y };
  bowl.visible = sh.where === 'bowl'; pan.visible = sh.where === 'pan'; rack.visible = sh.where === 'rack';
}

/* ---------------- crumb drawing (cut face and lens) ---------------- */
/* ---------------- cut face of the 3D dough ---------------- */
let seed = 7; const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
const POOL = 26000, SIG = 0.5, EF2 = Math.exp(SIG * SIG);
const px = new Float32Array(POOL), py = new Float32Array(POOL), pf = new Float32Array(POOL);
for (let i = 0; i < POOL; i++) {
  px[i] = rnd(); py[i] = rnd();
  const z = Math.sqrt(-2 * Math.log(rnd() + 1e-9)) * Math.cos(2 * Math.PI * rnd());
  pf[i] = Math.exp(SIG * z - SIG * SIG / 2);
}
const grain = document.createElement('canvas'); grain.width = grain.height = 128;
{ const g = grain.getContext('2d'), d = g.createImageData(128, 128); for (let i = 0; i < d.data.length; i += 4) { const v = 120 + rnd() * 135; d.data[i] = v; d.data[i + 1] = v * 0.93; d.data[i + 2] = v * 0.8; d.data[i + 3] = 26; } g.putImageData(d, 0, 0); }
function palette(s) {
  const baked = s.id === 'cool' ? 1 : s.id === 'bake' ? smooth((s.m - 10) / 10) : 0;
  return {
    wall: `rgb(${lerp(234, 243, baked) | 0},${lerp(219, 231, baked) | 0},${lerp(186, 198, baked) | 0})`,
    hole: `rgba(${lerp(170, 196, baked) | 0},${lerp(140, 168, baked) | 0},${lerp(98, 118, baked) | 0},0.92)`,
    deep: `rgba(${lerp(122, 150, baked) | 0},${lerp(96, 118, baked) | 0},${lerp(64, 76, baked) | 0},0.95)`,
    rim: `rgba(${lerp(126, 150, baked) | 0},${lerp(98, 116, baked) | 0},${lerp(62, 74, baked) | 0},0.55)`,
    lit: 'rgba(255,250,236,0.55)'
  };
}
function drawCells(ctx, w, h, mmPerPx, s, offset = 0) {
  const pal = palette(s);
  ctx.fillStyle = pal.wall; ctx.fillRect(0, 0, w, h);
  ctx.fillStyle = ctx.createPattern(grain, 'repeat'); ctx.fillRect(0, 0, w, h);
  if (s.id === 'mix' && s.gl < 0.5) { // dry flour pockets early in mixing
    ctx.fillStyle = 'rgba(250,246,238,0.8)';
    for (let i = 0; i < 400 * (1 - s.gl * 2); i++) { const r = (0.5 + pf[i] * 1.6) * 0.25 / mmPerPx; ctx.beginPath(); ctx.arc(px[(i + 999) % POOL] * w, py[(i + 999) % POOL] * h, r, 0, 7); ctx.fill(); }
  }
  const Dpx = s.D / 1000 / mmPerPx, meanA = Math.PI / 4 * Dpx * Dpx * EF2;
  // overlapping circles cover 1 − e^(−sum) of the face; choose the count so the holes cover exactly the gas share (a flat cut shows the same share as the volume)
  const N = Math.min(POOL - offset, Math.round(-Math.log(1 - Math.min(s.P, 0.97)) * w * h / meanA));
  if (N <= 0) return;
  ctx.fillStyle = pal.hole;
  ctx.beginPath();
  for (let i = 0; i < N; i++) { const k = i + offset, r = pf[k] * Dpx / 2; if (r < 0.7) continue; const x = px[k] * w, y = py[k] * h; ctx.moveTo(x + r, y); ctx.arc(x, y, r, 0, Math.PI * 2); }
  ctx.fill();
  if (N < 900) { // few, large cells (the lens): shade each cavity, dark under its top edge, lit at the bottom
    for (let i = 0; i < N; i++) {
      const k = i + offset, r = pf[k] * Dpx / 2; if (r < 5) continue; const x = px[k] * w, y = py[k] * h;
      const g = ctx.createLinearGradient(x, y - r, x, y + r);
      g.addColorStop(0, pal.deep); g.addColorStop(0.55, pal.hole); g.addColorStop(1, pal.wall);
      ctx.fillStyle = g; ctx.beginPath(); ctx.arc(x, y, r * 0.96, 0, Math.PI * 2); ctx.fill();
    }
  }
  // sub-pixel bubbles: specks whose darkness carries their area
  ctx.fillStyle = pal.rim;
  for (let i = 0; i < N; i++) { const k = i + offset, r = pf[k] * Dpx / 2; if (r >= 0.7) continue; ctx.globalAlpha = clamp(r * r * 2.2, 0.08, 0.9); ctx.fillRect(px[k] * w, py[k] * h, 1, 1); }
  ctx.globalAlpha = 1;
  ctx.strokeStyle = pal.rim; ctx.lineWidth = Math.max(0.6, Dpx * 0.05);
  ctx.beginPath();
  for (let i = 0; i < N; i++) { const k = i + offset, r = pf[k] * Dpx / 2; if (r < 1.5) continue; const x = px[k] * w, y = py[k] * h; ctx.moveTo(x + r * Math.cos(3.6), y + r * Math.sin(3.6)); ctx.arc(x, y, r, 3.6, 6.0); }
  ctx.stroke();
  ctx.strokeStyle = pal.lit; ctx.lineWidth = Math.max(0.5, Dpx * 0.035);
  ctx.beginPath();
  for (let i = 0; i < N; i++) { const k = i + offset, r = pf[k] * Dpx / 2; if (r < 2.5) continue; const x = px[k] * w, y = py[k] * h; ctx.moveTo(x + r * Math.cos(0.5), y + r * Math.sin(0.5)); ctx.arc(x, y, r, 0.5, 2.6); }
  ctx.stroke();
}
let capKey = '', capAt = 0;
function drawCap(s, force) {
  const key = [s.si, Math.round(s.P * 150), Math.round(s.D / 8), Math.round(s.crust * 30), Math.round(dims.w * 4), Math.round(dims.h * 4), Math.round(s.gl * 8)].join('|');
  const now = performance.now();
  if (!force && (key === capKey || now - capAt < 120)) return;
  capKey = key; capAt = now;
  const W = 1024, H = clamp(Math.round(W * dims.h / dims.w), 160, 1400);
  if (capCanvas.height !== H) { capCanvas.height = H; capTex.dispose(); capTex = new THREE.CanvasTexture(capCanvas); capTex.colorSpace = THREE.SRGBColorSpace; capTex.anisotropy = 4; capMat.map = capTex; capMat.emissiveMap = capTex; capMat.needsUpdate = true; }
  const ctx = capCanvas.getContext('2d'), mmPerPx = dims.w * 10 / W;
  drawCells(ctx, W, H, mmPerPx, s);
  if (s.crust > 0.01) { // 5 mm crust (Purlis & Salvadori), following the outline
    ctx.save();
    ctx.beginPath();
    for (let j = 0; j < NP; j++) { const X = capUv[j * 2] * W, Y = (1 - capUv[j * 2 + 1]) * H; j ? ctx.lineTo(X, Y) : ctx.moveTo(X, Y); }
    ctx.closePath(); ctx.clip();
    const cpx = 5 * s.crust / mmPerPx;
    ctx.lineJoin = 'round';
    ctx.strokeStyle = 'rgba(214,160,92,0.45)'; ctx.lineWidth = cpx * 3.4; ctx.stroke();
    const g = s.crust;
    ctx.strokeStyle = `rgb(${lerp(214, 132, g) | 0},${lerp(160, 70, g) | 0},${lerp(92, 28, g) | 0})`; ctx.lineWidth = cpx * 2; ctx.stroke();
    ctx.restore();
  }
  capTex.needsUpdate = true;
}
/* ---------------- camera ---------------- */
let yaw = 0.68, pitch = 0.38, zoom = 1;
const target = new THREE.Vector3(), camGoal = new THREE.Vector3(), tgtGoal = new THREE.Vector3();
let camInit = false;
function placeCamera(dt) {
  const D = dims, size = Math.max(D.W * 2 + 4, D.H * 1.6 + 3, D.L + 6, D.where === 'bowl' ? 22 : 16);
  const r = size / (2 * Math.tan(camera.fov * Math.PI / 360)) * 1.0 * zoom;
  tgtGoal.set(D.L * 0.42, D.y + D.H * 0.48, 0);
  camGoal.set(-Math.cos(pitch) * Math.cos(yaw), Math.sin(pitch), Math.cos(pitch) * Math.sin(yaw)).multiplyScalar(r).add(tgtGoal);
  const k = camInit ? 1 - Math.exp(-dt * 4) : 1; camInit = true;
  target.lerp(tgtGoal, k); camera.position.lerp(camGoal, k); camera.lookAt(target);
}
const ptrs = new Map(); let pinch0 = 0, zoom0 = 1;
cv.addEventListener('pointerdown', e => { cv.setPointerCapture(e.pointerId); ptrs.set(e.pointerId, { x: e.clientX, y: e.clientY }); if (ptrs.size === 2) { const [a, b] = [...ptrs.values()]; pinch0 = Math.hypot(a.x - b.x, a.y - b.y); zoom0 = zoom; } });
cv.addEventListener('pointermove', e => {
  const p = ptrs.get(e.pointerId); if (!p) return;
  if (ptrs.size === 1) { yaw = clamp(yaw + (e.clientX - p.x) * 0.006, -0.35, 1.35); pitch = clamp(pitch + (e.clientY - p.y) * 0.005, 0.04, 1.25); }
  p.x = e.clientX; p.y = e.clientY;
  if (ptrs.size === 2) { const [a, b] = [...ptrs.values()]; const d = Math.hypot(a.x - b.x, a.y - b.y); if (pinch0) zoom = clamp(zoom0 * pinch0 / d, 0.45, 2.2); }
});
const up = e => { ptrs.delete(e.pointerId); pinch0 = 0; };
cv.addEventListener('pointerup', up); cv.addEventListener('pointercancel', up);
cv.addEventListener('wheel', e => { e.preventDefault(); zoom = clamp(zoom * Math.exp(e.deltaY * 0.0012), 0.45, 2.2); }, { passive: false });
$('reset').addEventListener('click', () => { yaw = 0.68; pitch = 0.38; zoom = 1; });

/* ---------------- HUD: ruler, temperature tag, lens leader ---------------- */

/* ---------------- the close-up: one patch of dough, few items, drawn large, labelled in place ---------------- */
// Not to scale on purpose: each item is drawn big enough to read, and its real size is on its label.
// What IS to scale: the share of the patch taken by gas equals the dough's real gas share.
const mc = $('micro'), mx = mc.getContext('2d');
let sel = null, mW = 0, mH = 0, hits = [];
const hash = (i, j, k = 0) => { let h = (i * 374761393 + j * 668265263 + k * 1274126177) | 0; h = (h ^ (h >>> 13)) * 1274126177 | 0; return ((h ^ (h >>> 16)) >>> 0) / 4294967296; };
let rs = 11; const R = () => (rs = (rs * 16807) % 2147483647) / 2147483647;
/* Sprites: each ingredient is painted once, shaded, at 128 px, then stamped scaled and rotated. */
function sprite(size, paint) { const c = document.createElement('canvas'); c.width = c.height = size; paint(c.getContext('2d'), size); return c; }
const SP = {};
SP.starch = sprite(128, (g, n) => { // a lens-shaped granule lit from the top left: rim, growth rings, equatorial furrow, highlight
  const c = n / 2, r = n / 2 - 3;
  let gr = g.createRadialGradient(c - r * 0.35, c - r * 0.4, r * 0.05, c, c, r);
  gr.addColorStop(0, '#fffdf7'); gr.addColorStop(0.55, '#f6eedb'); gr.addColorStop(0.9, '#e2d2ad'); gr.addColorStop(1, '#c9b386');
  g.fillStyle = gr; g.beginPath(); g.arc(c, c, r, 0, 7); g.fill();
  g.strokeStyle = 'rgba(205,186,146,.55)'; g.lineWidth = 1.4; for (const q of [0.72, 0.5, 0.3]) { g.beginPath(); g.arc(c + r * 0.04, c + r * 0.05, r * q, 0, 7); g.stroke(); }
  g.strokeStyle = 'rgba(170,146,104,.55)'; g.lineWidth = 2; g.beginPath(); g.moveTo(c - r * 0.8, c + r * 0.08); g.quadraticCurveTo(c, c - r * 0.06, c + r * 0.8, c + r * 0.08); g.stroke();
  g.strokeStyle = 'rgba(140,114,74,.85)'; g.lineWidth = 3; g.beginPath(); g.arc(c, c, r - 1.5, 0, 7); g.stroke();
  gr = g.createRadialGradient(c - r * 0.42, c - r * 0.45, 0, c - r * 0.42, c - r * 0.45, r * 0.38); gr.addColorStop(0, 'rgba(255,255,255,.95)'); gr.addColorStop(1, 'rgba(255,255,255,0)');
  g.fillStyle = gr; g.beginPath(); g.arc(c - r * 0.42, c - r * 0.45, r * 0.38, 0, 7); g.fill();
});
SP.gel = sprite(128, (g, n) => { // swollen, gelatinised: soft-edged, translucent, no rim
  const c = n / 2, gr = g.createRadialGradient(c - 10, c - 12, 4, c, c, n / 2 - 2);
  gr.addColorStop(0, 'rgba(255,250,236,.85)'); gr.addColorStop(0.6, 'rgba(248,236,206,.6)'); gr.addColorStop(1, 'rgba(236,220,186,0)');
  g.fillStyle = gr; g.beginPath(); g.arc(c, c, n / 2 - 2, 0, 7); g.fill();
  g.strokeStyle = 'rgba(196,170,122,.5)'; g.lineWidth = 3; g.setLineDash([7, 6]); g.beginPath(); g.arc(c, c, n / 2 - 14, 0, 7); g.stroke();
});
SP.shadow = sprite(128, (g, n) => { const c = n / 2, gr = g.createRadialGradient(c, c, n * 0.18, c, c, n / 2); gr.addColorStop(0, 'rgba(40,52,60,.45)'); gr.addColorStop(1, 'rgba(40,52,60,0)'); g.fillStyle = gr; g.fillRect(0, 0, n, n); });
SP.blur = sprite(64, (g, n) => { const c = n / 2, gr = g.createRadialGradient(c - 6, c - 6, 2, c, c, n / 2); gr.addColorStop(0, 'rgba(250,244,228,.75)'); gr.addColorStop(0.65, 'rgba(236,226,200,.45)'); gr.addColorStop(1, 'rgba(236,226,200,0)'); g.fillStyle = gr; g.fillRect(0, 0, n, n); });
const yeastSprite = (dead) => sprite(128, (g, n) => { // ovoid cell: cell wall, cytoplasm, vacuole, granules, highlight
  const c = n / 2, r = n / 2 - 4;
  let gr = g.createRadialGradient(c - r * 0.3, c - r * 0.35, r * 0.1, c, c, r);
  if (dead) { gr.addColorStop(0, '#d6d1c8'); gr.addColorStop(0.7, '#a39d93'); gr.addColorStop(1, '#6e6a63'); }
  else { gr.addColorStop(0, '#ffe0a3'); gr.addColorStop(0.6, '#e9a948'); gr.addColorStop(1, '#a96a1c'); }
  g.fillStyle = gr; g.beginPath(); g.arc(c, c, r, 0, 7); g.fill();
  g.strokeStyle = dead ? 'rgba(80,76,70,.9)' : 'rgba(110,64,14,.9)'; g.lineWidth = 4; g.stroke();
  g.fillStyle = dead ? 'rgba(235,232,226,.35)' : 'rgba(255,240,205,.55)'; g.beginPath(); g.ellipse(c + r * 0.15, c + r * 0.1, r * 0.42, r * 0.36, 0.4, 0, 7); g.fill();
  g.fillStyle = dead ? 'rgba(70,66,60,.45)' : 'rgba(120,70,16,.55)';
  for (const [dx, dy, q] of [[-0.45, 0.2, 0.08], [-0.2, 0.5, 0.06], [0.4, -0.45, 0.07], [-0.5, -0.15, 0.05], [0.55, 0.3, 0.05]]) { g.beginPath(); g.arc(c + dx * r, c + dy * r, q * r, 0, 7); g.fill(); }
  gr = g.createRadialGradient(c - r * 0.45, c - r * 0.5, 0, c - r * 0.45, c - r * 0.5, r * 0.35); gr.addColorStop(0, 'rgba(255,255,255,.85)'); gr.addColorStop(1, 'rgba(255,255,255,0)');
  g.fillStyle = gr; g.beginPath(); g.arc(c - r * 0.45, c - r * 0.5, r * 0.35, 0, 7); g.fill();
});
SP.yeast = yeastSprite(false); SP.dead = yeastSprite(true);
SP.fat = sprite(64, (g, n) => { const c = n / 2, gr = g.createRadialGradient(c - 8, c - 9, 2, c, c, n / 2 - 2); gr.addColorStop(0, '#fffbe0'); gr.addColorStop(0.45, '#f3e07e'); gr.addColorStop(1, 'rgba(214,180,60,.0)'); g.fillStyle = gr; g.beginPath(); g.arc(c, c, n / 2 - 2, 0, 7); g.fill(); });
SP.sugar = sprite(32, (g, n) => { const c = n / 2, gr = g.createRadialGradient(c, c, 0, c, c, c); gr.addColorStop(0, 'rgba(255,190,222,1)'); gr.addColorStop(0.35, 'rgba(239,111,174,.85)'); gr.addColorStop(1, 'rgba(239,111,174,0)'); g.fillStyle = gr; g.fillRect(0, 0, n, n); });
SP.co2 = sprite(32, (g, n) => { const c = n / 2, gr = g.createRadialGradient(c - 3, c - 3, 0, c, c, c - 1); gr.addColorStop(0, 'rgba(255,255,255,.95)'); gr.addColorStop(0.5, 'rgba(140,200,250,.75)'); gr.addColorStop(1, 'rgba(70,140,220,0)'); g.fillStyle = gr; g.fillRect(0, 0, n, n); });
const NOISE = sprite(256, (g, n) => { // soft caustic texture for the water
  const d = g.createImageData(n, n);
  for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) {
    const v = Math.sin(x * 0.049 + Math.sin(y * 0.031) * 2.1) * Math.sin(y * 0.043 + Math.sin(x * 0.027) * 1.7) + 0.5 * Math.sin((x + y) * 0.11) * Math.sin((x - y) * 0.083);
    const o = (y * n + x) * 4, t = 128 + v * 60; d.data[o] = t; d.data[o + 1] = t; d.data[o + 2] = t; d.data[o + 3] = 255;
  }
  g.putImageData(d, 0, 0);
});

function stamp(ctx, img, x, y, rx, ry, rot) { const c = Math.cos(rot), sn = Math.sin(rot), d = mc.width / (mW || 1); ctx.setTransform(c * rx * d, sn * rx * d, -sn * ry * d, c * ry * d, x * d, y * d); ctx.drawImage(img, -1, -1, 2, 2); }
// the cast, in patch coordinates (0..1); jittered grid so nothing piles up
const grid = (n, seed) => Array.from({ length: n }, (_, i) => { const c = Math.ceil(Math.sqrt(n * 1.6)), gx = i % c, gy = Math.floor(i / c), r = Math.ceil(n / c); return { u: (gx + 0.5 + (hash(i, seed) - 0.5) * 0.7) / c, v: (gy + 0.5 + (hash(i, seed, 1) - 0.5) * 0.7) / r }; });
const CAST = {
  starch: grid(16, 1).map((p, i) => ({ ...p, big: i % 4 !== 3, rot: hash(i, 7) * Math.PI, e: 0.55 + 0.3 * hash(i, 8) })),
  yeast: grid(7, 2).map((p, i) => ({ ...p, rot: hash(i, 9) * Math.PI, bud: i % 3 === 0, ph: hash(i, 10) * 6.28 })),
  fat: grid(4, 3).map((p, i) => ({ ...p, rot: hash(i, 11) * Math.PI })),
  sugar: grid(28, 4).map((p, i) => ({ ...p, ph: hash(i, 12) * 6.28 }))
};
const BUBS = [{ u: 0.2, v: 0.36, w: 1.25 }, { u: 0.66, v: 0.27, w: 1 }, { u: 0.43, v: 0.8, w: 0.9 }, { u: 0.9, v: 0.76, w: 0.7 }];
function layout(s, W, H) {
  // scale the cells until the share of the patch they cover equals the dough's real gas share (checked on a 48 × 32 grid)
  const P = Math.min(s.P, 0.88), sw = BUBS.reduce((a, b) => a + b.w, 0);
  const at = k => BUBS.map(b => ({ x: b.u * W, y: b.v * H, r: k * Math.sqrt(b.w / sw) }));
  const cover = bubs => { let n = 0; for (let i = 0; i < 48; i++) for (let j = 0; j < 32; j++) { const x = (i + 0.5) / 48 * W, y = (j + 0.5) / 32 * H; if (bubs.some(b => (x - b.x) ** 2 + (y - b.y) ** 2 < b.r * b.r)) n++; } return n / 1536; };
  if (P < 0.003) return at(0);
  let lo = 0, hi = Math.hypot(W, H);
  for (let it = 0; it < 16; it++) { const m = (lo + hi) / 2; if (cover(at(m)) < P) lo = m; else hi = m; }
  return at((lo + hi) / 2);
}
// push a point out of every gas cell: growing bubbles squeeze the ingredients into the walls
function squeeze(x, y, bubs, pad) {
  for (let it = 0; it < 3; it++) for (const b of bubs) { const dx = x - b.x, dy = y - b.y, d = Math.hypot(dx, dy) || 1; if (d < b.r + pad) { x = b.x + dx / d * (b.r + pad); y = b.y + dy / d * (b.r + pad); } }
  return [x, y];
}
const HEAD = s => ({
  mix: s.f < 0.3 ? 'Flour meets water: starch soaks some up, gluten proteins wake up.' : 'Mixing builds a gluten net and traps air as tiny bubbles.',
  rise: s.m > 95 && s.m < 100 || s.m > 145 && s.m < 150 ? 'Knock-back: gas is pressed out, big cells split into small ones.' : 'Yeast eat sugar and breathe out CO₂, which inflates the bubbles.',
  shape: 'Shaping presses gas out and splits the cells: this sets how fine the crumb is.',
  proof: 'Bubbles grow until the walls between them are thin films.',
  bake: s.core < 56 ? 'Heat: gas expands and steam forms, so the loaf springs up.' : s.core < 70 ? 'Yeast are dead. Starch swells into gel: dough is turning into crumb.' : 'The crumb is set. The core holds near 98 °C while water leaves as steam.',
  cool: 'Steam keeps leaving. The bubble pattern you see is the crumb you slice.'
}[s.id]);
function drawMicro(s, e, tnow) {
  const dpr = Math.min(devicePixelRatio || 1, 2), W = mc.clientWidth, H = mc.clientHeight;
  if (!W || !H) return;
  if (mc.width !== Math.round(W * dpr) || mc.height !== Math.round(H * dpr)) { mc.width = Math.round(W * dpr); mc.height = Math.round(H * dpr); }
  mW = W; mH = H;
  const ctx = mx, T = tnow / 1000, reset = () => ctx.setTransform(dpr, 0, 0, dpr, 0, 0); reset();
  const U = Math.min(W, H) / 10;             // drawing unit: a big starch granule is ~1 unit across
  const al = key => (sel && sel !== key) ? 0.14 : 1, gel = e.gel, wet = s.id === 'mix' ? clamp(s.m / 3) : 1;
  const bubs = layout(s, W, H); hits = [];
  ctx.globalAlpha = 1; ctx.globalCompositeOperation = 'source-over';
  // the liquid
  const bg = ctx.createLinearGradient(0, 0, W, H);
  if (gel > 0) { bg.addColorStop(0, `rgb(${lerp(214, 247, gel) | 0},${lerp(232, 235, gel) | 0},${lerp(238, 208, gel) | 0})`); bg.addColorStop(1, `rgb(${lerp(190, 236, gel) | 0},${lerp(214, 218, gel) | 0},${lerp(226, 184, gel) | 0})`); }
  else { bg.addColorStop(0, '#e3eff2'); bg.addColorStop(1, '#c3dbe5'); }
  ctx.fillStyle = bg; ctx.fillRect(0, 0, W, H);
  if (wet < 1) { ctx.fillStyle = `rgba(240,230,206,${(1 - wet) * 0.9})`; ctx.fillRect(0, 0, W, H); }
  ctx.globalAlpha = 0.14; ctx.globalCompositeOperation = 'overlay'; ctx.save(); ctx.translate(Math.sin(T * 0.25) * 8, 0); ctx.fillStyle = ctx.createPattern(NOISE, 'repeat'); ctx.fillRect(-20, -20, W + 40, H + 40); ctx.restore();
  ctx.globalCompositeOperation = 'source-over'; ctx.globalAlpha = 1;
  if (sel === 'water') { ctx.fillStyle = 'rgba(80,160,230,.28)'; ctx.fillRect(0, 0, W, H); }
  // positions after the squeeze
  const pos = (p, pad) => squeeze(p.u * W, p.v * H, bubs, pad);
  const sp = CAST.starch.map(g => { const r = (g.big ? 0.55 : 0.22) * U * (1 + 0.35 * gel); const [x, y] = pos(g, r * 0.9); return { ...g, x, y, r }; });
  // gluten: links between neighbouring granules, joined as mixing develops it; films around the gas cells
  ctx.globalAlpha = al('gluten');
  const links = [];
  sp.forEach((a, i) => { const nb = sp.map((b, j) => [j, Math.hypot(a.x - b.x, a.y - b.y)]).filter(([j]) => j !== i).sort((p, q) => p[1] - q[1]).slice(0, 3); nb.forEach(([j], n) => { if (i < j || n > 1) links.push([a, sp[j], hash(i, j)]); }); });
  const nL = Math.round(links.length * (0.15 + 0.85 * e.dev));
  ctx.lineCap = 'round';
  for (let pass = 0; pass < 2; pass++) {
    ctx.strokeStyle = pass ? (gel > 0.5 ? 'rgba(112,84,186,.95)' : 'rgba(128,96,232,.95)') : 'rgba(140,110,240,.22)';
    ctx.lineWidth = pass ? Math.max(2, U * 0.06) : Math.max(6, U * 0.2);
    ctx.beginPath();
    for (let i = 0; i < nL; i++) { const [a, b, h] = links[i], mxp = (a.x + b.x) / 2 + (h - 0.5) * U * 0.6, myp = (a.y + b.y) / 2 + (hash(i, 3) - 0.5) * U * 0.6; ctx.moveTo(a.x, a.y); ctx.quadraticCurveTo(mxp, myp, b.x, b.y); if (pass && i === 1) hits.push({ k: 'gluten', x: mxp, y: myp, r: U * 0.3 }); }
    ctx.stroke();
  }
  if (e.dev < 0.35) { // loose protein pieces before they join
    ctx.strokeStyle = 'rgba(128,96,232,.9)'; ctx.lineWidth = Math.max(2, U * 0.07);
    for (let i = 0; i < 14; i++) { const x = hash(i, 21) * W, y = hash(i, 22) * H, a = hash(i, 23) * 6.28; ctx.beginPath(); ctx.moveTo(x, y); ctx.quadraticCurveTo(x + Math.cos(a) * U * 0.5, y + Math.sin(a + 1) * U * 0.5, x + Math.cos(a) * U, y + Math.sin(a) * U); ctx.stroke(); if (i === 0) hits.push({ k: 'gluten', x, y, r: U * 0.4 }); }
  }
  // starch granules
  for (const g of sp) {
    ctx.globalAlpha = al('starch') * (1 - gel) * 0.8; stamp(ctx, SP.shadow, g.x + g.r * 0.2, g.y + g.r * 0.25, g.r * 1.25, g.r * g.e * 1.35, g.rot);
    if (gel < 1) { ctx.globalAlpha = al('starch') * (1 - gel); stamp(ctx, SP.starch, g.x, g.y, g.r, g.r * (g.big ? g.e : 1), g.rot); }
    if (gel > 0) { ctx.globalAlpha = al('starch') * gel; stamp(ctx, SP.gel, g.x, g.y, g.r * 1.15, g.r * 1.1, g.rot); }
    hits.push({ k: 'starch', x: g.x, y: g.y, r: g.r, big: g.big });
  }
  reset();
  // fat
  for (const f of CAST.fat) { const r = 0.32 * U; const [x, y] = pos(f, r); ctx.globalAlpha = al('fat') * (0.95 - 0.3 * e.fatMelt); stamp(ctx, SP.fat, x, y, r * (1 + 1.3 * e.fatMelt), r * (0.8 - 0.4 * e.fatMelt), f.rot); hits.push({ k: 'fat', x, y, r }); }
  reset();
  // dissolved sugar: as many dots as sugar is left
  const nS = Math.round(CAST.sugar.length * clamp(e.left / 14.8) * (1 - e.sucrose)), sd = Math.max(8, U * 0.2);
  ctx.globalAlpha = al('sugar');
  for (let i = 0; i < nS; i++) { const p = CAST.sugar[i]; const [x0, y0] = pos(p, sd); const x = x0 + Math.sin(T * 0.9 + p.ph) * U * 0.06, y = y0 + Math.cos(T * 0.8 + p.ph) * U * 0.06; ctx.drawImage(SP.sugar, x - sd / 2, y - sd / 2, sd, sd); if (i === 0) hits.push({ k: 'sugar', x, y, r: sd }); }
  // yeast: each drawn cell stands for about 10 billion real ones
  const yp = CAST.yeast.map(c => { const r = 0.3 * U; const [x, y] = pos(c, r * 1.1); return { ...c, x, y, r }; });
  for (const c of yp) {
    const j = e.alive ? U * 0.025 : 0, x = c.x + Math.sin(T * 2.1 + c.ph) * j, y = c.y + Math.cos(T * 1.7 + c.ph) * j, img = e.alive ? SP.yeast : SP.dead;
    ctx.globalAlpha = al('yeast') * 0.5; stamp(ctx, SP.shadow, x + c.r * 0.25, y + c.r * 0.3, c.r * 1.4, c.r * 1.2, c.rot);
    ctx.globalAlpha = al('yeast'); stamp(ctx, img, x, y, c.r, c.r * 0.8, c.rot);
    if (c.bud) stamp(ctx, img, x + Math.cos(c.rot) * c.r * 1.15, y + Math.sin(c.rot) * c.r * 1.15, c.r * 0.45, c.r * 0.4, c.rot);
    hits.push({ k: 'yeast', x, y, r: c.r });
  }
  reset();
  // CO₂ leaving each live yeast cell and flying into the nearest bubble
  if (e.alive && e.rate > 0 && bubs[0].r > 2) {
    for (const c of yp) {
      let nb = bubs[0], bd = 1e9; for (const b of bubs) { const d = Math.hypot(b.x - c.x, b.y - c.y) - b.r; if (d < bd) { bd = d; nb = b; } }
      for (let q = 0; q < 3; q++) {
        const t = (T * 0.35 * e.rate + c.ph + q / 3) % 1, ex = nb.x + (c.x - nb.x) / (Math.hypot(c.x - nb.x, c.y - nb.y) || 1) * nb.r * 0.9, ey = nb.y + (c.y - nb.y) / (Math.hypot(c.x - nb.x, c.y - nb.y) || 1) * nb.r * 0.9;
        const x = lerp(c.x, ex, t), y = lerp(c.y, ey, t) - Math.sin(t * Math.PI) * U * 0.25, sz = Math.max(6, U * (0.1 + 0.08 * t));
        ctx.globalAlpha = al('gas') * Math.min(1, e.rate) * (t < 0.85 ? 1 : (1 - t) / 0.15); ctx.drawImage(SP.co2, x - sz / 2, y - sz / 2, sz, sz);
      }
    }
  }
  // crystals at the start of mixing
  [['sugar', e.sucrose, 0.8, 0.5], ['salt', e.saltXtal, 0.3, 0.62]].forEach(([t, left, u, v]) => {
    if (left <= 0) return; const sz = U * 0.9 * Math.sqrt(left), x = u * W, y = v * H;
    ctx.globalAlpha = al(t) * Math.min(1, left * 1.5); ctx.save(); ctx.translate(x, y); ctx.rotate(0.4);
    const gr = ctx.createLinearGradient(-sz / 2, -sz / 2, sz / 2, sz / 2); gr.addColorStop(0, '#fff'); gr.addColorStop(1, t === 'sugar' ? '#f0b8d4' : '#b9c9db');
    ctx.fillStyle = gr; ctx.fillRect(-sz / 2, -sz / 2, sz, sz); ctx.strokeStyle = t === 'sugar' ? '#d9579a' : '#7f97b0'; ctx.lineWidth = 2; ctx.strokeRect(-sz / 2, -sz / 2, sz, sz); ctx.restore();
    hits.push({ k: t, x, y, r: sz / 2, xtal: true });
  });
  // gas cells: neighbours meet at flat walls (each cell clipped by the half-planes it shares)
  const film = Math.max(2, (s.id === 'proof' || s.id === 'bake' || s.id === 'cool' ? 0.05 : 0.09) * U), steam = s.id === 'bake' ? clamp((s.core - 80) / 18) : 0;
  ctx.globalAlpha = al('gas');
  bubs.forEach((b, i) => {
    if (b.r < 1) return;
    ctx.save();
    bubs.forEach((o, j) => { if (j === i || o.r < 1) return; const dx = o.x - b.x, dy = o.y - b.y, d = Math.hypot(dx, dy) || 1; if (d > b.r + o.r) return;
      const m = (d * d + b.r * b.r - o.r * o.r) / (2 * d) - film / 2, nx = dx / d, ny = dy / d, px = b.x + nx * m, py = b.y + ny * m, L = 4000;
      ctx.beginPath(); ctx.moveTo(px - ny * L, py + nx * L); ctx.lineTo(px + ny * L, py - nx * L); ctx.lineTo(px + ny * L - nx * L, py - nx * L - ny * L); ctx.lineTo(px - ny * L - nx * L, py + nx * L - ny * L); ctx.closePath(); ctx.clip(); });
    // a hollow seen in cross-section: shadow under the near rim, the far wall lit, cool CO₂ tint in dough, warm crumb tones once baked
    const bk = Math.max(gel, s.id === 'cool' ? 1 : 0), mixc = (c1, c2) => c1.map((v, n) => Math.round(lerp(v, c2[n], bk)));
    const rim = mixc([96, 128, 158], [138, 98, 56]), mid = mixc([170, 199, 220], [214, 182, 136]), far = mixc([222, 236, 244], [246, 230, 200]);
    ctx.beginPath(); ctx.arc(b.x, b.y, b.r + film * 3, 0, 7); ctx.fillStyle = 'rgba(40,34,30,.16)'; ctx.fill();
    let g = ctx.createRadialGradient(b.x + b.r * 0.18, b.y + b.r * 0.22, b.r * 0.05, b.x, b.y, b.r);
    g.addColorStop(0, `rgb(${far})`); g.addColorStop(0.62, `rgb(${mid})`); g.addColorStop(1, `rgb(${rim})`);
    ctx.beginPath(); ctx.arc(b.x, b.y, b.r, 0, 7); ctx.fillStyle = g; ctx.fill();
    // shadow cast by the upper-left rim into the hollow
    ctx.save(); ctx.beginPath(); ctx.arc(b.x, b.y, b.r, 0, 7); ctx.clip();
    g = ctx.createRadialGradient(b.x + b.r * 0.32, b.y + b.r * 0.38, b.r * 0.78, b.x + b.r * 0.32, b.y + b.r * 0.38, b.r * 1.32);
    g.addColorStop(0, 'rgba(20,28,40,0)'); g.addColorStop(1, `rgba(${bk ? '70,42,16' : '20,34,58'},${bk ? 0.7 : 0.55})`);
    ctx.fillStyle = g; ctx.fillRect(b.x - b.r, b.y - b.r, b.r * 2, b.r * 2);
    // rising CO₂ specks while yeast work, steam wisps in the oven
    if (e.alive && e.rate > 0) {
      for (let n = 0; n < 9; n++) { const ph = hash(i, n, 5), t = (T * 0.12 * e.rate + ph) % 1, x = b.x + (hash(i, n, 6) - 0.5) * b.r * 1.3, y = b.y + b.r * 0.7 - t * b.r * 1.4, rr = Math.max(1.5, b.r * 0.025 * (1 + t));
        ctx.globalAlpha = al('gas') * 0.55 * Math.sin(t * Math.PI); ctx.fillStyle = '#ffffff'; ctx.beginPath(); ctx.arc(x, y, rr, 0, 7); ctx.fill(); }
      ctx.globalAlpha = al('gas');
    }
    if (steam > 0) {
      ctx.strokeStyle = `rgba(255,255,255,${0.35 * steam})`; ctx.lineWidth = Math.max(2, b.r * 0.05); ctx.lineCap = 'round';
      for (let n = 0; n < 3; n++) { const x0 = b.x + (n - 1) * b.r * 0.35, t = (T * 0.25 + n / 3) % 1; ctx.globalAlpha = al('gas') * Math.sin(t * Math.PI);
        ctx.beginPath(); ctx.moveTo(x0, b.y + b.r * 0.6 - t * b.r * 0.6); ctx.bezierCurveTo(x0 + b.r * 0.15, b.y + b.r * 0.3 - t * b.r * 0.6, x0 - b.r * 0.15, b.y - t * b.r * 0.6, x0, b.y - b.r * 0.3 - t * b.r * 0.6); ctx.stroke(); }
      ctx.globalAlpha = al('gas');
    }
    ctx.restore();
    // the wall: a thin gluten film with a bright lip on the lit side
    ctx.beginPath(); ctx.arc(b.x, b.y, b.r, 0, 7); ctx.strokeStyle = bk > 0.5 ? 'rgba(122,84,48,.95)' : 'rgba(146,118,240,.95)'; ctx.lineWidth = Math.max(film, bk > 0.5 ? 2.5 : 0); ctx.stroke();
    ctx.strokeStyle = 'rgba(255,255,255,.75)'; ctx.lineWidth = Math.max(1.2, film * 0.5); ctx.beginPath(); ctx.arc(b.x, b.y, b.r - film * 0.6, 0.15, 1.9); ctx.stroke();
    ctx.restore();
    { const cx2 = W / 2, cy2 = H / 2, dx = cx2 - b.x, dy = cy2 - b.y, d = Math.hypot(dx, dy) || 1, q = Math.min(b.r * 0.6, d); hits.push({ k: 'gas', x: b.x + dx / d * q, y: b.y + dy / d * q, r: 8, inner: true }); }
  });
  // labels, placed next to the item they name; no two may overlap
  const LB = {
    starch: gel > 0.5 ? 'Starch · swollen into gel' : 'Starch granule · real size 2–35 µm',
    gluten: e.dev < 0.35 ? 'Gluten proteins · not yet joined' : s.id === 'bake' && s.core > 60 ? 'Gluten · setting' : 'Gluten network',
    yeast: e.alive ? 'Yeast cell · real size 4–10 µm' : 'Yeast · dead at 56 °C',
    sugar: 'Sugar dissolved · ' + r1(e.left) + ' g left', fat: e.fatMelt > 0.5 ? 'Fat · melted' : 'Fat (shortening)',
    gas: (s.id === 'bake' && s.core > 80 ? 'Gas cell · CO₂ + steam' : 'Gas cell · CO₂') + ' · ≈ ' + Math.round(s.D / 10) * 10 + ' µm', water: gel > 0.5 ? 'Water + gelatinised starch' : 'Water (with salt, sugar)'
  };
  if (e.sucrose > 0) LB.sugar = 'Sugar crystal · splitting'; if (e.saltXtal > 0) LB.salt = 'Salt crystal · dissolving';
  const ibr = inset.getBoundingClientRect(), mbr = mc.getBoundingClientRect();
  const taken = [{ x: ibr.left - mbr.left - 8, y: ibr.top - mbr.top - 8, w: ibr.width + 16, h: ibr.height + 16 }, { x: W - (W < 480 ? 230 : 340), y: H - 40, w: W < 480 ? 230 : 340, h: 40 }], order = sel ? [sel] : W < 520 ? ['gas', 'starch', 'yeast', 'gluten'] : ['gas', 'starch', 'gluten', 'yeast', 'sugar', 'fat', 'salt', 'water'];
  ctx.font = '700 ' + (W < 520 ? 11 : 12.5) + 'px system-ui,sans-serif'; reset();
  const free = r => r.x > 6 && r.y > 6 && r.x + r.w < W - 6 && r.y + r.h < H - 6 && !taken.some(t => r.x < t.x + t.w + 6 && r.x + r.w + 6 > t.x && r.y < t.y + t.h + 4 && r.y + r.h + 4 > t.y);
  for (const k of order) {
    if (!LB[k]) continue;
    let cands = k === 'water' ? [{ x: W * 0.5, y: H * 0.5, r: 0 }] : hits.filter(h => h.k === k);
    if (k === 'water') { for (let i = 0; i < 30; i++) { const x = hash(i, 31) * W, y = hash(i, 32) * H; if (!bubs.some(b => Math.hypot(x - b.x, y - b.y) < b.r + 20) && !hits.some(h => Math.hypot(x - h.x, y - h.y) < h.r + 14)) cands.push({ x, y, r: 0 }); } cands = cands.slice(1); }
    if (k === 'starch') cands = cands.filter(h => h.big);
    if (k !== 'gas' && k !== 'water') cands = cands.filter(h => !bubs.some(b => Math.hypot(h.x - b.x, h.y - b.y) < b.r - 1));
    const txt = LB[k], tw = ctx.measureText(txt).width + 28, th = 26; let placed = false;
    for (const h of cands) {
      const off = (h.r || 0) + 10;
      for (const [dx, dy] of [[1, 0], [-1, 0], [0, -1], [0, 1], [1, -1], [-1, 1]]) {
        const r = { x: h.x + dx * off - (dx < 0 ? tw : dx === 0 ? tw / 2 : 0), y: h.y + dy * off - (dy < 0 ? th : dy === 0 ? th / 2 : 0), w: tw, h: th };
        if (!free(r)) continue;
        taken.push(r); placed = true;
        const col = COL[k];
        ctx.globalAlpha = 1;
        const rr = Math.max(6, Math.min(h.r || 6, 40)) + 3, ax = clamp(h.x, r.x, r.x + r.w), ay = clamp(h.y, r.y, r.y + r.h), dd = Math.hypot(ax - h.x, ay - h.y) || 1;
        ctx.strokeStyle = 'rgba(16,12,20,.5)'; ctx.lineWidth = 4; ctx.beginPath(); ctx.arc(h.x, h.y, rr, 0, 7); ctx.moveTo(ax, ay); ctx.lineTo(h.x + (ax - h.x) / dd * rr, h.y + (ay - h.y) / dd * rr); ctx.stroke();
        ctx.strokeStyle = 'rgba(255,255,255,.95)'; ctx.lineWidth = 2; ctx.stroke();
        ctx.shadowColor = 'rgba(0,0,0,.35)'; ctx.shadowBlur = 8; ctx.shadowOffsetY = 2;
        ctx.fillStyle = 'rgba(16,12,20,.92)'; ctx.beginPath(); ctx.roundRect(r.x, r.y, r.w, r.h, 13); ctx.fill();
        ctx.shadowColor = 'transparent'; ctx.shadowBlur = 0; ctx.shadowOffsetY = 0;
        ctx.fillStyle = col; ctx.beginPath(); ctx.arc(r.x + 13, r.y + 13, 4.5, 0, 7); ctx.fill();
        ctx.fillStyle = '#f3ede4'; ctx.textAlign = 'left'; ctx.fillText(txt, r.x + 23, r.y + 17.5);
        break;
      }
      if (placed) break;
    }
  }
  // corner note: what is and is not to scale
  ctx.font = '600 11px system-ui,sans-serif'; const note = (W < 480 ? 'Drawn large · gas to scale (' : 'Close-up, drawn large to read · gas share to scale (') + Math.round(s.P * 100) + '%)';
  const nw = ctx.measureText(note).width + 16; ctx.fillStyle = 'rgba(16,12,20,.78)'; ctx.beginPath(); ctx.roundRect(W - nw - 8, H - 30, nw, 22, 11); ctx.fill(); ctx.fillStyle = '#d8cfdd'; ctx.fillText(note, W - nw, H - 15);
  ctx.globalAlpha = 1;
}
const r1 = x => x.toFixed(x < 10 ? 1 : 0);
mc.addEventListener('click', ev => {
  const r = mc.getBoundingClientRect(), x = ev.clientX - r.left, y = ev.clientY - r.top;
  let hit = 'water', bd = 1e9;
  for (const h of hits) { const d = Math.hypot(h.x - x, h.y - y) - (h.r || 8); if (d < 6 && d < bd) { bd = d; hit = h.k; } }
  selectIng(sel === hit ? null : hit);
});
/* ---------------- ingredient meters under the close-up ---------------- */
const metersEl = $('meters'), meterEls = {};
ING.forEach(i => {
  const b = document.createElement('button'); b.type = 'button'; b.className = 'meter'; b.setAttribute('aria-pressed', 'false');
  b.innerHTML = `<span class="mt"><i></i>${i.label}</span><span class="mv"></span><span class="mb"><b></b></span>`;
  b.querySelector('i').style.background = i.col; b.querySelector('.mb b').style.background = i.col === '#2c4a6e' ? '#5b86b8' : i.col;
  b.addEventListener('click', () => selectIng(sel === i.k ? null : i.k));
  metersEl.appendChild(b); meterEls[i.k] = b;
});
function renderMeters(s, e) {
  const M = {
    starch: [e.gel > 0 ? (e.gel < 1 ? 'Gel ' + Math.round(e.gel * 100) + '%' : 'Gel (crumb)') : 'Raw', e.gel || 0.04],
    gluten: [s.id === 'mix' ? 'Forming ' + Math.round(e.dev * 100) + '%' : s.id === 'bake' ? (s.core > 60 ? 'Setting' : 'Stretching') : s.id === 'cool' ? 'Set' : s.id === 'proof' ? 'Thin films' : 'Stretched', e.dev],
    water: [Math.round(e.water) + ' g', e.water / 234],
    yeast: [e.alive ? (e.rate > 1.2 ? 'Fast' : 'Working') : 'Dead', e.alive ? Math.min(1, e.rate / 1.8) : 0],
    sugar: [r1(e.left) + ' g left', e.left / 14.8],
    salt: [e.saltXtal > 0 ? 'Dissolving' : 'Dissolved', 1 - e.saltXtal],
    fat: [e.fatMelt > 0 ? (e.fatMelt < 1 ? 'Melting' : 'Melted') : 'Solid', e.fatMelt || 0.04],
    gas: [Math.round(s.P * 100) + '%', s.P]
  };
  for (const k in M) { const el = meterEls[k]; el.querySelector('.mv').textContent = M[k][0]; el.querySelector('.mb b').style.width = Math.round(clamp(M[k][1]) * 100) + '%'; el.setAttribute('aria-pressed', sel === k); }
  const hl = HEAD(s), he = $('headline'); if (he.textContent !== hl) { he.textContent = hl; he.classList.remove('in'); void he.offsetWidth; he.classList.add('in'); }
}

/* ---------------- the bread: a tag, the spot the close-up shows, and zoom lines to the close-up ---------------- */
let marker = null;
const zc = $('zoom'), zx = zc.getContext('2d'), viz = $('viz');
function drawZoom() {
  if (zc.width) { zc.width = 0; zc.height = 0; } return;
  const W = viz.clientWidth, H = viz.clientHeight, dpr = Math.min(devicePixelRatio || 1, 2);
  if (zc.width !== Math.round(W * dpr) || zc.height !== Math.round(H * dpr)) { zc.width = Math.round(W * dpr); zc.height = Math.round(H * dpr); }
  zx.setTransform(dpr, 0, 0, dpr, 0, 0); zx.clearRect(0, 0, W, H);
  if (!marker) return;
  const vb = viz.getBoundingClientRect(), ib = inset.getBoundingClientRect(), sb = mc.getBoundingClientRect();
  const mx0 = ib.left - vb.left + marker[0], my0 = ib.top - vb.top + marker[1], q = 9;
  if (mx0 < ib.left - vb.left || mx0 > ib.right - vb.left || my0 < ib.top - vb.top || my0 > ib.bottom - vb.top) return;
  const L = sb.left - vb.left, T = sb.top - vb.top, R = sb.right - vb.left, B = sb.bottom - vb.top;
  const side = L > mx0 + q; // close-up to the right (desktop) or below (phone)
  const pairs = side ? [[mx0 + q, my0 - q, L, T], [mx0 + q, my0 + q, L, B]] : [[mx0 - q, my0 + q, L, T], [mx0 + q, my0 + q, R, T]];
  zx.fillStyle = 'rgba(242,177,63,.07)'; zx.beginPath(); zx.moveTo(pairs[0][0], pairs[0][1]); zx.lineTo(pairs[0][2], pairs[0][3]); zx.lineTo(pairs[1][2], pairs[1][3]); zx.lineTo(pairs[1][0], pairs[1][1]); zx.closePath(); zx.fill();
  zx.setLineDash([5, 5]); zx.strokeStyle = 'rgba(242,177,63,.85)'; zx.lineWidth = 1.5;
  for (const [a, b, c, d] of pairs) { zx.beginPath(); zx.moveTo(a, b); zx.lineTo(c, d); zx.stroke(); }
  zx.setLineDash([]);
  zx.fillStyle = '#f2b13f'; zx.font = '800 11px system-ui,sans-serif'; zx.textAlign = 'center';
  const lx = side ? (mx0 + L) / 2 : (mx0 + (L + R) / 2) / 2, ly = side ? (my0 + (T + B) / 2) / 2 - 8 : (my0 + T) / 2;
  const tw = zx.measureText('close-up of this spot').width + 16; zx.fillStyle = 'rgba(16,12,20,.9)'; zx.beginPath(); zx.roundRect(lx - tw / 2, ly - 14, tw, 20, 10); zx.fill(); zx.fillStyle = '#f2b13f'; zx.fillText('close-up of this spot', lx, ly);
}
const v3 = new THREE.Vector3();
function proj(x, y, z) { v3.set(x, y, z).project(camera); return [(v3.x + 1) / 2 * hud.clientWidth, (1 - v3.y) / 2 * hud.clientHeight]; }
function drawHud(s) {
  const W = hud.clientWidth, H = hud.clientHeight, dpr = Math.min(devicePixelRatio || 1, 2);
  if (hud.width !== Math.round(W * dpr)) { hud.width = Math.round(W * dpr); hud.height = Math.round(H * dpr); }
  hx.setTransform(dpr, 0, 0, dpr, 0, 0); hx.clearRect(0, 0, W, H);
  const p = proj(0, dims.y + dims.Hb * 0.9, 0), q = Math.max(4, W * 0.035);
  const cap = W < 160 ? 'The bread · ▢ close-up' : 'The bread · ▢ = this close-up'; if ($('insetCap').textContent !== cap) $('insetCap').textContent = cap;
  hx.fillStyle = 'rgba(242,177,63,.18)'; hx.fillRect(p[0] - q, p[1] - q, 2 * q, 2 * q);
  hx.strokeStyle = 'rgba(16,12,20,.6)'; hx.lineWidth = 4; hx.strokeRect(p[0] - q, p[1] - q, 2 * q, 2 * q);
  hx.strokeStyle = '#f2b13f'; hx.lineWidth = 2; hx.strokeRect(p[0] - q, p[1] - q, 2 * q, 2 * q);
  marker = p;
  let t1 = s.id === 'bake' ? 'Core ' + Math.round(s.core) + ' °C' : s.id === 'mix' ? (s.f > 0.97 ? '25 °C' : 'Mixing') : s.id === 'rise' ? '30 °C' : s.id === 'proof' ? '43 °C' : s.id === 'shape' ? '500 g' : (s.f > 0.98 ? '423 g' : 'Cooling');
  if (W > 180) t1 += ' · ' + Math.round(s.V / 10) * 10 + ' cm³';
  hx.font = '800 10.5px system-ui,sans-serif';
  const tw = hx.measureText(t1).width + 14;
  hx.fillStyle = 'rgba(18,14,22,.9)'; hx.strokeStyle = s.id === 'bake' && s.core >= 56 ? '#f26a4f' : '#f2b13f'; hx.lineWidth = 1.2;
  hx.beginPath(); hx.roundRect(6, 6, tw, 19, 9.5); hx.fill(); hx.stroke();
  hx.fillStyle = '#f3ede4'; hx.textAlign = 'left'; hx.fillText(t1, 13, 19.5);
}

/* ---------------- panel: now, ingredients, the whole dough ---------------- */
const esc = t => String(t).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
function tagHTML(tags) {
  const by = {}; for (const t of tags) (by[t.t] || (by[t.t] = [])).push(...(t.src || []));
  return ['M', 'L', 'C', 'E', 'N'].filter(k => by[k]).map(k => `<span class="tag t${k}">${TAGN[k]}</span>`).join('');
}
let open = null, hiKey = null;
function makeList(el, map) {
  return rows => {
    const seen = new Set();
    rows.forEach(r => {
      seen.add(r.k);
      let row = map.get(r.k);
      if (!row) {
        row = document.createElement('div'); row.className = 'row'; row.setAttribute('role', 'listitem');
        row.innerHTML = '<button type="button" aria-expanded="false"><span class="k"></span><span class="tags"></span><span class="v"></span></button><div class="why" hidden></div>';
        row.firstChild.addEventListener('click', () => { open = open === r.k ? null : r.k; if (ING.some(i => i.k === r.k)) sel = open === r.k ? r.k : (sel === r.k ? null : sel); syncOpen(); dirty = true; });
        map.set(r.k, row); row._c = {};
      }
      const c = row._c, b = row.firstChild;
      const lh = (COL[r.k] ? `<span class="sw"></span>` : '') + esc(r.label);
      if (c.l !== lh) { b.querySelector('.k').innerHTML = c.l = lh; const sw = b.querySelector('.sw'); if (sw) sw.style.background = COL[r.k]; }
      const th = tagHTML(r.tags); if (c.t !== th) b.querySelector('.tags').innerHTML = c.t = th;
      const vh = esc(r.v) + (r.sub ? ' <small>· ' + esc(r.sub) + '</small>' : ''); if (c.v !== vh) b.querySelector('.v').innerHTML = c.v = vh;
      const srcs = [...new Set(r.tags.flatMap(t => t.src || []))];
      const wh = '<p>' + esc(r.why) + '</p>' + srcs.map(k => `<p class="cite">${esc(SHORT[k])} · ${esc(SRC[k].read)} · <a href="${SRC[k].u}" target="_blank" rel="noopener">open the source</a></p>`).join('');
      if (c.w !== wh) row.lastChild.innerHTML = c.w = wh;
      row.classList.toggle('hi', r.k === hiKey); row.classList.toggle('sel', r.k === sel);
      el.appendChild(row);
    });
    for (const [k, row] of map) if (!seen.has(k) && row.parentNode) row.remove();
  };
}
const ingMap = new Map(), condMap = new Map(), ALL = () => [...ingMap, ...condMap];
const renderIng = makeList($('ing'), ingMap), renderCond = makeList($('cond'), condMap);
function syncOpen() { for (const [k, row] of ALL()) { const on = k === open; row.firstChild.setAttribute('aria-expanded', on); row.lastChild.hidden = !on; row.classList.toggle('sel', k === sel); } }
function selectIng(k) { sel = k; open = k; syncOpen(); dirty = true; const row = ingMap.get(k); if (row && k && innerWidth > 860) row.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); }
const WHOLE = ['temp', 'surf', 'size', 'ph', 'wt'];
let lastNow = '';
function renderPanel(s) {
  renderIng(ingredients(s));
  renderCond(condition(s).filter(r => WHOLE.includes(r.k)));
  const pr = practical(s), key = s.id;
  if (key !== lastNow) {
    lastNow = key;
    $('nowH').textContent = (s.si + 1) + ' · ' + STEPS[s.si].name;
    $('nowT').textContent = pr.what;
    $('nowC').innerHTML = pr.check.map(c => `<li>${esc(c.t)} ${tagHTML(c.tags)}</li>`).join('');
  }
  syncOpen();
}
$('srcList').innerHTML = Object.keys(SRC).map(k => `<li>${esc(SRC[k].c)} <a href="${SRC[k].u}" target="_blank" rel="noopener">Link</a><br><span class="rd">Read: ${esc(SRC[k].read)}. Used for: ${esc(SRC[k].what)}</span></li>`).join('');

/* ---------------- steps, timeline, playback, walk-through ---------------- */
const stepsEl = $('steps'), timeEl = $('time');
const JUMP = [999, 1526, 2999, 3999, 4700, 5999];
STEPS.forEach((st, i) => {
  const b = document.createElement('button'); b.type = 'button';
  b.innerHTML = `<b>${i + 1} · ${esc(st.name)}</b><small>${esc(st.sub)}</small>`;
  b.addEventListener('click', () => { stopTour(); setPlaying(false); setU(JUMP[i]); });
  stepsEl.appendChild(b);
});
let u = 999, playing = false, dirty = true;
function setU(v) { u = clamp(v, 0, 5999.999); timeEl.value = Math.round(u); dirty = true; }
timeEl.addEventListener('input', () => { stopTour(); setPlaying(false); u = +timeEl.value; dirty = true; });
function setPlaying(on) { playing = on; $('play').textContent = on ? '❚❚' : '▶'; $('play').setAttribute('aria-label', on ? 'Pause' : 'Play'); }
$('play').addEventListener('click', () => { stopTour(); if (!playing && u >= 5999) setU(0); setPlaying(!playing); });
const TOUR = [
  { a: 0, b: 300, ms: 6500, k: 'water', t: 'This is a close-up of the inside of the dough, drawn large so you can read it. Mixing has just started: flour is getting wet, sugar and salt crystals are dissolving. The bars below show each ingredient right now.' },
  { a: 300, b: 999, ms: 7000, k: 'gluten', t: 'Mixing joins the wet gluten proteins (purple) into a net that ties the starch granules together, and traps air as tiny bubbles.' },
  { a: 1000, b: 1526, ms: 8000, k: 'yeast', t: 'First rise at 30 °C. Each yeast cell eats the dissolved sugar (pink) and breathes out CO₂ (the little blue bubbles), which flies into the gas cells and makes them grow. Watch the Sugar bar drop.' },
  { a: 1527, b: 1999, ms: 6500, k: 'gas', t: 'Knock-back at 95 and 145 min: gas is pressed out and the big cells split into small ones. The Gas bar falls, then climbs again.' },
  { a: 3000, b: 3999, ms: 7500, k: 'gas', t: 'Proof at 43 °C. The cells grow until they press against each other and the walls between them are thin films. The ingredients get squeezed into those walls.' },
  { a: 4000, b: 4800, ms: 9000, k: 'starch', t: 'Bake. Gas expands and the loaf springs. At 56 °C the yeast die (grey). Between 55 and 70 °C the starch swells into gel and the dough becomes crumb.' },
  { a: 5000, b: 5999, ms: 6000, k: 'water', t: 'Cool: 423 g from 500 g, the difference mostly water gone as steam. Tap any ingredient, in the picture or the bars, to follow it; the panel on the right shows where every number comes from.' }
];
let tour = null;
function startTour() { setPlaying(false); open = null; sel = null; tour = { i: 0, t0: performance.now() }; $('tourBox').hidden = false; showBeat(); }
function showBeat() { const b = TOUR[tour.i]; $('tourT').textContent = b.t; $('tourN').textContent = (tour.i + 1) + ' of ' + TOUR.length; hiKey = b.k; sel = b.k; tour.t0 = performance.now(); setU(b.a); }
function stopTour() { if (!tour) return; tour = null; hiKey = null; sel = null; $('tourBox').hidden = true; dirty = true; }
$('tour').addEventListener('click', () => tour ? stopTour() : startTour());
$('tourSkip').addEventListener('click', stopTour);

function resize() {
  const w = inset.clientWidth, h = inset.clientHeight;
  if (renderer) renderer.setSize(w, h, false);
  camera.aspect = w / Math.max(1, h); camera.updateProjectionMatrix(); dirty = true;
}
addEventListener('resize', resize); resize();
let last = performance.now(), sNow = stateAt(u), eNow = extra(sNow), lastSi = -1, lastMicro = 0;
function frame(now) {
  const dt = Math.min(0.05, (now - last) / 1000); last = now;
  if (tour) {
    const b = TOUR[tour.i], k = (now - tour.t0) / b.ms;
    if (k >= 1.2) { if (tour.i + 1 < TOUR.length) { tour.i++; showBeat(); } else stopTour(); }
    else { u = lerp(b.a, b.b, smooth(k)); timeEl.value = Math.round(u); dirty = true; }
  } else if (playing) {
    u += dt * 1000 / 10; if (u >= 5999.999) { u = 5999.999; setPlaying(false); }
    timeEl.value = Math.round(u); dirty = true;
  }
  if (dirty) {
    sNow = stateAt(u); eNow = extra(sNow);
    buildDough(sNow); drawCap(sNow, sNow.si !== lastSi); renderPanel(sNow); ui(sNow); lastSi = sNow.si;
    const heat = sNow.id === 'bake' ? smooth(sNow.f * 4) * (1 - smooth((sNow.f - 0.985) * 60)) : 0;
    oven.visible = heat > 0.01; heatMat.emissiveIntensity = heat * 2.2; ovenWall.material.emissiveIntensity = heat * 0.8; ovenLight.intensity = heat * 170;
    inset.classList.toggle('hot', heat > 0.01);
  }
  if (dirty || (!reduced && now - lastMicro > 33)) { drawMicro(sNow, eNow, now); renderMeters(sNow, eNow); lastMicro = now; }
  dirty = false;
  placeCamera(dt);
  if (renderer) renderer.render(scene, camera);
  drawHud(sNow); drawZoom();
  requestAnimationFrame(frame);
}
function ui(s) {
  const st = STEPS[s.si];
  $('capN').textContent = s.si + 1; $('capH').textContent = st.name; $('capC').textContent = fmtClock(s.clock);
  $('clock').textContent = fmtClock(s.clock);
  [...stepsEl.children].forEach((b, i) => { if (i === s.si) b.setAttribute('aria-current', 'step'); else b.removeAttribute('aria-current'); });
}
requestAnimationFrame(frame);
new ResizeObserver(() => { dirty = true; }).observe(stage);
new ResizeObserver(resize).observe(inset);

let seen = false; try { seen = localStorage.getItem('living-dough-v4') === '1'; localStorage.setItem('living-dough-v4', '1'); } catch (e) { }
if (!seen && !reduced) setTimeout(startTour, 900);
index.html85 lines

Raw file

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="dark">
<title>Living Dough | Animations | Shahrouz Ghadimi</title>
<meta name="description" content="Living Dough: inside one real 500 g bread dough from mixing to cooling. Every ingredient and what happens to it at each step, traced to published measurements.">
<link rel="icon" href="../favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="./dough.css">
</head>
<body>
<header class="top">
  <a class="back" href="../animations/">&larr; Animations</a>
  <div class="ttl">
    <h1>Living Dough</h1>
    <p>Inside one real 500 g dough, step by step: every ingredient, every number from a measurement.</p>
  </div>
  <button type="button" id="tour" class="tourb">▶ Walk me through</button>
</header>

<div id="main" role="main">
  <section id="stage" aria-label="Inside the dough">
    <div class="head2">
      <span class="cap-n" id="capN">1</span>
      <div><b id="capH">Mix</b><span id="capC">12 min</span><p id="headline"></p></div>
    </div>
    <div class="viz" id="viz">
      <div class="slide"><canvas id="micro" aria-label="Close-up of the inside of the dough: gas cells, starch, gluten, yeast, sugar, fat and water. Tap an ingredient to follow it."></canvas>
        <figure class="inset" id="inset">
          <canvas id="scene" aria-label="The bread in 3D, cut in half. Drag to turn."></canvas>
          <canvas id="hud" aria-hidden="true"></canvas>
          <figcaption id="insetCap">The bread · ▢ = this close-up</figcaption>
          <button type="button" id="reset" class="reset" aria-label="Reset the 3D view">⟲</button>
        </figure>
      </div>
      <canvas id="zoom" aria-hidden="true"></canvas>
    </div>
    <div class="meters" id="meters" role="list" aria-label="Ingredients now"></div>
    <div class="tourbox" id="tourBox" hidden>
      <p id="tourT"></p>
      <div class="tour-row"><span id="tourN"></span><button type="button" id="tourSkip">Stop</button></div>
    </div>
  </section>

  <nav id="rail" aria-label="Steps">
    <div class="steps" id="steps"></div>
    <div class="tl">
      <button type="button" id="play" aria-label="Play">▶</button>
      <input type="range" id="time" min="0" max="6000" step="1" value="1000" aria-label="Time through the six steps">
      <span id="clock">12 min</span>
    </div>
  </nav>

  <aside id="panel" aria-label="What is happening">
    <section class="now">
      <h2 id="nowH">Mix</h2>
      <p id="nowT"></p>
      <ul id="nowC" class="checks"></ul>
    </section>
    <h3>Ingredients in detail <span class="hint">where every number comes from</span></h3>
    <div id="ing" role="list"></div>
    <h3>The whole dough</h3>
    <div id="cond" role="list"></div>
    <p class="keys">
      <span class="tag tM">measured</span> in the bake we follow ·
      <span class="tag tL">lab study</span> on a similar dough ·
      <span class="tag tC">calculated</span> from measured numbers ·
      <span class="tag tE">estimate</span> joins or draws what was not measured
    </p>
    <details class="recipe">
      <summary>The bake we follow</summary>
      <p>A straight-dough white pan bread baked in a cereal-science lab: Puhr &amp; D’Appolonia, <i>Cereal Chemistry</i> 1992. Flour 100, water 69.1, sugar 5, yeast 3, shortening 3, salt 2 (parts by weight). In one 500 g piece: 274 g flour, 190 g water, 13.7 g sugar, 8.2 g yeast, 8.2 g shortening, 5.5 g salt. Mixed, fermented 3 h at 30 °C and knocked back at 95 and 145 min, divided into 500 g pieces, proofed 55 min at 43 °C, baked 25 min at about 204 °C, weighed and measured an hour later.</p>
      <p>What that paper did not measure (the inside of the dough, the ingredients’ sizes and how fast they change) comes from lab studies of similar doughs, tagged <span class="tag tL">lab study</span>. The magnified view is drawn to true scale from those numbers.</p>
    </details>
    <details class="recipe" id="srcBox">
      <summary>All sources</summary>
      <ol id="srcList"></ol>
    </details>
  </aside>
</div>
<script type="module" src="./dough.js"></script>
</body>
</html>
dough.css151 lines

Raw file

/* Living Dough v3: one dough, cut open, six steps. Stage + step rail on the left, the dough's condition on the right (below on phones). */
:root{
  color-scheme:dark;
  --bg:#120e16; --panel:#1a1520; --line:#30283a; --ink:#f3ede4; --muted:#a79daf;
  --amber:#f2b13f; --gas:#62c7ef; --heat:#f26a4f; --ok:#8fd6a4;
  --tM:#8fd6a4; --tL:#62c7ef; --tC:#c8b6ff; --tE:#f2b13f;
  --display:ui-rounded,"SF Pro Rounded","Avenir Next","Segoe UI",system-ui,sans-serif;
  --body:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;
}
*{box-sizing:border-box}
html,body{height:100%;margin:0}
body{background:var(--bg);color:var(--ink);font:400 14px/1.45 var(--body);display:flex;flex-direction:column;overflow:hidden}
button{font:inherit;color:inherit;cursor:pointer}
:focus-visible{outline:2px solid var(--gas);outline-offset:2px}
[hidden]{display:none !important}
p{margin:0}

.top{display:flex;align-items:center;gap:14px;padding:8px 14px;border-bottom:1px solid var(--line);flex:0 0 auto}
.back{color:var(--muted);text-decoration:none;font-size:11.5px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;white-space:nowrap}
.back:hover{color:var(--ink)}
.ttl{flex:1 1 auto;min-width:0}
.ttl h1{margin:0;font:800 19px/1.1 var(--display)}
.ttl p{font-size:12.5px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.tourb{border:1px solid var(--amber);background:rgba(242,177,63,.12);color:var(--amber);border-radius:999px;padding:7px 14px;font-weight:800;font-size:13px;white-space:nowrap;min-height:36px}

#main{flex:1 1 auto;min-height:0;display:grid;grid-template-columns:minmax(0,1fr) 370px;grid-template-rows:minmax(0,1fr) auto;grid-template-areas:"stage panel" "rail panel"}
#stage{grid-area:stage;position:relative;overflow:hidden;min-height:300px;background:var(--bg)}
#scene,#hud{position:absolute;inset:0;width:100%;height:100%;display:block}
#scene{touch-action:none;cursor:grab}
#scene:active{cursor:grabbing}
#hud{pointer-events:none}

#stage{display:flex;flex-direction:column}
.head2{display:flex;gap:12px;align-items:flex-start;padding:12px 16px 6px;flex:0 0 auto}
.head2 b{font:800 17px/1.2 var(--display);color:var(--amber);margin-right:8px}
.head2 span:not(.cap-n){font-size:12.5px;color:var(--muted);font-variant-numeric:tabular-nums}
.head2 p{font:700 clamp(16px,1.7vw,21px)/1.25 var(--display);margin-top:3px;color:var(--ink);text-wrap:balance}
.cap-n{flex:0 0 auto;width:30px;height:30px;border-radius:50%;background:var(--amber);color:#1a1520;font:800 15px/30px var(--display);text-align:center;margin-top:2px}
.viz{position:relative;flex:1 1 auto;min-height:0;display:flex;margin:4px 16px 8px}
.viz .slide{flex:1 1 auto}
.slide{position:relative;min-height:0;border-radius:16px;overflow:hidden;border:1px solid var(--line);box-shadow:inset 0 0 0 1px rgba(255,255,255,.04)}
#zoom{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}
#micro{position:absolute;inset:0;width:100%;height:100%;display:block;cursor:pointer;touch-action:manipulation}
.meters{flex:0 0 auto;display:grid;grid-template-columns:repeat(8,minmax(0,1fr));gap:6px;padding:0 16px 12px}
.meter{border:1px solid var(--line);background:rgba(255,255,255,.03);border-radius:10px;padding:6px 8px 7px;text-align:left;min-width:0;display:flex;flex-direction:column;gap:3px}
.meter[aria-pressed="true"]{border-color:var(--amber);background:rgba(242,177,63,.12)}
.meter .mt{display:flex;align-items:center;gap:5px;font-size:11px;font-weight:800;color:var(--muted);text-transform:uppercase;letter-spacing:.04em;white-space:nowrap;overflow:hidden}
.meter .mt i{flex:0 0 auto;width:9px;height:9px;border-radius:50%}
.meter .mv{font:800 13.5px/1.15 var(--display);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-variant-numeric:tabular-nums}
.meter .mb{height:5px;border-radius:3px;background:rgba(255,255,255,.08);overflow:hidden}
.meter .mb b{display:block;height:100%;border-radius:3px;transition:width .25s}
.inset{position:absolute;right:10px;top:10px;z-index:2;margin:0;width:210px;aspect-ratio:4/3;border-radius:12px;overflow:hidden;border:1.5px solid rgba(242,177,63,.75);box-shadow:0 6px 20px rgba(0,0,0,.45);background:radial-gradient(120% 90% at 50% 35%,#2a2030 0%,#120e16 75%)}
.inset.hot{background:radial-gradient(120% 90% at 55% 30%,#5a2a16 0%,#2a1510 50%,#120e16 85%)}
.inset figcaption{position:absolute;left:7px;bottom:5px;right:30px;font-size:10.5px;font-weight:700;color:var(--ink);text-shadow:0 1px 3px #000;pointer-events:none}
.tourbox{position:absolute;left:50%;transform:translateX(-50%);bottom:12px;width:min(440px,calc(100% - 24px));background:rgba(26,21,32,.95);border:1px solid var(--amber);border-radius:12px;padding:10px 12px;font-size:13.5px}
.tour-row{display:flex;justify-content:space-between;align-items:center;margin-top:8px;color:var(--muted);font-size:12px}
.tour-row button{border:1px solid var(--line);background:none;border-radius:8px;padding:4px 10px;font-size:12px}

#rail{grid-area:rail;border-top:1px solid var(--line);background:var(--panel);padding:8px 10px 10px}
.steps{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:6px}
.steps button{border:1px solid var(--line);background:rgba(255,255,255,.02);border-radius:10px;padding:6px 8px;text-align:left;min-height:48px;display:flex;flex-direction:column;gap:1px;min-width:0}
.steps b{font:800 13px/1.2 var(--display);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.steps small{font-size:11px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.steps button[aria-current="step"]{border-color:var(--amber);background:rgba(242,177,63,.13)}
.steps button[aria-current="step"] b{color:var(--amber)}
.tl{display:flex;align-items:center;gap:10px;margin-top:8px}
#play{flex:0 0 auto;width:42px;height:42px;border-radius:50%;border:0;background:var(--amber);color:#1a1520;font-size:15px;font-weight:900}
#time{flex:1 1 auto;accent-color:var(--amber);height:28px;min-width:0}
#clock{flex:0 0 auto;min-width:92px;text-align:right;font-variant-numeric:tabular-nums;font-size:12.5px;color:var(--muted)}

#panel{grid-area:panel;border-left:1px solid var(--line);background:var(--panel);overflow-y:auto;padding:12px 14px 20px}
#panel h2{margin:0 0 6px;font:800 17px/1.2 var(--display);color:var(--amber)}
#panel h3{margin:16px 0 4px;font:800 14px/1.2 var(--display)}
#panel h3 .hint{font:500 11.5px var(--body);color:var(--muted);margin-left:6px}
.now{border:1px solid rgba(242,177,63,.45);background:rgba(242,177,63,.07);border-radius:12px;padding:10px 12px}
.now p{font-size:13.5px}
.checks{list-style:none;margin:8px 0 0;padding:0;display:grid;gap:6px}
.checks li{font-size:13px;padding-left:20px;position:relative}
.checks li::before{content:"✓";position:absolute;left:2px;top:0;color:var(--amber);font-weight:900}
.checks .tag{margin-left:4px}
.sw{display:inline-block;width:11px;height:11px;border-radius:3px;margin-right:6px;vertical-align:-1px;border:1px solid rgba(255,255,255,.35)}
.row.sel{background:rgba(255,255,255,.06);border-radius:8px}
.row.sel>button{padding-left:8px;padding-right:6px}
#condWhen{font:600 12px var(--body);color:var(--muted);margin-left:4px}
.keys{font-size:11.5px;color:var(--muted);line-height:1.9;margin:12px 0 0}
.tag{display:inline-block;border-radius:999px;padding:0 7px;font-size:10.5px;font-weight:800;line-height:17px;letter-spacing:.02em;border:1px solid currentColor;white-space:nowrap}
.tM{color:var(--tM)} .tL{color:var(--tL)} .tC{color:var(--tC)} .tE{color:var(--tE)} .tN{color:var(--muted)}

.row{border-top:1px solid var(--line)}
.row>button{display:grid;grid-template-columns:1fr auto;gap:2px 10px;width:100%;border:0;background:none;padding:9px 2px;text-align:left;align-items:baseline}
.row .k{font-size:12px;color:var(--muted);font-weight:700;text-transform:uppercase;letter-spacing:.04em}
.row .tags{justify-self:end;display:flex;gap:4px;flex-wrap:wrap;justify-content:flex-end}
.row .v{grid-column:1/-1;font:700 15px/1.35 var(--display);font-variant-numeric:tabular-nums}
.row .v small{font:500 12.5px/1.35 var(--body);color:#d8cfdd}
.row.hi{background:rgba(242,177,63,.10);border-radius:8px;box-shadow:inset 3px 0 0 var(--amber)}
.row.hi>button{padding-left:10px;padding-right:6px}
.why{padding:0 4px 10px;font-size:12.5px;color:#d8cfdd}
.why p+p{margin-top:6px}
.why a{color:var(--gas)}
.why .cite{font-size:11.5px;color:var(--muted)}
.row>button[aria-expanded="true"] .k{color:var(--ink)}

.recipe{margin-top:12px;border:1px solid var(--line);border-radius:10px;padding:8px 10px;font-size:12.5px;color:#d8cfdd}
.recipe summary{cursor:pointer;font-weight:800;color:var(--ink)}
.recipe p{margin-top:8px}
#srcList{margin:8px 0 0;padding-left:18px}
#srcList li{margin-bottom:8px;font-size:12px}
#srcList a{color:var(--gas)}
#srcList .rd{color:var(--muted)}

@media (max-width:860px){
  body{overflow:auto;height:auto}
  #main{display:flex;flex-direction:column}
  #panel{border-left:0;border-top:1px solid var(--line);overflow:visible}
  .ttl p{display:none}
  .steps{grid-template-columns:repeat(3,minmax(0,1fr))}
  #stage{height:auto;min-height:0}
  .viz{margin:4px 10px 8px;flex:0 0 auto;height:58vh;min-height:340px}
  .inset{width:128px;right:6px;top:6px}
  .inset figcaption{font-size:9.5px;right:6px}
  .reset{display:none}
  .head2{padding:10px 12px 4px}
  .meters{grid-template-columns:repeat(4,minmax(0,1fr));padding:0 10px 10px}
  .meter .mv{font-size:12px;white-space:normal;line-height:1.15;min-height:2.3em}
  .meter .mt{font-size:10px}
  .tourbox{font-size:12.5px;padding:8px 10px;bottom:8px}
}
@media (max-width:420px){
  .top{gap:8px;padding:6px 10px}
  .tourb{padding:6px 10px;font-size:12px}
  .back{font-size:10.5px}
}

/* the site's shared footer, kept small under the tool */
.site-foot{flex:0 0 auto;display:flex;flex-wrap:wrap;gap:2px 14px;padding:5px 14px calc(5px + env(safe-area-inset-bottom,0px));font-size:11px;color:var(--muted);border-top:1px solid var(--line);background:var(--bg)}
.site-foot a{color:var(--muted);text-decoration:none}
.site-foot a:hover{color:var(--ink);text-decoration:underline}
@media (max-width:860px){.site-foot{padding:14px;font-size:12.5px}.site-foot span{flex:1 1 100%}}

/* polish */
#headline.in{animation:hlIn .45s ease-out}
@keyframes hlIn{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
@media (prefers-reduced-motion:reduce){#headline.in{animation:none}}
.meter{transition:border-color .2s,background .2s,transform .15s}
.meter:hover{transform:translateY(-1px);border-color:rgba(255,255,255,.22)}
.meter .mb{height:6px;background:rgba(255,255,255,.07);box-shadow:inset 0 1px 2px rgba(0,0,0,.4)}
.meter .mb b{background-image:linear-gradient(180deg,rgba(255,255,255,.35),rgba(255,255,255,0) 60%)!important;background-blend-mode:overlay}
.slide{background:#dfe9ee;box-shadow:0 10px 30px rgba(0,0,0,.35),inset 0 0 0 1px rgba(255,255,255,.05)}
@media (max-width:380px){.meters{gap:4px}.meter{padding:5px 6px 6px}.meter .mt{font-size:9px;letter-spacing:0;gap:4px}.meter .mv{font-size:11px}}
@media (max-width:860px) and (max-height:480px){.viz{height:82vh}}

Need an interactive piece for your business or audience?

A product explainer, a training walkthrough, a simulation people can play with. This one is free to take. I can build yours for a fixed price agreed up front, and the first call is free.

How it works and what it costs Book a free call ↗

Or write to me · how to use what is here