From 221505ea21d8093f00b3cef98822d967c8894337 Mon Sep 17 00:00:00 2001 From: Tim <6703801+timzifer@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:23:18 +0100 Subject: [PATCH] docs: split AGENTS.md into a root file and package-local ones MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AGENTS.md had grown to 1,582 lines and 102 KB, loaded whole into every agent run and skimmed by every person. The root file keeps what binds the whole tree — the one rule, layer discipline, golden files and FMA, the pool and the allocation gate, parallel equals serial, transitions, open questions and the cross-cutting part of Scope — and ends with an index of eleven package files: data, stat, scale, coord, geom, render, three, ir, interact, spec and backend. Each holds that package's "things that will bite", and geom and coord their "deliberately not done" lists. The text is moved, not edited: every non-blank line of the old file appears exactly once in the new ones, in its original order within each file, with relative links rebased by "../". The only new prose is a two-sentence header per package file, the index and one pointer in Scope. Root is now 328 lines and 21 KB; AGENTS.md#scope, which CONCEPT.md links to, still exists. Fixes #87 Claude-Session: https://claude.ai/code/session_015BfhXWEPyCFY4fZhg5nzsh --- AGENTS.md | 1308 ++------------------------------------------ backend/AGENTS.md | 154 ++++++ coord/AGENTS.md | 218 ++++++++ data/AGENTS.md | 42 ++ geom/AGENTS.md | 461 ++++++++++++++++ interact/AGENTS.md | 41 ++ ir/AGENTS.md | 30 + render/AGENTS.md | 103 ++++ scale/AGENTS.md | 79 +++ spec/AGENTS.md | 33 ++ stat/AGENTS.md | 67 +++ three/AGENTS.md | 136 +++++ 12 files changed, 1402 insertions(+), 1270 deletions(-) create mode 100644 backend/AGENTS.md create mode 100644 coord/AGENTS.md create mode 100644 data/AGENTS.md create mode 100644 geom/AGENTS.md create mode 100644 interact/AGENTS.md create mode 100644 ir/AGENTS.md create mode 100644 render/AGENTS.md create mode 100644 scale/AGENTS.md create mode 100644 spec/AGENTS.md create mode 100644 stat/AGENTS.md create mode 100644 three/AGENTS.md diff --git a/AGENTS.md b/AGENTS.md index 3c9e94a..2cbeace 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -88,74 +88,6 @@ then commit. **Never widen a tolerance to make a failure go away.** `backend/stilus/cmd/gallery`. Never hand-edit them. A test and a CI job both check they match the code. -**`backend/gg` must not import `gg/gpu`.** Importing it activates the GPU tier, -pulls `wgpu` and `goffi` into the build, and makes CI need graphics hardware. -The CPU rasterizer is the supported path — -[ADR 0006](docs/adr/0006-gg-coupling-surface.md). - -**gg is pinned exactly.** Upgrading it is a deliberate change with its own -commit, not a side effect of `go get -u`. - -**The raster backend is `backend/stilus`, and `backend/gg` is deprecated.** -New raster work goes into stilus; gg keeps building, unchanged, through -v0.19.0 and is removed in v0.20.0 with its GPU tier, and is never tagged v1 -([ADR 0094](docs/adr/0094-the-raster-backend-is-stilus.md)). -Four things there bite: - -- *A glyph outline is in ems, not design units.* `stilus.GlyphCache` - quantises the matrix's linear part to 1/64 and reads its scale as the em size - in pixels. Handed design units, a 16 px label in a 2048-unit font has a scale - of 16/2048, which rounds to 1/64 — twice its size — and a 10 px label rounds - to zero and is laid out and never drawn. `TestSmallTextIsDrawnAtItsSize` is - that bug. -- *The font box is OS/2's, advances are unrounded.* Ascent and descent come - from `sTypoAscender`/`sTypoDescender`, hhea only when both are zero — gg's - rule, which keeps every chart on the rectangle gg laid it out on. The vector - emitters read hhea; the 15 % between the two is the drift - `TestMeasurementAgreesWithTheVectorEmitter` allows. Advances are the font's - own widths, not gg's whole pixels, and agree with the SVG backend to - 0.01 px. -- *The module declares Go 1.27.1*, because go-opentype does, and so does - `backend/window`, which draws through it. The committed workspace says - 1.27.1 for that reason; every other module still declares 1.25, and CI's - minimum-toolchain job builds them from a workspace that leaves those two out - with `GOTOOLCHAIN=local`. Without that the toolchain switches itself up and - the 1.25 claim is checked by nothing. -- *A module another one imports is tagged before the importer can require - it.* A require on a version that does not exist breaks the workspace too, - because the module graph is read before the workspace replaces it. So - v0.15.0 went out in three steps — the core with gg and arrow, then - `backend/stilus` once its require named that core, then `backend/window` - once its require named stilus — which is CONTRIBUTING's "When a require - line does have to move", and is what the next new module will need too. - -**A domain is ordered, and an axis's direction is `scale.Reverse`.** `Domain`, -`LogDomain`, `SymLogDomain` and `Zoomer.SetDomain` all order the bounds they are -given. Writing them backwards to flip an axis half-works, which is why it is not -allowed to: `Map` and `Invert` mirror, and then `Zero` and `Nice` reorder the -pair, the containment test in `Ticks` drops every tick there is, and the first -pan turns the axis back round. What reverses is the device range — see -[ADR 0075](docs/adr/0075-an-axis-has-a-direction.md). Anything that walks ticks -across a panel walks them in **screen** order for the same reason: a tick -sequence is ascending by value, and on a reversed axis that is right to left. - -**An axis break is off until the renderer switches it on, and a value inside -one is not missing.** `scale.Break`, `scale.Fold` and their time forms keep -`Map` continuous: a value in a cut maps linearly across the gap and the panel's -clip hides it, which is what keeps `Invert` exact and a bar across the break one -bar. Do not "fix" that by answering NaN or `Defined == false` — a point there -would vanish silently and the tall bar the break exists for would be cut. The -gap is a device length the scale cannot know, so `render.breakGaps` sets it -through `scale.Breaker` once per render, and sets it **off** under any coord -that is not `coord.Breakable` and on every second axis: a break drawn without -its mark is an axis whose ruler is wrong where nobody says so. The cuts are -resolved on the stack of every call rather than cached, so a pan needs nothing -invalidated and a snapshot shares nothing it writes; per piece, `place` and the -endpoint snap apply exactly as they do to a whole axis. With no active cut, -`framedCartesian.Clip` is the panel rectangle and its furniture is two-point -polylines — which is why no golden file moved, and why that branch must stay. -See [ADR 0083](docs/adr/0083-an-axis-break-is-marked-or-not-drawn.md). - **Scales place a value with one explicit rounding, and it is not redundant.** `scale.place` writes `rlo + float32(float32(t)*(rhi-rlo))`. The inner conversion looks like a no-op — `t` is already being converted — and it is not: @@ -172,11 +104,6 @@ architectures by a chosen sample rather than by a bit. The same rounding is therefore forced in LTTB's own area computation. Do not "simplify" either one away; nothing in the toolchain will tell you that you have. -**Scales snap their endpoints.** `Map` returns the exact range bounds for the -exact domain bounds. Without that, a tick on the plot edge lands a float32 ulp -outside it and gets culled. There is a test; do not "simplify" it away. Every -scale does this. - **There is one layout solver, and every chart goes through it.** `layout.Compute` is `layout.Panels` over a one-by-one grid, and `render.Draw` resolves a single-panel chart into a one-panel grid. That is deliberate — see @@ -184,279 +111,12 @@ resolves a single-panel chart into a one-panel grid. That is deliberate — see case" reintroduces exactly the divergence this arrangement exists to prevent, and the golden files would only cover one of them. -**Panels sharing an axis share the scale object.** So the device range is set -per panel, twice: once before the furniture pass and once before the data pass. -Dropping the second call leaves every panel but the last drawing its data where -the last panel's axis is. There is a test. - -**A dependency arrow is routed in device space, a curve label is placed there, -and a nearest-neighbour partition is cut there; those three are the whole -list.** Everywhere else a geom computes a -midpoint, a corner or a staircase step *before* the coord, because those are -statements about the data — `geom.stepColumns` is the canonical case. -`geom.Depends` puts its two *ends* through `coord.Point` like every other mark -and then joins them with an elbow whose corners are device points and whose stub is in pixels, because there is -nothing in data space between the finish of one task and the start of another: -the route is a reading aid rather than a claim about any value in between. The -direction out of each bar is **measured** from its own two edges rather than -assumed, which is what makes a reversed axis turn both ends together and what -makes one routing function serve a gantt drawn down the page as well as across -it. See [ADR 0068](docs/adr/0068-gantt-charts.md). - -The second exception is `geom.LabelLevels`, whose argument is sharper. A label -on a contour is turned to the curve's **tangent**, and a tangent in data space -is not the tangent on screen: under `coord.Polar` and `coord.Smith` a curve that -is straight in the scaled pair is bent on the panel, so an angle chosen before -the coord would write the label across its own line on exactly the two coords -the feature exists for. `geom.curveLabeller` therefore reads the device points -the mark is about to stroke and nothing else — which is also why one helper -serves a traced lattice and a formula. See -[ADR 0073](docs/adr/0073-labels-on-a-curve.md). - -The third is `geom.Voronoi`, and its argument is the treemap's rather than -either of those. A cell's whole content is that its boundary is **halfway -between two dots**, which needs a length — and the two axes of a chart are not -obliged to share one: there is no distance between a millimetre of rain and a -kilometre of easting. Cutting the partition in the scaled pair and stretching -it into the panel is an anisotropic map, which takes perpendicular bisectors to -lines that are not perpendicular bisectors, so every boundary on screen would -be halfway between nothing. The sites go through the scales and `coord.Point` -like every other mark's positions; only the partition between them is device -geometry, which is why `stat.Voronoi` runs in `Build` against `Frame.Area` — -the fourth stat to do so, beside the hexagonal lattice, the beeswarm's offsets -and the treemap's squarify. The honest cost is that the picture depends on the -panel: a colourbar narrows the plot area and the boundaries move. See -[ADR 0080](docs/adr/0080-nearest-neighbour-cells.md). - -**A progress layer paints twice over, and that is what keeps the batching.** -`geom.ProgressBy` draws every cell at the unfinished alpha and the finished -part of every cell at full strength on top, in two passes — not one composite -shape per cell. `geom.groupByRect` batches by colour, and a shape per cell -would be a drawing call per cell and a per-mark colour in the IR, which is what -[ADR 0007](docs/adr/0007-per-mark-colour.md) refuses. The fraction grows from -the edge the *row* named first, which is why `geom.edgesOn` exists beside -`spanOn`: the two return one pair of edges in the order the data has them and -in the order the screen has them, and filling from the screen's side would say -a task on a reversed axis had started at the end. - -**A layer may hold data its `Source` does not.** `geom.Depends` reads a second -table, and `geom.Desc.Links`, `spec.Layer.Links` and -`a11y`'s row count all had to learn it. Three things there are load-bearing: -the link table is **never hoisted** in a document, because two dependency -layers over one plan are two sets of constraints; `Subset` cuts the *task* -table and leaves the links alone, so a constraint whose other end is in the -next panel resolves to nothing and is dropped; and the layer reports **no -rows**, because the row it would report belongs to the table `Source` does not -hand out. - -**A track shares the panel's scale object, and that is the whole feature.** -`Plot.tracked` gives every track panel the chart's own scale for the axis it -runs along — `c.X` for a bottom or top band, `c.Y` for a left or right one. A zoom reaches a scale -through `scale.Zoomer.SetDomain`, so one object means the panel and its bands -move together by construction rather than by two handlers agreeing. Cloning it -there — which is what `freeScale` does for a *free facet axis*, and looks like -the tidier thing to do — compiles, draws a chart that looks right, and breaks -every acceptance criterion the feature has. The same trap is why -`scale.Cloner` and `scale.Snapshotter` are opposites; see -[ADR 0031](docs/adr/0031-tracks.md). A track's own Y is unzoomable for free, -because `zoomAxis` no-ops on a scale that is not a `Zoomer` and `scale.Ordinal` -deliberately is not one. There is a test for each half. - -**A fixed row's arithmetic is written to be bit-identical when nothing is -fixed.** `layout.rowHeights` divides once and multiplies once rather than -summing, because a float32 sum of n equal terms is not always their product, -and the guide column is measured against that total. Rewriting it as the -obvious loop moves every golden file in the repository by an ulp — which the -structural comparison will *not* catch, because it tolerates exactly that. - -**A Smith coord makes a scale's range its own domain.** `coord.Smith.Frame` -calls `SetRange(lo, hi)` with the scale's *own domain*, so that `Map` is the -identity and the pair reaching `Point` is a normalised impedance rather than a -pixel. Choosing what the interval means is what a coord does — Cartesian chooses -a distance along an edge, Polar chooses radians and pixels — so this is the -mechanism and not an exception to it. Two consequences: the coord assumes an -**affine** scale on each axis (a log Smith axis is a different chart, and the -coord does not guess which), and a zoom moves nothing, because the next `Frame` -re-derives the range from the domain it was just handed. Anything new that -assumes "a scale's range is in pixels" is wrong under this coord and probably -under the next one. See [ADR 0033](docs/adr/0033-smith-charts.md). - -**A map's default projection is the equal-area one, and that is a decision -rather than a preference.** `coord.Geo("")` and a document naming no projection -are both `coord.DefaultProjection`, which is `Mollweide`: on a map, how much -ground a thing covers reads as how much of it there is, so the three -projections that draw a region larger or smaller than its share are asked for -by name. Do not "simplify" it to the affine one because that is the cheapest -map to compute. - -**A map makes a scale's range its own domain too, and then cuts it.** -`coord.Geo.Frame` calls the same `identityRange` the Smith coord does — a -projection is not separable, so the pair reaching `Point` has to be the degrees -themselves — and then *narrows* its own copy to what the projection reaches: -±85.051129° for Mercator, a turn of longitude about the centre for everything. -`Extent` reports that cut rather than the scale's range, so a mark asked to -span the axis spans the map instead of running off to the infinity a Mercator's -pole is. Three things follow. An axis here wants a **linear** scale, for the -Smith chart's reason. A place the projection has no image for — the far side of -a globe, a latitude past the cut — is **NaN**, so anything new that assumes -`Point` is finite is wrong under this coord first: the graticule is drawn by a -walk that starts a new subpath wherever the image resumes, which is why a -meridian on a globe is one shape holding several subpaths. And the latitude -clamp is *a hair inside* the cut, because the domain travels as a float32 and -the nearest float32 to 85.051129 is outside it — clamp to the cut itself and -the map loses its southern edge. Everything the coord draws for **itself** — a meridian, a parallel, the side of -a cell, the outline of the map — is walked in longitudes measured from the -centre meridian rather than in the caller's, and `geo.relW`/`relE` are that -interval. A walk in the caller's longitudes jumps the width of the picture -wherever theirs crosses the map's cut: a Pacific-centred world map has a domain -of −180° to 180° and a map from −30° to 330°, and its parallels came out drawn -straight back across the world. Data points go through `Point`, which wraps; -anything the coord builds goes through `pointAt`, which does not. Unlike a -Smith chart a map **zooms**, because its picture is derived from the domain -rather than fixed: the fit is -recomputed every `Frame` by walking the image of the domain — a lattice, plus -the rim for a globe — rather than from a per-projection formula, and one scale -factor serves both directions because a map stretched to fill its panel is a -projection nobody chose. See -[ADR 0081](docs/adr/0081-a-map-projection.md). - -**A coord holds no scales, with one exception, and it is the one with more -than two axes.** `coord.Parallel` carries a scale per dimension because that is -what a parallel-coordinates panel is; every other coord borrows the panel's two -and re-ranges them (`smith.identityRange`, `ternary.pin`). Two things follow -and both are load-bearing. A mark reaches those scales through -`coord.Dimensions` — `geom.Training.Dims` at train time, `f.Coords()` at build -time — rather than through anything new on `Coord`, which never gains a method. -And the panel's own ticks are silenced **by the coord**: left to themselves -they would number an axis index and a fraction of an axis. A theme that turns -them off as well gives back the gutter a panel reserves for tick labels it -never writes, and the dimensions keep their numbers through it because -`Furniture.FamiliesAreTheAxes` says the families *are* the axes — ADR 0070's -label gate, amended. A coord whose family is a third reading beside two -labelled axes leaves that flag alone, which is why a ternary chart is -unchanged. See -[ADR 0078](docs/adr/0078-a-coord-with-more-than-two-axes.md). - -**A coord may draw one grid line per tick, and may label nothing the scale did -not.** `render.drawAxes` walks `for i, t := range xTicks`, takes the geometry -from `fur.GridX[i]` and the *text* from `t.Label`. That is why a Smith chart's -columns are an impedance rather than the reflection coefficient an instrument -reports: with Γ on the axes the impedance grid would have no tick behind it. -Before reaching for a second grid family, read ADR 0033's "Revisit if" — -widening this is one decision, not several. - -**And check first whether the family is furniture at all.** -[ADR 0050](docs/adr/0050-locus-annotations.md) is the answer for the four -families 0033 declined, and it widened nothing: a curve given by a formula -rather than by a tick is an *annotation* defined in data space, so the coord -draws it through `Point` like any other mark and `render` never sees it. That is -what `geom.Locus` is, and it is why there are VSWR circles now and still no -second tick list. -A `Shape` may also hold more than one subpath, which is how a ternary chart's -third grid family is drawn without a third tick list -([ADR 0051](docs/adr/0051-barycentric-coord.md)). What genuinely needed the -wider seam was a labelled *furniture* family with no tick behind it — a -ternary's third ladder, and what everyone assumed was a projection's graticule -— and [ADR 0070](docs/adr/0070-a-third-labelled-family.md) spent it once for -all of them. [ADR 0073](docs/adr/0073-labels-on-a-curve.md) had narrowed it to -that much first: a family drawn as a **mark** writes its own levels along its -curves now, with the curve gapped for the text, and `render`'s one tick list -per axis is untouched. The graticule turned out not to be a customer: with -degrees on the axes a meridian *is* a longitude tick's own shape, exactly as a -polar ring is a Y tick's. What a map does raise as a family is the **edge of -the map** — a globe's rim is where the sphere turns away rather than a meridian -anybody can label, and it is drawn nowhere else -([ADR 0081](docs/adr/0081-a-map-projection.md)). - -**A locus is sampled against the panel, and the Nichols families are refined -rather than walked.** `stat.Extent.Steps` is a tolerance rather than a count for -them: a Nichols chart is the log-polar view of a circle, and the arc that passes -near the origin is a hair of the circle and is the whole plunge to −∞ dB, while -the rest of the same circle is a smooth curve a few dozen samples describe. A -uniform walk resolves one or the other — the −1° N contour sampled uniformly -stops dead at −6 dB, hanging in mid-air well above the bottom of the panel — so -`nichols.refine` bisects until the step is a few pixels and stops at a step that -leaves the window. Do not "simplify" the window rule away: it is also what -*bounds* the refinement, because the arc approaching the origin is self-similar -and a rule that only looked at the step would halve for ever. The other half is -`emit`'s ninety-degree break, which is how the branch point at L = 0 is found -without looking for it. See [ADR 0050](docs/adr/0050-locus-annotations.md)'s -amendment. - -**PDF is figure's own emitter, not `gg-pdf`.** That library cannot draw -geometry — its path operations reach a stub in `gxpdf` — so the roadmap's plan -of routing PDF through gg's recording API would have produced pages with tick -labels and nothing else. `gg/recording` therefore stays out of `backend/gg`, -and [ADR 0006](docs/adr/0006-gg-coupling-surface.md)'s import rule is unchanged. -See [ADR 0009](docs/adr/0009-pdf-backend.md) for the evidence. - -**The PDF backend measures with the font it draws with, whichever font that -is.** `internal/fontmetrics` carries Helvetica's advance table and PDF's -base-14 Helvetica is that font; an *embedded* face measures through -`embeddedFace`, out of its own `hmtx` and `hhea` -([ADR 0038](docs/adr/0038-embedded-fonts.md)). Every other backend -approximates; this one does not, and the promise has to survive the font -changing — measuring against Helvetica and drawing in Noto Sans sizes every -margin from a typeface the document does not contain. Do not "improve" either -half by measuring with something else. - -**The raster backend's embedded fonts do not cover everything, and a rune they -cannot draw is written as `?`.** The Go fonts cover Latin, Greek, Cyrillic, the -common punctuation and the mathematical operators; they do not cover CJK, and -they do not cover the mathematical angle brackets U+27E8 and U+27E9 a Bloch -sphere's `|0⟩` is written with. So the SVG of a chart and the PNG of the same -chart can differ in their labels — the vector viewer asks the reader's own -fonts and a PNG has nobody to ask. `stilus.WithFallbackFont` (and the -deprecated `gg.WithFallbackFont`) supplies the coverage; -the substitution is `backend/pdf`'s rule for a rune outside WinAnsi, so a -missing glyph is visible rather than silent. `TestAMissingRuneIsAQuestionMarkUnlessAFallbackHasIt` -in backend/stilus and `TestTheEmbeddedFontHasNoMathematicalAngleBrackets` in backend/gg -pin the gap, so a font change that closed it would be noticed rather than -leaving the fallback guarding nothing. See -[ADR 0038](docs/adr/0038-embedded-fonts.md)'s amendment. - -**An embedded font's glyphs are numbered on first use, and that is what makes -writing a PDF one pass.** A content stream names glyphs by id and a subset's -ids depend on what the whole document drew, so a writer that waited would have -to buffer every text run in the file. Numbering on first use inverts it, and -`sfnt.Font.Subset` honours the order it is given — which is also the only order -that is a pure function of the drawing, per ADR 0012. Two things there are -load-bearing. A composite glyph's component ids are references into the same -font and are **rewritten** to the new numbering; copying one unrewritten draws -a plausible wrong letter, which is the worst kind of wrong. And the subset tag -comes from the face's index rather than from a hash of the glyphs, because a -hash would make the file depend on which labels the chart happened to draw and -the golden tests compare bytes. - **Colour ramps interpolate in linear light.** `palette.Lerp` decodes sRGB, blends, and re-encodes. Averaging the encoded bytes instead is about 20% too dark at the midpoint, which shows up as a band across a gradient. gg composites in linear space for the same reason. There is a test that pins the midpoint of black-to-white at 188, not 128. -**A geom must not assume a scale accepts every finite value.** A log scale has -no position for zero and returns NaN from `Map`. Geoms ask `scale.Definite` -through `geom.defined` and treat such a row as missing, so a NaN coordinate -never reaches a backend — [ADR 0008](docs/adr/0008-categorical-axes.md). Adding -a geom means computing `scratch.plottable` once and using it, not re-testing -`finite` per traversal: the traversals have to agree about where the holes are. - -**Per-mark colour batches; it does not widen the IR.** `geom.groupByColor` -emits one drawing call per distinct colour. Adding a per-vertex colour channel -to `ir.Backend` is the thing that record exists to refuse — -[ADR 0007](docs/adr/0007-per-mark-colour.md). - -**Decimation happens in `Build`, never in `Train`.** A geom trains on every row -and reduces only when it draws, so an axis reports the data rather than the -subset that survived — [ADR 0011](docs/adr/0011-decimation.md). Reducing in -`Train`, or in the data layer, would make a chart's axis depend on how wide the -chart is, and there is a test that catches it. - -**The reduction runs on device coordinates.** A pixel column is the unit the -whole exercise is about, and on a log axis equal steps in data are not equal -steps on screen. `stat.LTTB` and `stat.MinMax` are generic over `float32` and -`float64` precisely so the device-space path costs no conversion. - **Everything sized by the data comes from a pool.** `geom.scratch` holds the per-Build buffers and is returned at the end of the call, which is what makes a redrawn chart allocate the same handful of times over a million rows as over a @@ -495,19 +155,6 @@ not, because it is for a free facet axis. They are opposites and neither is a substitute for the other. A scale implementing neither still works — the chart is drawn serially. -**A density-raster figure embeds a PNG inside its SVG, and that payload is -compared as pixels.** `docs/images/density.svg` carries a base64 deflate stream, -and deflate output is the standard library's business rather than figure's — -the same chart on two Go releases produces two different streams, which is -exactly how this first went red. So the gallery lifts embedded payloads out of -both documents and compares them with the same per-channel tolerance the PNG -half already uses; the vector half, including the `` element's own -position and size, is still compared exactly. See -`backend/stilus/cmd/gallery/embedded.go`, and note this is not a widened tolerance -but the same one applied to pixels rather than to an encoding of them. It is -also why there is no golden SVG for a density chart in `testdata/golden`: -pinning `compress/flate` is not a test of figure. - **Do not compare device coordinates with `==` in a test.** `scale.place` now removes the fusion that a scale itself introduced, but everything downstream of it — a Catmull-Rom control point, a bar's half-width, a boxplot quantile — is @@ -517,368 +164,6 @@ tests carry `sameRect`/`samePoint` at `svgdiff.DefaultTolerance` for this, and comparisons were green on amd64 for three milestones and red on every macOS run. -**A geom that holds data implements `geom.Faceter`; one that does not, must -not.** Faceting splits the layers that have rows and replicates the ones that -do not, which is why an `HLine` appears on every panel. Adding `Source`/`Subset` -to an annotation would make a threshold vanish from every panel but the one its -value happens to fall in. - -**A watched render must draw exactly what an unwatched one draws.** -`interact.Index.Watch` wraps a backend and indexes what it sees; every method -forwards first and indexes second. There is a test comparing the two traces -call for call, and `TestAWatchedRenderDrawsWhatAnUnwatchedOneDoes` compares the -SVG bytes. A probe that changed anything would silently halve the coverage of -every golden file, the same way a scheduling-dependent panel order would. - -**A watched render is serial, on purpose.** `render.Chart.Observer` forces the -serial path in `concurrent`. The observer is told which layer is drawing so a -caller can attribute the calls that follow; two panels drawing at once have no -order to be told in. Do not "optimise" this by giving each panel its own -observer — the index would then depend on scheduling, and so would every -tooltip. - -**`figure/three` paints in its own order, and `render` did not gain a second -one.** A `three.Layer` is deliberately not a `geom.Geom`: a geom's `Build` -streams ink, which makes a layer a paint unit, and a projected scene has no -paint unit smaller than the view. So a layer emits primitives into a `Sink` and -one painter projects, orders and draws all of them at once. If a change here -starts wanting `render` to record layers and merge the recordings, that is the -thing [ADR 0010](docs/adr/0010-panel-layout.md) exists to prevent and -[ADR 0056](docs/adr/0056-three-dimensional-charts.md) refuses again. - -**The depth key is the centroid's depth along the view direction, one formula -for every primitive of every layer, ties to the emission index.** Two things -that look like improvements are not, and both were tried: - -*Letting a layer pick its own measure* is two numbers on two scales — they -differ by the height times the view direction's z — so one layer sorts wholly -before the other however the geometry runs. - -*Keying on the centroid dropped to the floor* is the subtler one, because its -argument is half true: that key does vary less over a steep primitive, and it -is monotone along every view ray. It still does not follow, and this is the -sentence to remember — **monotone along a ray says nothing about two -centroids, which lie on two different rays.** Two sheets at different heights -whose footprints overlap without coinciding come out backwards. -`TestASheetIsNotPaintedOverTheOneInFrontOfIt` is that case with the numbers in -it; run it before believing any replacement key. - -**What the key promises is smaller than "correct", and the difference is the -part to know.** Two primitives are ordered correctly when their depth *ranges* -are disjoint. Where the ranges interleave, no per-primitive number decides -between them and this package does not split them apart — splitting is a BSP -tree, which is a renderer. Real charts stay inside the promise because the -shapes emitted here are already small: one quad per cell, one face per bar -side, one primitive per path segment. The case that leaves it is several layers -stacked over a grid coarse enough that one cell spans more depth than the -layers are apart. - -**Letting a layer pick its own depth measure is the same bug one level up.** -Two layers keyed by two different formulas are two numbers on two scales, and -merging them is arithmetic rather than geometry: one layer sorts wholly before -the other however the geometry runs. `TestASurfaceAndAPathAreOrderedAgainstEachOther` -is what catches it, and it is invisible in any picture with one layer in it. - -**The occlusion tests cast rays; they do not restate the sort.** A test whose -expected answer recomputes the ordering rule proves only that the sort sorts. -`checkOcclusion` intersects the view ray through each sample point with the -plane of every primitive covering it and insists the nearest is painted last — -so it fails for any key that gets the visible picture wrong, including the one -the implementation happens to use. Keep it that way when the key changes. - -**The depth key is computed in float64 and stored as float32, on purpose.** The -narrowing turns a near-tie into an exact tie, and an exact tie is broken by -emission index, which is the same on every architecture. A float64 key would -let two primitives a ulp apart order one way on arm64 and the other on amd64 — -and `internal/svgdiff` tolerates exactly that much coordinate difference, so -the reorder would *not* be caught. It is `scale.place`'s and `stat.LTTB`'s -lesson in a third place. - -**Faces batch by run, never by colour — and only where the merge is provably -invisible.** `geom.groupByColor` merges every mark of one colour into one call -because order within a flat layer does not matter. In a scene the order *is* -the thing being computed, so only primitives already adjacent in it are -candidates at all. Adjacency is not sufficient either: two adjacent faces can -still overlap on screen, and a run that draws all its fills and then all its -outlines puts a farther face's outline over a nearer face's fill, while a union -filled once is not what several translucent fills compose to. So `mergeable` -takes the run only for an opaque, unoutlined style, where the colour is the -same everywhere in the union either way. Widening that condition is how the -painter's order gets undone by the optimisation meant to be invisible. - -**A surface fills and outlines only when asked.** `interact` ranks a stroked -vertex above the area it outlines, so a mesh that always drew its own outline -would report a corner on every hover. It is `geom.Rect`'s rule and it is -load-bearing rather than cosmetic. - -**`three` announces its panels with nil X and Y.** A projected scene has no -screen axes to invert a device position through, and `interact.Index.At` -already checks before it inverts — so a hit reports `Kind`, `Layer`, `Series` -and `Row`, and leaves `Hit.X` and `Hit.Y` at zero. Filling them in with the -scene's scales would name a value nothing was drawn at. - -**The cube is fitted to its own circumscribed sphere, not to its projected -box.** The sphere's radius is a constant of the scene and the box's is not, so -the scene keeps its size while it turns. Fitting the box is the tighter fit and -makes the picture breathe under the reader's hand, and an instrument whose -scale moves while it is being read is not one. `three.Dolly` is how the reader -reclaims the room this costs. - -**A `three.Live` keeps its own scratch; a one-shot render borrows from the -pool.** A scene large enough to be worth turning is megabytes of vertex arena, -so drawing one allocates enough between frames to run a collection — and -`sync.Pool` is emptied by one. A chart redrawn on every pointer move would find -an empty pool and rebuild its arenas every frame. `BenchmarkOrbit32` and -`BenchmarkOrbit96` are what catch it going back. - -**A scene's scales are trained once per frame however many views look at it.** -`scale.Scale.Train` accumulates, so training per view gives every layer as many -times its weight as there are cameras — and the symptom is a domain that -changes when an author adds a picture, which looks entirely reasonable and is -wrong. There is a test that counts the calls. - -**A rectangular clip must reach a raster backend as a rectangle.** gg -rasterises a path clip into a coverage mask and then consults that mask on -every drawing call inside the clip, so a figure costs its drawing calls times -its area; a rectangle it can express as a scissor and the per-pixel cost goes -away. Every clip this library pushes is a rectangle — a panel, a facet cell, -one view of a scene — so `backend/gg` recognises one with -[`ir.Path.AsRect`](ir/path.go) before falling back to the mask. The shape of -this bug is worth remembering: it is invisible at a hundred drawing calls and -it turned the gallery's ten-minute test budget into a failure at three -thousand, and the stack it fails in belongs to the rasteriser, not to the code -that caused it. - -**A shaded surface is one drawing call per quad, and a trajectory one per -segment.** The IR carries no per-mark colour -([ADR 0007](docs/adr/0007-per-mark-colour.md)), so faces that differ in shade -cannot be merged, and a path with one depth would sort as one thing. That is a -cost model rather than a bug, but it is still a count, and -`backend/stilus/cmd/gallery`'s tests render every figure about five times over in -each of two formats. `TestNoFigureIsDrawnWithTooManyCalls` is the wall, and it -counts calls rather than seconds because a timing assertion on a shared runner -is a gate people learn to ignore. - -**A projected axis labels itself only if at least two of its labels survive.** -Turn a scene until an axis points at the reader and it projects to a few -pixels: every value on it lands in the same place. A pile of overlapping -numbers there looks wrong at a glance and a reader discounts it; the single -number a greedy collision pass leaves behind looks like a label and reads like -one, while naming a position that cannot be told from any other on that axis. -So `three`'s label pass runs twice, once to count and once to draw, and an -axis that keeps fewer than two gives its boxes back to the next axis. Its -line, its tick marks and its title stay: a mark is a position, a number is a -claim about how much room there is. - -**An axis title is placed past its own tick labels, and both the room and the -placement come from `furnitureReach`.** They were computed separately once: the -title was put a guessed distance out, its box overlapped the labels', it won -the collision because a title is placed first, and the axis quietly lost most -of its numbers. A guess and a measurement of the same distance are two numbers; -that function exists so there is one. - -**Hit-testing indexes one mark per subpath, not one per call.** A layer draws -all its bars in a single path, because `geom.groupByColor` batches by colour. A -mark per call would make the row of bars one shape, so pointing at the fourth -bar would report whichever corner of whichever bar happened to be nearest. -There is a test. - -**A geom reports its rows separately from what it draws, and that is the -whole point.** `geom.Rows` takes the positions a row landed at, not the points -of a drawing call — a smoothed line is a Bézier path whose control points are -not measurements, a staircase draws two points per row, a bar is four corners -around one value. Attributing rows to a call's points would attribute them to -whichever encoding the geom happened to use, and would be wrong for three of -the six geoms that have rows. There is a test per geom. - -**Row reporting is gated on `Frame.Rows != nil` at every step.** `acquire(f)` -records it on the scratch as `wantRows`, and `rowsOf`, `sourceRows` and the -interpolated series' row list all check it. An ordinary render must keep -costing exactly what it did — `BenchmarkFrame1k` did not move when row -identity landed (76 allocations then; the current count is in -[docs/benchmarks.md](docs/benchmarks.md)), and `BenchmarkWatchedFrame` -against `BenchmarkWatchedFrameRows` is pinned flat. - -**A row is reported in the caller's table, not in the cut figure made.** -Faceting cuts each layer with `data.Rows`, and a row number relative to that -cut is a row number in a table nobody holds. `series.origin` comes from -`data.Origins` and `series.rowAt` resolves through it. A geom that collects its -own element list — a scatter, a bar, both for per-mark colour — must report -through `scratch.sourceRows` rather than handing over the element numbers: the -two lists look identical and mean different things, and a faceted chart is -where that shows. - -**A pinned scale domain skips nicing, and that is not an oversight.** -`scale.Zoomer.SetDomain` sets `pinned` as well as `fixed`, and `effective()` -returns the pinned domain before nicing or zero-forcing get a chance. An axis -that snapped to round numbers after every wheel notch would not follow the -pointer, and on a log axis nicing rounds the view out to whole decades. `fixed` -alone stops *training*; `pinned` also stops *framing*. - -**A second axis is a scale on the chart and a binding on the layer, and five -places had to learn it.** `render.Panel.axesOf` asks the layer through -`geom.Describe` — not a method on `Geom`, which never gains one — so the chart -and the document agree by construction -([ADR 0037](docs/adr/0037-secondary-axis.md)). The two directions are -independent: a layer may name `OnX2` and `OnY2` together. Four consequences are -load-bearing. `Panel.setRange` frames the coord against the **secondary** pair as -well as the primary one, or the layers on a second axis map through a scale -with no device range. `coord.Opposite` is an optional interface and `Polar` deliberately does -not implement it — a ring has no far side — so a chart that names a second axis -under a polar coord simply does not draw one. The second axis draws **no grid -lines**, and there is a test comparing the count against a one-axis chart: -two ladders of rules at different values are a moiré, and which scale a line -belongs to is unanswerable by looking. And the scales on `render.LayerInfo` are what make a -hit report the right number — an index that inverted every mark through the -panel's own scales would name 4200 on a chart whose right axis reads 12 %, -which is wrong by a *unit* on the feature whose whole purpose is that the units -differ. The layout's right and top gutters are zero for a column or row with no -second axis, which is what leaves every golden file unchanged; the guide column -is anchored past the right one, because the width was already reserved and an -anchor on the panel edge puts a legend on top of the labels. A facet's strip -sits **outside** the top gutter: a strip between a panel and its own tick -labels reads as though it named the axis. - -Steering has to move both. `Live.Wheel`, `ZoomTo`, `PanBy` and `Autoscale` all -reach `Panel.Y2` as well as `Panel.Y`, or the two series slide apart under the -reader's hand — a chart with two axes is one chart, so a zoom is one zoom. -`interact.Panel` learns about the second axis from the scales on -`render.LayerInfo` rather than from `Observer.Panel`, which carries the panel's -own two. - -**An error bar's orientation is its encoding, and its bounds are derived in -`Train`.** `Y2`/`ErrorBy` runs it vertically and `X2`/`ErrorXBy` horizontally — -the rule `Rect` already follows about its edges, which is why there is no -orientation option to contradict — and naming both is `ErrBothAxes` rather than -a guess that depends on option order ([ADR 0036](docs/adr/0036-error-bars.md)). -The bounds are computed in `Train` because the axis has to describe them: an -interval whose top runs off the plot is the reading the chart was opened for, -which is the same boundary ADR 0019 draws for a stack's totals. `errorGeom.half` -is measured once per `Train` out of a buffer the layer keeps — `smallestGap` -sorts, and asking it per row is what made a bar layer quadratic once already. -And every segment goes through the coord: a cap drawn as two device points -would be a straight line under a polar coord, where the mark is an arc. - -**A tick label has two spellings and the Go one wins, but both are written -down.** `scale.Format` takes a function and `scale.NumberFormat` takes a spec; -`Desc` carries `Formatted` *and* `Format`, because a Desc that dropped the spec -when a function was present would silently change the chart the day somebody -deleted the Go code — [ADR 0035](docs/adr/0035-label-format-and-locale.md). Two -things there are easy to break. A spec that names no precision must keep the -axis's own, which is derived from the tick *step* and is what keeps a column of -labels aligned: that is why `autoFor` returns a description rather than a -formatter, and why the two meet in `numberFormat.label`. And an unlocalised -scale must take the *old* path exactly — `punctuate` with English's separators -is the identity on `strconv`'s output, and a time scale with no locale calls -`time.Format` itself rather than the layout-splitting path — because that is -what leaves every golden file in the repository unchanged. There is a test -asserting that naming English changes nothing; do not "simplify" the default -branch away. - -**A locale reaches a chart's axes by a walk, and the walk is the feature.** -`figure.Locale` localises the scales in the *chart description*, after it is -built, which is what reaches a track's own scale and a free facet axis's clone -— neither of which the caller holds. Setting it in `Plot.X` instead compiles -and misses both. It happens before the parallel path, and a locale is read -from then on and never written, so there is nothing for `Snapshotter` to fix. - -**A null is a missing value, and only a numeric column can say so by itself.** -`""` is a string somebody may have measured and the zero time is an instant, so -absence in a text or temporal column is stated beside the values through -`data.Column.Nulls` rather than inside them — [ADR 0034](docs/adr/0034-null-values.md), -[ADR 0061](docs/adr/0061-columns-are-one-value.md). -It is read in exactly one place, `geom.column`, which writes NaN whatever the -column is stored as; every policy, traversal and mark downstream is the -machinery that already handled a NaN, and no geom knows about nulls. Three -things there are load-bearing. A column with **no** nulls must answer `ok == -false`, because that answer is what every reader decides between the borrowed -column and a copy on — a mask of all false makes a chart copy a column to -change none of it. `masks` compares the mask against the values before copying, -so an Arrow numeric column, whose nulls are already NaN, is still handed on -untouched. And `series.detach` copies before writing, because `s.x` may be the -caller's own slice: a neighbouring column's null takes a row's *position* away, -and doing that in place edits the table rather than the chart. A genuine `""` -is still a category and there is a test for it — dropping every empty string -passes every null test and is a different feature. - -**`data.Stream` is deliberately not a `data.Source`.** A Source is read column -by column over several calls, and a table appended to between two of them -disagrees with itself. `Snapshot` freezes and swaps; `Source()` reads whatever -the last snapshot froze. Making Stream implement Source would compile, and -would produce a chart with more timestamps than values under load. The two -buffers are reused, so a snapshot is valid only until the next one — that is -the price of the frame costing no allocations, and it is why Snapshot belongs -between frames rather than during one. - -**Unwrap a ring buffer before rewriting it, not while.** `Stream.compact` -resolves every slot number first and rewrites the columns afterwards, and takes -the *old* window as a parameter. `at` answers from the ring's current length, -so rewriting the first column changes the answer for the second — a bug that -only appears on the second column, and only after the ring has wrapped. There -is a test. - -**Damage is per drawing call, and reports `ok == false` rather than guessing.** -`ir.Damage` compares two recordings call for call; a different call count, a -different kind, or a moved transform means the chart's *structure* changed and -the answer is a full repaint. Do not make it clever about realigning: a list of -rectangles that describes half a frame is worse than repainting the frame. - -**`ir.Partial.Damage(nil)` means the whole frame, and an empty list never -arrives.** A frame identical to the last one is not painted at all rather than -painted with no damage, which is why the nil case is unambiguous. - -**A Stroke cannot be compared with `==`.** It holds a dash slice. `ir` carries -`Stroke.same`, `Fill.same` and `MarkerStyle.same` for this; reach for those -rather than adding a comparison that compiles today because the field you would -have missed happens not to be there yet. - -**The JSON spec writes what a mark uses, not what it was given.** A geom -accepts every option and ignores the ones it has no use for, which is what -keeps the option set one namespace; a *document* listing a line's whisker -extent would read as though that meant something. `spec.writeMarkProps` decides -per mark. Adding an option means adding it there too, and the round-trip test -in `spec/` is what catches forgetting. - -**`geom.Desc` and `scale.Desc` are complete, not partial.** Every field with a -non-zero default — `BarWidth`, `Whisker`, `Outliers`, `Extend`, `Opacity` — -carries the value the layer is actually using, so nothing downstream has to -know what the defaults are. `Opacity` is `-1` when unset, matching `config`. - -**The canvas backend builds one path string per drawing call.** Crossing the -WebAssembly boundary is what costs in a browser: a five-hundred-point line is -one `Path2D` and one `stroke`, not five hundred `lineTo` calls. There is a test -that fails if a chart over five hundred rows starts making more than a hundred -context calls, and one that fails if `beginPath` reappears. - -**`backend/canvas` is empty except on js/wasm, and that is what the doc.go is -for.** Every implementation file carries `//go:build js && wasm`; `doc.go` -carries no constraint, so `go build ./...` on a server has a package to build -rather than an error. Its tests run under node in CI, against a recording -context — node has no canvas, and a test that needed one would be a test nobody -could run. - -**`backend/gg` still must not import `gg/gpu`, and the GPU tier is a module -below it.** `backend/gg/gpu` is nested *inside* `backend/gg` so that the raster -backend's own module graph stays gg, `x/image` and the core; importing the tier -is the whole opt-in — [ADR 0022](docs/adr/0022-gpu-tier.md). Moving the blank -import up one directory would put `wgpu`, `naga` and `goffi` into every program -that renders a PNG, and would cost the module its js/wasm target. - -**gogpu is pinned exactly, and its pin is tied to gg's.** `backend/window` -requires gogpu v0.52.1 because that is the release whose `gputypes` and -`gpucontext` resolve to the versions gg v0.52.5 compiles against. A newer gogpu -pulls a `gputypes` that gg at this pin does not build with, and the failure is a -wall of "too many arguments" inside gg's internals rather than anything naming a -version. Upgrade the two together or not at all. - -**A backend wrapper hides the optional interfaces of what it wraps.** `Damage`, -`Resize` and `Describe` are all reached by type assertion, so a wrapper that -does not declare them silently drops them. `ir.Recorder` and `interact`'s probe -both forward `Describe`; `render.Draw` keeps the *unwrapped* backend for the -semantics question, because it wraps the backend to install a typesetter. A -`` that quietly disappears from interactive charts only is what this -costs when it is forgotten, and there is a test. - **A description costs a pass over the data, so a render must not take one.** `Plot.Describe` is a method that does work rather than an option that sets a flag: it reads every plotted column. The title alone is free and is always @@ -887,76 +172,6 @@ description into `chart()` so that every frame recomputes it would put a data pass in the frame budget, and `TestARenderDoesNotAllocatePerPoint` would not notice — it counts allocations, not passes. -**Redundant encoding is a default, not an override.** `theme.Redundant` fills in -a dash and a marker ladder, and `config.dashFor`/`markerFor` use them only when -the layer set neither `geom.Dash` nor `geom.Shape`. That is why `config` carries -`markerSet` beside `dashSet` and why `geom.Desc` carries `MarkerSet`: a circle -is both the zero value and a shape somebody may have asked for, and without the -flag a round trip through the spec turns an unset shape into a pinned one. - -**A time domain is nanoseconds since the scale's origin, not since 1970.** -`scale.Origin` moves it, `scale.ValueOf`/`InstantOf` convert across it, and -`geom.column` uses them — so a time column is read in the axis's own space. -The default origin is the Unix epoch, which is exactly `scale.Nanos`, so nothing -changes for a scale that never asked. What does change is that `scale.Nanos` is -the wrong conversion to reach for near a rebased axis: the domain values, the -`Invert` results and the `Desc` bounds are all measured from the origin, and the -JSON spec writes it out for that reason. - -**The raster backend draws italic now, and `WithFont` takes three fonts.** -`ir.FontRef.Italic` was ignored by `backend/gg` once, which -was invisible until a typesetter started producing italic runs — at which point -the PNG and the SVG of the same chart would have disagreed in the -documentation. The default set parses `goitalic` alongside `goregular` and -`gobold`; a caller supplying their own passes nil for a style they do not have, -and gets the regular face for it. - -**A typeset label is measured by laying it out.** `render`'s `mathBackend` -answers `Measure` from the typesetter and `Text` from the same layout, so the -margin a title is given is the width the title turns out to have. Measuring the -markup and drawing the notation would leave a fraction hanging out of the -canvas, and nothing would fail. - -**A resized frame is not comparable with the last one.** `Live.Resize` clears -`drawn`, because every coordinate moved and there is no damage to compute. It -also keeps whatever the scales were zoomed to, on purpose: a reader who dragged -a view into place has not asked to leave it. - -**A position adjustment is derived in `Train` and drawn in `Build`, and both -halves are forced.** `render.Draw` trains every layer before it measures -anything, because tick labels need a domain — so a stacked bar's Y scale has to -be trained on the *totals*, or the tallest stack runs off the top of an axis -that describes rows nobody can see. `geom.groups.train` therefore computes the -per-row `(lo, hi)` pair, and `Build` only maps it through the scales. This is -the same boundary ADR 0011 draws for decimation, drawn for the same reason: what -a chart's axis says must not depend on how wide the chart is. See -[ADR 0019](docs/adr/0019-position-adjustments.md). - -**A stacked layer's holes are decided once, and both traversals read that -answer.** `groups.ok` is computed in `Train` and an unplottable row gets `NaN` -bounds, so the cumulative sum and the drawing traversal agree about where the -holes are. A NaN the sum skipped but the draw did not would shift every segment -above it — there is a test, and it compares a table with a hole against the same -table with the row removed. - -**A grouped layer's buffers live on the layer, not in the frame's pool.** The -group index, the row lists and the derived bounds are refilled by every `Train` -out of memory the geom keeps: `Train` runs as often as `Build` does, and a chart -redrawn over a live table would otherwise allocate its group index per frame. -`TestAStackedLayerDoesNotAllocatePerPoint` is what holds that. Note that the -rows of each group are listed once, in `groups.split`, rather than found by -scanning the table per group — the scan is what makes a chart with many series -quadratic. - -**There is exactly one scratch per `Build`, and a helper takes the caller's -rather than acquiring its own.** Two scratches held at once put two objects with -*disjoint* buffers into one pool; whichever comes back in the other's role next -frame has to grow the other's buffers, which is a per-row allocation on the path -whose whole point is not having one. `geom.eachGroup` therefore takes a -`*scratch` parameter. This shipped broken for exactly one commit and cost a -grouped frame 127 kB and seven allocations it did not need; nothing failed -except the allocation gate, which is what the gate is for. - **A gated benchmark measures on one processor, and that is what makes its count reproducible.** `sync.Pool` keeps a private slot per P. A render Gets its scratch and Puts it back on one goroutine — but a frame takes milliseconds, the @@ -977,338 +192,12 @@ gate was steady all along while the benchmark half was not. A pool miss is a real cost that a real chart pays occasionally; it is simply not the cost this gate measures, which is whether a frame allocates *per row*. -**Group order is order of first appearance, and `geom.Order` is the only thing -that changes it.** Map iteration order is not an order; ADR 0012 requires a -parallel render to be byte-identical to a serial one, and `scale.Qualitative`, -`geom.groupByColor` and `boxplot.summarise` all already establish the -convention. - -**A grouped `Bar` and `Area` stack by default; nothing else does.** That is -`config.stackFor`, and it is why `geom.Desc` carries `Stack` *and* `StackSet` — -`NoStack` is both the zero value and an adjustment somebody may have asked for, -exactly as `Dash`/`DashSet` and `Marker`/`MarkerSet` already are. Without the -flag, a round trip through the spec turns a grouped bar's default into a pinned -"do not stack", and the chart silently changes. - -**Which guide a layer contributes follows from the kind of colour scale it was -handed.** `scale.Qualitative` is a `ColorScale` — it rides that interface the way -`scale.Categorical` rides `Scale` — so `geom.ColorBy` takes either kind, and -`config.colorGuide` returns false for a discrete one while `config.legends` -returns an entry per category. A colourbar over eight categories would be a ramp -through colours nothing is painted with. - -**A layer that implements `geom.Legender` is not asked for `Legend` as well.** -`geom.Legends` prefers the list; `geom.LegendsOr` is the fallback written once, -and a geom that answers `Legends` without it silently loses its single entry. -There is a test — it was the first thing that broke when the interface landed. - -**A rect and a region are both `("rect", "")` in the document, and the encoding -is what tells them apart.** `spec.geomMark` is passed the layer's encoding for -that one reason: a rect with a *field* is data, a rect with a *datum* is an -annotation. Dropping the parameter compiles and turns every heatmap into a -four-literal annotation. - -**A coord is a value, and `Frame` hands one back rather than moving the -receiver.** `coord.Coord.Frame(coord.Framing{...})` returns the coord positioned in that -panel; the chart's own coord is never written to. That is not style — panels are -built on separate goroutines (ADR 0012), and a coord that remembered which panel -it was in would be a data race with no `Snapshotter` to fix it. `render.Panel` -may carry a coord of its own; a facet's panels do not, because the panels of a -facet are one plot over different rows, and a grid's cells do, because they are -separate plots sharing a canvas. - -**`Cartesian` is the identity, and the golden files are the proof.** -`cartesian.Area` writes the same four corners in the same order as -`ir.Path.Rect`, `Edge` is one `LineTo`, `Clip` is the rectangle, and a straight -run still reaches the backend as a `Polyline` rather than as a stroked path. -Every one of those is load-bearing: the argument that the coordinate stage -changed nothing is that the committed golden files still match, and each of them -is a way to break it silently. `geom.strokeRun` is where the polyline/path -choice lives; do not "simplify" it into always building a path. - -**A geom works in mapped space and lets the coord place the point.** What -`scale.Map` returns is a position in an interval, which under Cartesian happens -to be a device coordinate and under Polar is an angle or a radius. So a geom -that computes a midpoint, a corner or a staircase step computes it *before* the -coord, never after: `geom.stepColumns` builds the staircase out of the mapped -columns for exactly this reason, because the corner of a step is a statement -about the data and not about where two device points happened to land. - -**The per-point call has a batch form and the geoms use it.** -`coord.Coord.Points(dst, xs, ys)` is called once per run, not once per row: a -per-row interface method is the shape that cost a million allocations on a -million-row column once already, and `scratch.marks` gathers the surviving rows -into a contiguous pair so there is one call. `BenchmarkPolar1k` against -`BenchmarkPolar100k` in `.github/scripts/allocgate.awk` and -`TestAPolarRenderDoesNotAllocatePerPoint` are the gates, and a polar coord does -not decimate — so those benchmarks really do draw every row. - -**Furniture is filled, not returned, and `Reset` reaches past the length.** -`render` keeps one `coord.Furniture` in a pool for the whole furniture pass and -resets it between panels. `coord.resetShapes` empties every shape the slice has -*ever* held rather than only the ones inside its current length, because -`side.next` hands those back out on the next frame — a shape still holding last -frame's points would draw them again, on a chart with fewer ticks than the last -one. Returning the struct by value instead costs a steady-state frame about -twenty allocations; that was measured, and it is why the signature differs from -the one ADR 0018 sketched. - -**A hit on a filled mark is decided against the outline, not the box.** -`interact.inside` ray-casts the subpath the drawing call carried. Before the -coordinate stage -every filled mark figure drew was a rectangle, so its bounding box *was* its -shape; a pie's wedges have boxes that overlap almost completely, and a hit -decided on the box alone names whichever wedge was indexed last. The row behind -an area hit is then the nearest reported position *inside that shape's box*, -measured from the pointer rather than from the corner the hit reports — a corner -of a tall bar is nearer to the neighbouring bar's row than to its own, and every -slice of a pie shares the corner in the middle. - -**A break-out is a displacement the coord computes and the geom applies.** -`coord.Exploder` answers how far a mark moves when it is broken out of the -middle; `geom` moves the points the `Area` call appended, in place. That split -is the coordinate stage's own: a coord reports geometry and does not draw. Two -consequences are load-bearing. `coord.Cartesian` deliberately does **not** -implement `Exploder`, so `geom.Explode` on a Cartesian chart draws exactly what -it drew — that silence is what keeps every golden file unchanged by an option -every geom now accepts, and making Cartesian answer would move every bar of a -layer the same way, which is a translation rather than a reading. And the -displacement is applied to the mark's path rather than to its extent: a -broken-out slice keeps the angle and the radii the data gave it, and growing the -radius instead would move the ink *and* the reading. See -[ADR 0026](docs/adr/0026-breaking-a-mark-out.md). - -**A run's displacement buffer is tested by length, not against nil.** The -batching runs come back from the scratch pool emptied rather than cleared away, -so a layer that breaks nothing out is handed a non-nil `offs` with nothing in -it. `geom.offsetAt` therefore compares `i >= len(offs)`. Testing for nil there -compiles, passes every test with a fresh pool, and panics on the second frame of -a chart drawn after a broken-out one. - -**A bar's slot is measured once per Train, out of a buffer the layer keeps.** -Two mistakes lived in one line here, and both are worth recognising again. -`smallestGap` sorts, and `barGeom.halfWidth` asked it for the answer *per row* — -which made a bar layer quadratic in its rows: a ring of sixteen thousand slices -spent 2.5 seconds a frame, of which 64 % was that sort. And `smallestGap` -allocated the copy it sorted, so even once per `Train` it was a copy of the -column **per frame** — 800 kB of the 810 kB a hundred-thousand-slice frame -allocated, which is also enough garbage to drive the collections that empty the -scratch pool. It is `barGeom.gap` now, measured in `Train` out of `barGeom.gaps` -— `smallestGap(buf, vs)` hands the buffer back — and `Rect` and `Boxplot` keep -one each for the same reason. The buffer lives on the layer rather than in the -frame's pool because `Train` runs outside a `Build`, where there is no scratch -to take; that is the same argument the group index already makes. - -**A stress layout's row order decides which minimum it reaches, and that is a -bigger number than it sounds.** `stat.Stress` descends a non-convex objective, -and both the arrangement it starts from and the order a sweep visits the nodes -in come from the order the caller's rows interned them. So relabelling the same -edges is not a relabelling of the same picture: the collaboration graph in -`docs/images/network.png` settles at a stress of 3.47 in the order its rows -arrive in and at 2.30 under one relabelling — a third lower, from the same code -at the same budget. Picking the start rows more cleverly does not fix it; that -was measured and only moves which numbering is the unlucky one -([ADR 0077](docs/adr/0077-a-node-link-layout.md)'s second amendment has the -table). And **`geom.Order` is not the way to ask for another one**: it reaches -the grouped marks and the set charts, `geom/relational.go`'s edge reader never -looks at it, and a `NodeLink` given one draws exactly what it drew. A caller -who wants a different node order re-orders the rows of the table. `stat.StressSweeps` is a *budget* and not a convergence point — about -four percent of stress is still on the table at fifty sweeps for a 127-node -tree — and a monotone descent on the stress is not a monotone improvement in -legibility, because nothing here counts an overlap or a crossing. - -**A stat evaluated on a grid pins the grid's ends, and never truncates a -kernel.** Both halves of that are the same bug, and it shipped for exactly one -CI run — green on amd64, red on macOS. `lo + float64(i)*step` is a multiply and -an add, which Go may contract into an FMA "possibly across statements"; arm64 -takes it and amd64 does not, so a grid of sixty-one points over [-3, 3] ended -at 3 on one machine and 3.0000000000000004 on the other. That is one ulp, and -one ulp is invisible — until it lands on the far side of a *decision*. `AppendKDE` -skipped any sample past four bandwidths, so the endpoint's kernel was summed on -one architecture and dropped on the other, and a density that was symmetric on -one was not on the other. - -`stat.gridAt` now hands back the ends exactly rather than computing them, which -is the same "do not compute what is known" fix `scale.place` carries for the -same arithmetic; `AppendKDE` and `AppendLoess` both use it. And the kernel is -summed in full: a cutoff is a discontinuity, so the estimate depended on the -last bit of its argument, and it was not buying an order of growth either — the -loop visits every row either way and the cutoff saved an `exp`. -`TestADensityHasNoCliffInItsTail` and `TestAnEvaluationGridEndsExactlyOnItsBounds` -are what hold both, and the first fails on *every* architecture, which is the -point: a property that only one machine can check is a property nobody checks. - -**A distribution stat runs in `Train`; a device-space one runs in `Build`.** -ADR 0011 puts decimation in `Build` on the rule that what a chart's axis reports -must not depend on how wide the chart is. A histogram, a violin, an ECDF and a -trend are the same rule pointing the other way: their output *is* what the axis -has to describe — counts, a fraction, a fit — so they are computed in `Train` -and the scales are trained on the answer. Two marks are the exception because -what they compute is a length on screen: `geom.Hexbin` bins over the plot -rectangle, and `geom.Beeswarm` places its marks against a marker diameter. See -[ADR 0028](docs/adr/0028-distribution-stats.md). - -**A hexbin has no colourbar, and that is the price of regular hexagons.** Its -counts are not known until the plot rectangle is, and the guide column is -measured before that. Adding one means either binning in data space — cells that -are hexagons in the data and something else on screen — or measuring the guides -twice. Both are worse than shading from a faded colour to the full one. - -**`stat` does no sorting, and the geoms keep the buffers.** `Quantile`, `ECDF` -and `Loess` take ordered columns; `Silverman` takes two spread measures rather -than computing an IQR. Sorting inside a stat means either mutating the caller's -column or allocating a copy of it per frame, and a chart redrawn every frame -already keeps a buffer. Every distribution geom therefore carries its own sort -buffer on the layer, for the reason `barGeom.gaps` does: `Train` runs outside a -`Build`, where there is no scratch to take. - -**`stat.Bin` is the 1-D histogram now.** The 2-D binner that used to be called -`Bin` is `stat.BinGrid`, beside `stat.BinHex`. The three are named after what -they fill, and "bin" without a qualifier means the histogram. - -**A hexagonal lattice is not d3-hexbin's.** `Hex.Cell` follows its structure and -corrects its metric: both work in lattice coordinates where a column step is 1 -and a row step is 1, but on screen those are √3·r and 1.5·r, so comparing -`px² + py²` there mixes units and misplaces points near the interlocking band. -The vertical term carries `(dy/dx)² = 3/4`, and -`TestEveryHexPointLandsInItsNearestCell` checks the defining property directly. -Without it the picture grows seams along every second row. - -**A sized layer draws circles, not markers, and that is the IR's doing.** -`ir.Backend.Markers` carries one `MarkerStyle` per call, so a per-row size would -be a drawing call per row — the cost ADR 0007 refused for colour. `geom.SizeBy` -therefore emits one path per colour with a circle per subpath, which also gives -a pointer the bubble it is inside rather than the nearest centre. Do not -"restore" marker shapes there: it would be a call per row again. - -**A size scale's range is set by `render`, not by the geom.** A geom cannot set -it in `Build` — panels are built on separate goroutines and a shared scale -written from two of them is a data race with no `Snapshotter` to fix it — and -`Geom.Train` has no theme. So `sizeGuides` sets it once per scale on the serial -path, before the guides are measured and before any mark reads it. A range the -caller pinned with `scale.SizeRange` outranks it, exactly as a pinned domain -outranks training. - -**The guide column is one list, and a fourth kind must not make it four.** -`layout.Guide` carries what the solver needs of any guide and `GridResult.Guides` -is the boxes, parallel and in order. It was generalised once rather than -extending it twice — see -[ADR 0027](docs/adr/0027-size-channel-and-the-guide-column.md). Adding a kind is -a `GuideKind` constant, a measuring function and a drawing function; adding a -field to `Grid` is the thing that arrangement exists to refuse. - -**A histogram ignores `GroupBy` on purpose.** Two overlapping histograms hide -each other exactly where the comparison is. `Violin`, `Ridgeline` and `ECDF` are -the three marks that answer that question without overplotting, and each takes -the series column. Do not "fix" it by stacking or dodging bins. - -**A text layer measures while it builds, and that is the one call it may -make.** `geom.Text` asks `ir.Backend.Measure` how wide each label is, because a -label that overruns its box reads as belonging to the neighbouring row and only -the layer knows both. `render.syncMeasurer` serialises those calls onto one font -stack: panels build on separate goroutines, and two of them disagreeing about -how wide a label is would draw different text in the same box. Measure is the -*only* backend call a geom may make during `Build`; anything else belongs in the -drawing calls it emits. - -**A truncated label is cached per row, and that is what keeps the text path off -the allocation gate.** Cutting a label builds a string, which is the one place a -per-row allocation could hide behind work that has to happen anyway. -`textGeom.remember` hands back last frame's string when the cut has not moved, so -a chart redrawn at the same size builds none — `BenchmarkLabelled1k` against -`BenchmarkLabelled10k` and `TestALabelledRenderDoesNotAllocatePerPoint` are what -hold it. The cache lives on the layer rather than in the scratch pool because it -has to survive a `Build`, the same argument `barGeom.gaps` makes. - -**A text layer's box is the box `Rect` would draw, and its anchor is clamped to -what is visible.** The same options handed to both marks label the rectangles -exactly, which is why the slot rule for an unnamed edge is `spanOn` rather than -anything of its own. The clamp is against `coord.Extent` rather than the plot -rectangle — that is the interval the scales map into, so it means something -under a polar coord too — and it is what puts the label in the middle of a bar -that is half scrolled off the edge rather than off-screen with the box's true -centre. The room a label has is measured as the chord between the box's mapped -edges, because under polar the box's width is an angle and what a label needs is -a length. - -**`geom.Align` records having been told, for the reason `Dash` and `Shape` do.** -The start of a run on the baseline is the zero value *and* an alignment somebody -may have asked for, and a text layer centres a label in its box when nobody has. -Without `config.alignSet` and `Desc.AlignSet` a round trip through the spec turns -that default into a pinned left edge and the chart silently changes. - -**A note and a text layer are both `"text"` in the document, and the encoding is -what tells them apart.** `spec.geomMark` asks `hasField`, exactly as it does for -a rect against a region: a text mark with a `text` *field* is data, one placed at -literal values is an annotation. Adding a channel to `spec.Encoding` means adding -it to `hasField` too, or a layer encoded only by that channel reads back as an -annotation. - **Responsive scaling multiplies lengths and must not mutate a shared theme.** `theme.Scaled` copies every dash slice it touches rather than scaling in place — `theme.Light` is a package variable, and scaling its grid dash would scale it for every chart in the process, once per render. There is a reason that is a sentence in the code as well as here. -### A relational layout is in the unit square, and the two coords disagree about Y - -`Treemap`, `Icicle`, `Sankey` and `Arc` all put their span on X in `[0, 1]` and -their height on Y in `[0, 1]`, and both scales are trained on exactly that. Four -things about that will bite. - -**The rim is `y = 1` and the hub is `y = 0`, and the choice is not free.** A -Cartesian panel flips Y — `y.SetRange(area.Max.Y, area.Min.Y)` in -`coord/coord.go` — so `y = 1` is the top of the plot. A polar one does not — -`rad.SetRange(q.r0, q.r1)` in `coord/polar.go` — so `y = 1` is the outer rim. -`rim = y1` is the one convention that makes a sunburst and a chord diagram work -with one pair of scales. It also means the Cartesian readings are unusually -oriented: an icicle grows upward from a root along the bottom. That is the -price, and it is written down in -[ADR 0039](docs/adr/0039-relational-layouts.md) rather than worked around. - -**A recipe wants `coord.Polar()` and never `coord.Pie()`.** `Pie` is -`Polar(Theta(FromY))`, which sweeps the *Y* axis round the circle. These marks' -Y is their depth, so a sunburst under `Pie` draws concentric wedges of the depth -axis — which is nonsense that renders without erroring. - -**The interning is in the geom, not in `stat`.** `stat` takes `[]int` node ids -and never sees a name. Which node is "first" decides everything downstream — -the column a sankey's node stands in, the way round a chord diagram goes, the -palette entry each node takes — and that order has to come from the table rather -than from a map ([ADR 0012](docs/adr/0012-parallel-panels.md)). The map in -`geom/relational.go` is only ever asked *whether* it has seen a name, never what -it holds, and it is `clear`ed rather than replaced so the buckets survive a -frame. A map made per `Train` is the allocation the gate exists to catch. - -**A treemap squarifies in `Build`, against the panel.** It optimises an aspect -ratio *on screen*, so packing the unit square and stretching the result into a -wide panel defeats the algorithm. It is the third instance of -[ADR 0028](docs/adr/0028-distribution-stats.md)'s exception, after the hexagonal -lattice and the beeswarm. It walks the tree breadth-first out of a pooled queue -rather than recursing, and writes only to the scratch — `Build` has to be safe -to run concurrently with itself. - -**`coord.Edge` takes device points.** Handing it the values the scales produced -asks a polar coord to read an angle as an abscissa, and it draws a shape nobody -can recognise — which is exactly the bug the chord diagram's first golden file -caught and no unit test did. `geom.edgeAlong` is the shared spelling, and it -splits a wide span because `Edge` joins two points the *short* way round. - -**A stroked outline hit-tests above the shape it outlines.** `interact` ranks a -vertex above an area, so bordering a treemap cell would make every hover report -a corner. That is why the separation between cells is `geom.Padding` — room — -and not ink, and why these marks stroke only when the caller named both a -`Fill` and a `Color`. `geom.Rect` has the same rule for the same reason. - -**A key is read from the *plot's* layer, never the panel's.** On a faceted -chart those are different objects: a panel holds a `geom.Faceter` `Subset` copy -whose `Source` is the cut, one panel's worth of rows, while a `Hit.Row` has -already been resolved back through `data.Subset` to the table the caller handed -in. Reading the cut with a handed-in row number indexes the wrong table — and -does it silently, with a plausible answer, which is the worst kind. The layer -index is the same in both because a facet preserves layer order. -`TestKeyIsReadFromTheHandedInTable` is the bug written down. - **A transition's row set is the union of its two states, and it is fixed.** An entering row exists at `f == 0` and an exiting one at `f == 1`. That is not tidiness: it keeps the frame's *structure* identical between frames, which is @@ -1341,10 +230,40 @@ label snaps and cannot be faded — a cross-fade needs per-row opacity, the IR change ADR 0007 refuses — but its position still moves, which is usually the shape wanted anyway. -**Watching a render is serial, and animating a watched one is too.** An -`Observer` or a `RowSink` takes the serial path in `render/parallel.go`, so a -chart that is being hovered does not build its panels concurrently. That is a -property of watching, not of animating, but it is where someone will notice it. +## Package notes + +Rules that belong to one part of the tree live next to it. An agent working in +a directory reads that directory's file as well as this one; a person changing +a package should too. A rule that turns out to bind more than one package +belongs here instead. + +- [data/AGENTS.md](data/AGENTS.md) — nulls, `data.Stream` and the ring buffer. +- [stat/AGENTS.md](stat/AGENTS.md) — stress layout, evaluation grids, no + sorting, histograms and the hexagonal lattice. +- [scale/AGENTS.md](scale/AGENTS.md) — domains, axis breaks, endpoint snapping, + pinned domains, tick-label formats, locales and time origins. +- [coord/AGENTS.md](coord/AGENTS.md) — Smith charts, map projections, parallel + coordinates, furniture, Cartesian as the identity, break-outs — and what the + coords deliberately do not do. +- [geom/AGENTS.md](geom/AGENTS.md) — device-space exceptions, batching, + decimation, row reporting, stacks and groups, the scratch pool, distribution + marks, text layers, relational layouts — and what the marks deliberately do + not do. +- [render/AGENTS.md](render/AGENTS.md) — shared scale objects across panels, + tracks, the layout's row arithmetic, second axes, guides, watched and resized + renders. +- [three/AGENTS.md](three/AGENTS.md) — the painter's order, the depth key, + occlusion tests, batching faces, the fitted cube, scene scratch and projected + axis labels. +- [ir/AGENTS.md](ir/AGENTS.md) — damage, comparing styles, and wrappers that + hide optional interfaces. +- [interact/AGENTS.md](interact/AGENTS.md) — watched renders, hit-testing per + subpath and against outlines, and keys read from the plot's layer. +- [spec/AGENTS.md](spec/AGENTS.md) — what a document writes for a mark, + complete descriptions, and marks the encoding tells apart. +- [backend/AGENTS.md](backend/AGENTS.md) — stilus and the deprecated gg, pins, + PDF fonts, embedded payloads in figures, rectangular clips, canvas and the + window. ## Open questions @@ -1380,161 +299,10 @@ and what is next, in the order it is being done. Adding a stub for something on that list is not progress towards it: the seams exist, that is enough. The release order is in [CONTRIBUTING](CONTRIBUTING.md#releasing). -Deliberately not done. There is **no force simulation** — not because one -cannot be made repeatable, which a fixed start and a fixed budget do, but -because it descends no objective, so what stopping it early costs cannot be -said. The chart it was once refused for is drawn: `geom.NodeLink` places nodes -by stress majorization, a descent that never goes uphill, stopped after a -constant number of sweeps — so -[ADR 0012](docs/adr/0012-parallel-panels.md) is satisfied the way every other -layout here satisfies it ([ADR 0077](docs/adr/0077-a-node-link-layout.md)). -Two things there are load-bearing and were wrong once: a sweep writes each -node's position back **before the next node reads it**, because the -simultaneous form is not a descent at all and cycles; and the starting -directions are chosen by eigenvalue **value** rather than magnitude, because -graph distances are often not Euclidean and the biggest by magnitude can be -negative. It refuses a graph of more -than `stat.MaxStressNodes` nodes rather than drawing a hairball. There is **no area-proportional Venn and no Venn of four sets** — the -first is a construction at two sets and an optimiser from three on, where seven -region areas have six free numbers to hit them with; the second is refused -because this mark writes each count *into* its region at one type size in a -fixed arrangement, and a four-set diagram has regions that hold nothing under -those conditions — a decision about this mark's promise rather than a fact about -four sets, and not because no fixed arrangement of four exists. -`geom.Venn` draws the two- and three-set diagram, whose positions are a table -rather than a solution, and `geom.Intersections` is the chart that keeps working -past three ([ADR 0074](docs/adr/0074-sets-are-counted.md) and its -[amendment](docs/adr/0074-sets-are-counted.md#amendment-two-refusals-restated)). -**An UpSet plot is a count and not a layout**, which is why it is three ordinary -marks and a track rather than anything new below `geom` — and why the set-size -bars beside the matrix are a mark reading that same count rather than arithmetic -repeated in the caller's code, though the panel they stand in is still the -caller's ([ADR 0076](docs/adr/0076-the-other-half-of-the-count.md)). A -relational mark -**ignores `geom.SizeBy`**, because a size per node is -meaningless when the value already is the size. A **sankey does not reorder its -nodes to reduce crossings**: that means a sort per sweep, and a sort is where a -layout stops being a pure function of its input and starts depending on how a -tie was broken — `geom.Order` is how a caller asks for a different order, by -sorting its own rows. A **treemap draws its leaves only**, because an internal -node's rectangle is the union of its children's and the nesting shows as -padding. A **parallel-sets diagram counts complete rows only**: a row missing a -category anywhere is counted nowhere, which is the one place in this library -where an absent value costs a row rather than gapping what it is part of — -each of its columns is a partition of the same total, and a count that skipped -only the crossings beside the gap would leave one column adding up to less than -the next, after which no two thicknesses in the diagram mean the same thing. -Its ribbons also **report no row**, because a ribbon is a count over rows and a -count is not a row; and its boxes are **not painted from the colour column's -scale**, because asking a discrete scale for a box's name is what registers -that name, and the legend beside it is naming classes -([ADR 0079](docs/adr/0079-parallel-sets.md)). And a **hit on one of these reports the layout's own coordinates** -rather than anything in the table: for these marks the row is the reading, which -is the first time that has been true and is -[ADR 0015](docs/adr/0015-hit-testing.md)'s revisit clause rather than this -record's. - -Deliberately not done. A **nearest-neighbour partition is none of the above and -sits at the other end of the same question**: its rows have coordinates, so -`geom.Voronoi` reads a pair of axes, and each cell *is* one row and reports it. -It **draws no dots** — a `geom.Scatter` layer over the same table does that — -and **no labels**; it **ignores `GroupBy`**, because there is one partition -over every row of the layer and a series inside it partitions nothing; and it -gives **one of two rows at the same point no cell at all**, because the -bisector between them is undefined and two cells drawn on top of each other are -two marks nobody can point at separately. It **outlines a cell only when both a -`Fill` and a `Color` are named**, which is `geom.Rect`'s rule for `interact`'s -reason, and the treemap's padding is not an alternative here: a cell that had -been inset would no longer be the set of points nearest its row, which is the -only thing the mark asserts. There is **no Lloyd relaxation, no weighted or -power diagram and no Voronoi treemap** — each is the optimiser -[ADR 0039](docs/adr/0039-relational-layouts.md) refuses — and **no Delaunay -triangulation**, because a half-plane intersection does not produce one and an -interpolated surface over scattered samples is a claim about the values -*between* the rows where a cell is a claim about which row is nearest -([ADR 0080](docs/adr/0080-nearest-neighbour-cells.md)). - -Deliberately not done. A **hexbin has no colourbar**, for the -ordering reason above. A **histogram ignores `GroupBy`**. A **sized layer draws -circles** and ignores `geom.Shape`: a marker ladder is a redundant encoding for -telling series apart, and a bubble cloud is one series. A **violin's widths are -normalised against the widest density in the layer**, so the violins are compared -by shape rather than by sample size — `geom.Bandwidth` is what makes two groups -strictly comparable, and without it each group is smoothed by its own spread. -There is **no contour and no QQ plot**: the first needs a marching-squares stat -that nothing else shares, and the second is an ECDF against a theoretical -quantile function, which is a distribution library rather than a chart. And -`geom.Ridgeline` is the **first geom that refuses a scale outright** — it errors -on a continuous Y axis rather than drawing every ridge on top of the last. - -Deliberately not done. A Smith chart's **coord** draws no constant-|Γ| -(VSWR) circles and no constant-Q arcs — each would be a third grid family -against two tick lists, per the trap above. They are drawn as `geom.Locus` -layers instead, which is an annotation and not furniture -([ADR 0050](docs/adr/0050-locus-annotations.md)); the **combined ZY overlay** is -one more family nobody has written. The chart still reads a **normalised -impedance** rather than the reflection coefficient a VNA reports, for the same -tick reason. `coord.SmithZ` is the bridge. It does not implement `coord.Exploder`: -the middle of a Smith chart is a matched load, not an origin of magnitude, so -there is no direction away from it that means anything. And it does not zoom. - -Deliberately not done, under a **geographic projection**, which exists now: -`coord.Geo` ships **no geography** — a coastline, a border and a country's fill -are rows in the caller's table, because a shapefile or a GeoJSON reader is a -package that is allowed dependencies and the core has none — and **no -spherical arithmetic**: a great circle and a rhumb line are two different -claims about one pair of places, so the waypoints are the caller's rows and a -coord that picked one would be answering a question about the world. A path -crossing the **antimeridian** is drawn across the map rather than wrapped round -it, for the same reason: two consecutive rows at 179° and −179° are two degrees -apart or three hundred and fifty-eight, and the pair does not say which. There -is **no mark that fills a closed ring of rows**, which is what a choropleth of -country shapes wants: that is a mark rather than a coord, with four questions -of its own — which row a region reports, how a ring is named, what a hole is, -whether a vertex is a mark — and a record of its own when somebody has -geography to draw. A gridded field is `geom.Rect` and draws today. There is -**no conic projection**, because Albers and Lambert are configured by two -standard parallels and `coord.Desc` carries no such field yet; adding one is -additive. And the map **does not decimate**, because a pixel column is a band -of longitude under two of the four projections and of nothing in particular -under the other two ([ADR 0081](docs/adr/0081-a-map-projection.md)). - -Deliberately not done. A polar coord **does not -decimate**, per that record's fourth property. `layout` is **untouched** — a -polar coord inscribes itself in whatever rectangle the solver gives it, and -gutter rules that understand a radial axis are a later milestone. A radar's -contour closes because `geom.Closed` says so, not because the coord guessed: -whether a series wraps is a fact about the series, and a polar time series -spiralling through three revolutions does not wrap. And a curve is hit-tested as -its control polygon, so a filled shape can be pointed at a little way outside -its ink at a bulge. - -Deliberately not done. There is no `geom.Slice` and -there are no `Inner`/`Outer` channels: `Geom.Train` is handed the two scales and -no coord, so a layer cannot know at training time which of them is the radius — -a channel that only exists under one coord would be the pie geom this project -does not have. The break-out is **per row rather than per group**, because that -is what a channel means everywhere else; a donut has one row per slice, so the -distinction only shows on a stack of several rows per series, whose segments -move independently. Only `Bar` and `Rect` honour it, because they are the marks -that draw an annular sector — a broken-out line has no ring to leave. And a -layer that asks for a break-out under a coord that cannot answer draws what it -drew, silently: an error would make every Cartesian chart's option list -conditional on a coord chosen somewhere else. - -Deliberately not done. A grouped **line, step and scatter do not -stack**: two series drawn over one another are two readings, and adding them -would invent a third nobody measured. Stacking accumulates in group order, so a -stack of mixed signs runs each segment from where the last one ended rather than -splitting into a positive and a negative half. `geom.WidthBy` gives a bar its -width from a column and does **not** reposition the slots — a marimekko is one -layer whose X column already holds each column's centre, and unequal slots that -label themselves are an axis question rather than an adjustment one. A group -index is per layer, so a facet whose panels hold different groups needs an -explicit `scale.Qualitative` for a series to keep its colour across panels. And -a group column that is numeric or temporal is formatted into a label per row, -which is a cost of naming a category with a number rather than of grouping: the -allocation gate uses a text column, which is what a series column is. +The deliberately-not-done lists for the marks and the coords are in +[geom/AGENTS.md](geom/AGENTS.md#deliberately-not-done) and +[coord/AGENTS.md](coord/AGENTS.md#deliberately-not-done); what follows is the +part that is not one package's. Deliberately not done. The GPU tier is opt-in beta and stays that way off — for server-side stills the CPU rasterizer and the vector diff --git a/backend/AGENTS.md b/backend/AGENTS.md new file mode 100644 index 0000000..197e94c --- /dev/null +++ b/backend/AGENTS.md @@ -0,0 +1,154 @@ +# Working in the backends + +Notes for changing the backends, moved here from the root +[AGENTS.md](../AGENTS.md), which holds the rules that apply everywhere — read +that one first. This file covers stilus and the deprecated gg, pins, PDF fonts, +embedded payloads in figures, rectangular clips, canvas and the window. + +## Things that will bite + +**`backend/gg` must not import `gg/gpu`.** Importing it activates the GPU tier, +pulls `wgpu` and `goffi` into the build, and makes CI need graphics hardware. +The CPU rasterizer is the supported path — +[ADR 0006](../docs/adr/0006-gg-coupling-surface.md). + +**gg is pinned exactly.** Upgrading it is a deliberate change with its own +commit, not a side effect of `go get -u`. + +**The raster backend is `backend/stilus`, and `backend/gg` is deprecated.** +New raster work goes into stilus; gg keeps building, unchanged, through +v0.19.0 and is removed in v0.20.0 with its GPU tier, and is never tagged v1 +([ADR 0094](../docs/adr/0094-the-raster-backend-is-stilus.md)). +Four things there bite: + +- *A glyph outline is in ems, not design units.* `stilus.GlyphCache` + quantises the matrix's linear part to 1/64 and reads its scale as the em size + in pixels. Handed design units, a 16 px label in a 2048-unit font has a scale + of 16/2048, which rounds to 1/64 — twice its size — and a 10 px label rounds + to zero and is laid out and never drawn. `TestSmallTextIsDrawnAtItsSize` is + that bug. +- *The font box is OS/2's, advances are unrounded.* Ascent and descent come + from `sTypoAscender`/`sTypoDescender`, hhea only when both are zero — gg's + rule, which keeps every chart on the rectangle gg laid it out on. The vector + emitters read hhea; the 15 % between the two is the drift + `TestMeasurementAgreesWithTheVectorEmitter` allows. Advances are the font's + own widths, not gg's whole pixels, and agree with the SVG backend to + 0.01 px. +- *The module declares Go 1.27.1*, because go-opentype does, and so does + `backend/window`, which draws through it. The committed workspace says + 1.27.1 for that reason; every other module still declares 1.25, and CI's + minimum-toolchain job builds them from a workspace that leaves those two out + with `GOTOOLCHAIN=local`. Without that the toolchain switches itself up and + the 1.25 claim is checked by nothing. +- *A module another one imports is tagged before the importer can require + it.* A require on a version that does not exist breaks the workspace too, + because the module graph is read before the workspace replaces it. So + v0.15.0 went out in three steps — the core with gg and arrow, then + `backend/stilus` once its require named that core, then `backend/window` + once its require named stilus — which is CONTRIBUTING's "When a require + line does have to move", and is what the next new module will need too. + +**PDF is figure's own emitter, not `gg-pdf`.** That library cannot draw +geometry — its path operations reach a stub in `gxpdf` — so the roadmap's plan +of routing PDF through gg's recording API would have produced pages with tick +labels and nothing else. `gg/recording` therefore stays out of `backend/gg`, +and [ADR 0006](../docs/adr/0006-gg-coupling-surface.md)'s import rule is unchanged. +See [ADR 0009](../docs/adr/0009-pdf-backend.md) for the evidence. + +**The PDF backend measures with the font it draws with, whichever font that +is.** `internal/fontmetrics` carries Helvetica's advance table and PDF's +base-14 Helvetica is that font; an *embedded* face measures through +`embeddedFace`, out of its own `hmtx` and `hhea` +([ADR 0038](../docs/adr/0038-embedded-fonts.md)). Every other backend +approximates; this one does not, and the promise has to survive the font +changing — measuring against Helvetica and drawing in Noto Sans sizes every +margin from a typeface the document does not contain. Do not "improve" either +half by measuring with something else. + +**The raster backend's embedded fonts do not cover everything, and a rune they +cannot draw is written as `?`.** The Go fonts cover Latin, Greek, Cyrillic, the +common punctuation and the mathematical operators; they do not cover CJK, and +they do not cover the mathematical angle brackets U+27E8 and U+27E9 a Bloch +sphere's `|0⟩` is written with. So the SVG of a chart and the PNG of the same +chart can differ in their labels — the vector viewer asks the reader's own +fonts and a PNG has nobody to ask. `stilus.WithFallbackFont` (and the +deprecated `gg.WithFallbackFont`) supplies the coverage; +the substitution is `backend/pdf`'s rule for a rune outside WinAnsi, so a +missing glyph is visible rather than silent. `TestAMissingRuneIsAQuestionMarkUnlessAFallbackHasIt` +in backend/stilus and `TestTheEmbeddedFontHasNoMathematicalAngleBrackets` in backend/gg +pin the gap, so a font change that closed it would be noticed rather than +leaving the fallback guarding nothing. See +[ADR 0038](../docs/adr/0038-embedded-fonts.md)'s amendment. + +**An embedded font's glyphs are numbered on first use, and that is what makes +writing a PDF one pass.** A content stream names glyphs by id and a subset's +ids depend on what the whole document drew, so a writer that waited would have +to buffer every text run in the file. Numbering on first use inverts it, and +`sfnt.Font.Subset` honours the order it is given — which is also the only order +that is a pure function of the drawing, per ADR 0012. Two things there are +load-bearing. A composite glyph's component ids are references into the same +font and are **rewritten** to the new numbering; copying one unrewritten draws +a plausible wrong letter, which is the worst kind of wrong. And the subset tag +comes from the face's index rather than from a hash of the glyphs, because a +hash would make the file depend on which labels the chart happened to draw and +the golden tests compare bytes. + +**A density-raster figure embeds a PNG inside its SVG, and that payload is +compared as pixels.** `docs/images/density.svg` carries a base64 deflate stream, +and deflate output is the standard library's business rather than figure's — +the same chart on two Go releases produces two different streams, which is +exactly how this first went red. So the gallery lifts embedded payloads out of +both documents and compares them with the same per-channel tolerance the PNG +half already uses; the vector half, including the `<image>` element's own +position and size, is still compared exactly. See +`backend/stilus/cmd/gallery/embedded.go`, and note this is not a widened tolerance +but the same one applied to pixels rather than to an encoding of them. It is +also why there is no golden SVG for a density chart in `testdata/golden`: +pinning `compress/flate` is not a test of figure. + +**A rectangular clip must reach a raster backend as a rectangle.** gg +rasterises a path clip into a coverage mask and then consults that mask on +every drawing call inside the clip, so a figure costs its drawing calls times +its area; a rectangle it can express as a scissor and the per-pixel cost goes +away. Every clip this library pushes is a rectangle — a panel, a facet cell, +one view of a scene — so `backend/gg` recognises one with +[`ir.Path.AsRect`](../ir/path.go) before falling back to the mask. The shape of +this bug is worth remembering: it is invisible at a hundred drawing calls and +it turned the gallery's ten-minute test budget into a failure at three +thousand, and the stack it fails in belongs to the rasteriser, not to the code +that caused it. + +**The canvas backend builds one path string per drawing call.** Crossing the +WebAssembly boundary is what costs in a browser: a five-hundred-point line is +one `Path2D` and one `stroke`, not five hundred `lineTo` calls. There is a test +that fails if a chart over five hundred rows starts making more than a hundred +context calls, and one that fails if `beginPath` reappears. + +**`backend/canvas` is empty except on js/wasm, and that is what the doc.go is +for.** Every implementation file carries `//go:build js && wasm`; `doc.go` +carries no constraint, so `go build ./...` on a server has a package to build +rather than an error. Its tests run under node in CI, against a recording +context — node has no canvas, and a test that needed one would be a test nobody +could run. + +**`backend/gg` still must not import `gg/gpu`, and the GPU tier is a module +below it.** `backend/gg/gpu` is nested *inside* `backend/gg` so that the raster +backend's own module graph stays gg, `x/image` and the core; importing the tier +is the whole opt-in — [ADR 0022](../docs/adr/0022-gpu-tier.md). Moving the blank +import up one directory would put `wgpu`, `naga` and `goffi` into every program +that renders a PNG, and would cost the module its js/wasm target. + +**gogpu is pinned exactly, and its pin is tied to gg's.** `backend/window` +requires gogpu v0.52.1 because that is the release whose `gputypes` and +`gpucontext` resolve to the versions gg v0.52.5 compiles against. A newer gogpu +pulls a `gputypes` that gg at this pin does not build with, and the failure is a +wall of "too many arguments" inside gg's internals rather than anything naming a +version. Upgrade the two together or not at all. + +**The raster backend draws italic now, and `WithFont` takes three fonts.** +`ir.FontRef.Italic` was ignored by `backend/gg` once, which +was invisible until a typesetter started producing italic runs — at which point +the PNG and the SVG of the same chart would have disagreed in the +documentation. The default set parses `goitalic` alongside `goregular` and +`gobold`; a caller supplying their own passes nil for a style they do not have, +and gets the regular face for it. diff --git a/coord/AGENTS.md b/coord/AGENTS.md new file mode 100644 index 0000000..c34bfd3 --- /dev/null +++ b/coord/AGENTS.md @@ -0,0 +1,218 @@ +# Working in `coord` + +Notes for changing `coord`, moved here from the root [AGENTS.md](../AGENTS.md), +which holds the rules that apply everywhere — read that one first. This file +covers Smith charts, map projections, parallel coordinates, furniture, +Cartesian as the identity, break-outs — and what the coords deliberately do not +do. + +## Things that will bite + +**A Smith coord makes a scale's range its own domain.** `coord.Smith.Frame` +calls `SetRange(lo, hi)` with the scale's *own domain*, so that `Map` is the +identity and the pair reaching `Point` is a normalised impedance rather than a +pixel. Choosing what the interval means is what a coord does — Cartesian chooses +a distance along an edge, Polar chooses radians and pixels — so this is the +mechanism and not an exception to it. Two consequences: the coord assumes an +**affine** scale on each axis (a log Smith axis is a different chart, and the +coord does not guess which), and a zoom moves nothing, because the next `Frame` +re-derives the range from the domain it was just handed. Anything new that +assumes "a scale's range is in pixels" is wrong under this coord and probably +under the next one. See [ADR 0033](../docs/adr/0033-smith-charts.md). + +**A map's default projection is the equal-area one, and that is a decision +rather than a preference.** `coord.Geo("")` and a document naming no projection +are both `coord.DefaultProjection`, which is `Mollweide`: on a map, how much +ground a thing covers reads as how much of it there is, so the three +projections that draw a region larger or smaller than its share are asked for +by name. Do not "simplify" it to the affine one because that is the cheapest +map to compute. + +**A map makes a scale's range its own domain too, and then cuts it.** +`coord.Geo.Frame` calls the same `identityRange` the Smith coord does — a +projection is not separable, so the pair reaching `Point` has to be the degrees +themselves — and then *narrows* its own copy to what the projection reaches: +±85.051129° for Mercator, a turn of longitude about the centre for everything. +`Extent` reports that cut rather than the scale's range, so a mark asked to +span the axis spans the map instead of running off to the infinity a Mercator's +pole is. Three things follow. An axis here wants a **linear** scale, for the +Smith chart's reason. A place the projection has no image for — the far side of +a globe, a latitude past the cut — is **NaN**, so anything new that assumes +`Point` is finite is wrong under this coord first: the graticule is drawn by a +walk that starts a new subpath wherever the image resumes, which is why a +meridian on a globe is one shape holding several subpaths. And the latitude +clamp is *a hair inside* the cut, because the domain travels as a float32 and +the nearest float32 to 85.051129 is outside it — clamp to the cut itself and +the map loses its southern edge. Everything the coord draws for **itself** — a meridian, a parallel, the side of +a cell, the outline of the map — is walked in longitudes measured from the +centre meridian rather than in the caller's, and `geo.relW`/`relE` are that +interval. A walk in the caller's longitudes jumps the width of the picture +wherever theirs crosses the map's cut: a Pacific-centred world map has a domain +of −180° to 180° and a map from −30° to 330°, and its parallels came out drawn +straight back across the world. Data points go through `Point`, which wraps; +anything the coord builds goes through `pointAt`, which does not. Unlike a +Smith chart a map **zooms**, because its picture is derived from the domain +rather than fixed: the fit is +recomputed every `Frame` by walking the image of the domain — a lattice, plus +the rim for a globe — rather than from a per-projection formula, and one scale +factor serves both directions because a map stretched to fill its panel is a +projection nobody chose. See +[ADR 0081](../docs/adr/0081-a-map-projection.md). + +**A coord holds no scales, with one exception, and it is the one with more +than two axes.** `coord.Parallel` carries a scale per dimension because that is +what a parallel-coordinates panel is; every other coord borrows the panel's two +and re-ranges them (`smith.identityRange`, `ternary.pin`). Two things follow +and both are load-bearing. A mark reaches those scales through +`coord.Dimensions` — `geom.Training.Dims` at train time, `f.Coords()` at build +time — rather than through anything new on `Coord`, which never gains a method. +And the panel's own ticks are silenced **by the coord**: left to themselves +they would number an axis index and a fraction of an axis. A theme that turns +them off as well gives back the gutter a panel reserves for tick labels it +never writes, and the dimensions keep their numbers through it because +`Furniture.FamiliesAreTheAxes` says the families *are* the axes — ADR 0070's +label gate, amended. A coord whose family is a third reading beside two +labelled axes leaves that flag alone, which is why a ternary chart is +unchanged. See +[ADR 0078](../docs/adr/0078-a-coord-with-more-than-two-axes.md). + +**A coord may draw one grid line per tick, and may label nothing the scale did +not.** `render.drawAxes` walks `for i, t := range xTicks`, takes the geometry +from `fur.GridX[i]` and the *text* from `t.Label`. That is why a Smith chart's +columns are an impedance rather than the reflection coefficient an instrument +reports: with Γ on the axes the impedance grid would have no tick behind it. +Before reaching for a second grid family, read ADR 0033's "Revisit if" — +widening this is one decision, not several. + +**And check first whether the family is furniture at all.** +[ADR 0050](../docs/adr/0050-locus-annotations.md) is the answer for the four +families 0033 declined, and it widened nothing: a curve given by a formula +rather than by a tick is an *annotation* defined in data space, so the coord +draws it through `Point` like any other mark and `render` never sees it. That is +what `geom.Locus` is, and it is why there are VSWR circles now and still no +second tick list. +A `Shape` may also hold more than one subpath, which is how a ternary chart's +third grid family is drawn without a third tick list +([ADR 0051](../docs/adr/0051-barycentric-coord.md)). What genuinely needed the +wider seam was a labelled *furniture* family with no tick behind it — a +ternary's third ladder, and what everyone assumed was a projection's graticule +— and [ADR 0070](../docs/adr/0070-a-third-labelled-family.md) spent it once for +all of them. [ADR 0073](../docs/adr/0073-labels-on-a-curve.md) had narrowed it to +that much first: a family drawn as a **mark** writes its own levels along its +curves now, with the curve gapped for the text, and `render`'s one tick list +per axis is untouched. The graticule turned out not to be a customer: with +degrees on the axes a meridian *is* a longitude tick's own shape, exactly as a +polar ring is a Y tick's. What a map does raise as a family is the **edge of +the map** — a globe's rim is where the sphere turns away rather than a meridian +anybody can label, and it is drawn nowhere else +([ADR 0081](../docs/adr/0081-a-map-projection.md)). + +**A locus is sampled against the panel, and the Nichols families are refined +rather than walked.** `stat.Extent.Steps` is a tolerance rather than a count for +them: a Nichols chart is the log-polar view of a circle, and the arc that passes +near the origin is a hair of the circle and is the whole plunge to −∞ dB, while +the rest of the same circle is a smooth curve a few dozen samples describe. A +uniform walk resolves one or the other — the −1° N contour sampled uniformly +stops dead at −6 dB, hanging in mid-air well above the bottom of the panel — so +`nichols.refine` bisects until the step is a few pixels and stops at a step that +leaves the window. Do not "simplify" the window rule away: it is also what +*bounds* the refinement, because the arc approaching the origin is self-similar +and a rule that only looked at the step would halve for ever. The other half is +`emit`'s ninety-degree break, which is how the branch point at L = 0 is found +without looking for it. See [ADR 0050](../docs/adr/0050-locus-annotations.md)'s +amendment. + +**A coord is a value, and `Frame` hands one back rather than moving the +receiver.** `coord.Coord.Frame(coord.Framing{...})` returns the coord positioned in that +panel; the chart's own coord is never written to. That is not style — panels are +built on separate goroutines (ADR 0012), and a coord that remembered which panel +it was in would be a data race with no `Snapshotter` to fix it. `render.Panel` +may carry a coord of its own; a facet's panels do not, because the panels of a +facet are one plot over different rows, and a grid's cells do, because they are +separate plots sharing a canvas. + +**`Cartesian` is the identity, and the golden files are the proof.** +`cartesian.Area` writes the same four corners in the same order as +`ir.Path.Rect`, `Edge` is one `LineTo`, `Clip` is the rectangle, and a straight +run still reaches the backend as a `Polyline` rather than as a stroked path. +Every one of those is load-bearing: the argument that the coordinate stage +changed nothing is that the committed golden files still match, and each of them +is a way to break it silently. `geom.strokeRun` is where the polyline/path +choice lives; do not "simplify" it into always building a path. + +**The per-point call has a batch form and the geoms use it.** +`coord.Coord.Points(dst, xs, ys)` is called once per run, not once per row: a +per-row interface method is the shape that cost a million allocations on a +million-row column once already, and `scratch.marks` gathers the surviving rows +into a contiguous pair so there is one call. `BenchmarkPolar1k` against +`BenchmarkPolar100k` in `.github/scripts/allocgate.awk` and +`TestAPolarRenderDoesNotAllocatePerPoint` are the gates, and a polar coord does +not decimate — so those benchmarks really do draw every row. + +**Furniture is filled, not returned, and `Reset` reaches past the length.** +`render` keeps one `coord.Furniture` in a pool for the whole furniture pass and +resets it between panels. `coord.resetShapes` empties every shape the slice has +*ever* held rather than only the ones inside its current length, because +`side.next` hands those back out on the next frame — a shape still holding last +frame's points would draw them again, on a chart with fewer ticks than the last +one. Returning the struct by value instead costs a steady-state frame about +twenty allocations; that was measured, and it is why the signature differs from +the one ADR 0018 sketched. + +**A break-out is a displacement the coord computes and the geom applies.** +`coord.Exploder` answers how far a mark moves when it is broken out of the +middle; `geom` moves the points the `Area` call appended, in place. That split +is the coordinate stage's own: a coord reports geometry and does not draw. Two +consequences are load-bearing. `coord.Cartesian` deliberately does **not** +implement `Exploder`, so `geom.Explode` on a Cartesian chart draws exactly what +it drew — that silence is what keeps every golden file unchanged by an option +every geom now accepts, and making Cartesian answer would move every bar of a +layer the same way, which is a translation rather than a reading. And the +displacement is applied to the mark's path rather than to its extent: a +broken-out slice keeps the angle and the radii the data gave it, and growing the +radius instead would move the ink *and* the reading. See +[ADR 0026](../docs/adr/0026-breaking-a-mark-out.md). + +## Deliberately not done + +Deliberately not done. A Smith chart's **coord** draws no constant-|Γ| +(VSWR) circles and no constant-Q arcs — each would be a third grid family +against two tick lists, per the trap above. They are drawn as `geom.Locus` +layers instead, which is an annotation and not furniture +([ADR 0050](../docs/adr/0050-locus-annotations.md)); the **combined ZY overlay** is +one more family nobody has written. The chart still reads a **normalised +impedance** rather than the reflection coefficient a VNA reports, for the same +tick reason. `coord.SmithZ` is the bridge. It does not implement `coord.Exploder`: +the middle of a Smith chart is a matched load, not an origin of magnitude, so +there is no direction away from it that means anything. And it does not zoom. + +Deliberately not done, under a **geographic projection**, which exists now: +`coord.Geo` ships **no geography** — a coastline, a border and a country's fill +are rows in the caller's table, because a shapefile or a GeoJSON reader is a +package that is allowed dependencies and the core has none — and **no +spherical arithmetic**: a great circle and a rhumb line are two different +claims about one pair of places, so the waypoints are the caller's rows and a +coord that picked one would be answering a question about the world. A path +crossing the **antimeridian** is drawn across the map rather than wrapped round +it, for the same reason: two consecutive rows at 179° and −179° are two degrees +apart or three hundred and fifty-eight, and the pair does not say which. There +is **no mark that fills a closed ring of rows**, which is what a choropleth of +country shapes wants: that is a mark rather than a coord, with four questions +of its own — which row a region reports, how a ring is named, what a hole is, +whether a vertex is a mark — and a record of its own when somebody has +geography to draw. A gridded field is `geom.Rect` and draws today. There is +**no conic projection**, because Albers and Lambert are configured by two +standard parallels and `coord.Desc` carries no such field yet; adding one is +additive. And the map **does not decimate**, because a pixel column is a band +of longitude under two of the four projections and of nothing in particular +under the other two ([ADR 0081](../docs/adr/0081-a-map-projection.md)). + +Deliberately not done. A polar coord **does not +decimate**, per that record's fourth property. `layout` is **untouched** — a +polar coord inscribes itself in whatever rectangle the solver gives it, and +gutter rules that understand a radial axis are a later milestone. A radar's +contour closes because `geom.Closed` says so, not because the coord guessed: +whether a series wraps is a fact about the series, and a polar time series +spiralling through three revolutions does not wrap. And a curve is hit-tested as +its control polygon, so a filled shape can be pointed at a little way outside +its ink at a bulge. diff --git a/data/AGENTS.md b/data/AGENTS.md new file mode 100644 index 0000000..4927935 --- /dev/null +++ b/data/AGENTS.md @@ -0,0 +1,42 @@ +# Working in `data` + +Notes for changing `data`, moved here from the root [AGENTS.md](../AGENTS.md), +which holds the rules that apply everywhere — read that one first. This file +covers nulls, `data.Stream` and the ring buffer. + +## Things that will bite + +**A null is a missing value, and only a numeric column can say so by itself.** +`""` is a string somebody may have measured and the zero time is an instant, so +absence in a text or temporal column is stated beside the values through +`data.Column.Nulls` rather than inside them — [ADR 0034](../docs/adr/0034-null-values.md), +[ADR 0061](../docs/adr/0061-columns-are-one-value.md). +It is read in exactly one place, `geom.column`, which writes NaN whatever the +column is stored as; every policy, traversal and mark downstream is the +machinery that already handled a NaN, and no geom knows about nulls. Three +things there are load-bearing. A column with **no** nulls must answer `ok == +false`, because that answer is what every reader decides between the borrowed +column and a copy on — a mask of all false makes a chart copy a column to +change none of it. `masks` compares the mask against the values before copying, +so an Arrow numeric column, whose nulls are already NaN, is still handed on +untouched. And `series.detach` copies before writing, because `s.x` may be the +caller's own slice: a neighbouring column's null takes a row's *position* away, +and doing that in place edits the table rather than the chart. A genuine `""` +is still a category and there is a test for it — dropping every empty string +passes every null test and is a different feature. + +**`data.Stream` is deliberately not a `data.Source`.** A Source is read column +by column over several calls, and a table appended to between two of them +disagrees with itself. `Snapshot` freezes and swaps; `Source()` reads whatever +the last snapshot froze. Making Stream implement Source would compile, and +would produce a chart with more timestamps than values under load. The two +buffers are reused, so a snapshot is valid only until the next one — that is +the price of the frame costing no allocations, and it is why Snapshot belongs +between frames rather than during one. + +**Unwrap a ring buffer before rewriting it, not while.** `Stream.compact` +resolves every slot number first and rewrites the columns afterwards, and takes +the *old* window as a parameter. `at` answers from the ring's current length, +so rewriting the first column changes the answer for the second — a bug that +only appears on the second column, and only after the ring has wrapped. There +is a test. diff --git a/geom/AGENTS.md b/geom/AGENTS.md new file mode 100644 index 0000000..025b1e5 --- /dev/null +++ b/geom/AGENTS.md @@ -0,0 +1,461 @@ +# Working in `geom` + +Notes for changing `geom`, moved here from the root [AGENTS.md](../AGENTS.md), +which holds the rules that apply everywhere — read that one first. This file +covers device-space exceptions, batching, decimation, row reporting, stacks and +groups, the scratch pool, distribution marks, text layers, relational layouts — +and what the marks deliberately do not do. + +## Things that will bite + +**A dependency arrow is routed in device space, a curve label is placed there, +and a nearest-neighbour partition is cut there; those three are the whole +list.** Everywhere else a geom computes a +midpoint, a corner or a staircase step *before* the coord, because those are +statements about the data — `geom.stepColumns` is the canonical case. +`geom.Depends` puts its two *ends* through `coord.Point` like every other mark +and then joins them with an elbow whose corners are device points and whose stub is in pixels, because there is +nothing in data space between the finish of one task and the start of another: +the route is a reading aid rather than a claim about any value in between. The +direction out of each bar is **measured** from its own two edges rather than +assumed, which is what makes a reversed axis turn both ends together and what +makes one routing function serve a gantt drawn down the page as well as across +it. See [ADR 0068](../docs/adr/0068-gantt-charts.md). + +The second exception is `geom.LabelLevels`, whose argument is sharper. A label +on a contour is turned to the curve's **tangent**, and a tangent in data space +is not the tangent on screen: under `coord.Polar` and `coord.Smith` a curve that +is straight in the scaled pair is bent on the panel, so an angle chosen before +the coord would write the label across its own line on exactly the two coords +the feature exists for. `geom.curveLabeller` therefore reads the device points +the mark is about to stroke and nothing else — which is also why one helper +serves a traced lattice and a formula. See +[ADR 0073](../docs/adr/0073-labels-on-a-curve.md). + +The third is `geom.Voronoi`, and its argument is the treemap's rather than +either of those. A cell's whole content is that its boundary is **halfway +between two dots**, which needs a length — and the two axes of a chart are not +obliged to share one: there is no distance between a millimetre of rain and a +kilometre of easting. Cutting the partition in the scaled pair and stretching +it into the panel is an anisotropic map, which takes perpendicular bisectors to +lines that are not perpendicular bisectors, so every boundary on screen would +be halfway between nothing. The sites go through the scales and `coord.Point` +like every other mark's positions; only the partition between them is device +geometry, which is why `stat.Voronoi` runs in `Build` against `Frame.Area` — +the fourth stat to do so, beside the hexagonal lattice, the beeswarm's offsets +and the treemap's squarify. The honest cost is that the picture depends on the +panel: a colourbar narrows the plot area and the boundaries move. See +[ADR 0080](../docs/adr/0080-nearest-neighbour-cells.md). + +**A progress layer paints twice over, and that is what keeps the batching.** +`geom.ProgressBy` draws every cell at the unfinished alpha and the finished +part of every cell at full strength on top, in two passes — not one composite +shape per cell. `geom.groupByRect` batches by colour, and a shape per cell +would be a drawing call per cell and a per-mark colour in the IR, which is what +[ADR 0007](../docs/adr/0007-per-mark-colour.md) refuses. The fraction grows from +the edge the *row* named first, which is why `geom.edgesOn` exists beside +`spanOn`: the two return one pair of edges in the order the data has them and +in the order the screen has them, and filling from the screen's side would say +a task on a reversed axis had started at the end. + +**A layer may hold data its `Source` does not.** `geom.Depends` reads a second +table, and `geom.Desc.Links`, `spec.Layer.Links` and +`a11y`'s row count all had to learn it. Three things there are load-bearing: +the link table is **never hoisted** in a document, because two dependency +layers over one plan are two sets of constraints; `Subset` cuts the *task* +table and leaves the links alone, so a constraint whose other end is in the +next panel resolves to nothing and is dropped; and the layer reports **no +rows**, because the row it would report belongs to the table `Source` does not +hand out. + +**A geom must not assume a scale accepts every finite value.** A log scale has +no position for zero and returns NaN from `Map`. Geoms ask `scale.Definite` +through `geom.defined` and treat such a row as missing, so a NaN coordinate +never reaches a backend — [ADR 0008](../docs/adr/0008-categorical-axes.md). Adding +a geom means computing `scratch.plottable` once and using it, not re-testing +`finite` per traversal: the traversals have to agree about where the holes are. + +**Per-mark colour batches; it does not widen the IR.** `geom.groupByColor` +emits one drawing call per distinct colour. Adding a per-vertex colour channel +to `ir.Backend` is the thing that record exists to refuse — +[ADR 0007](../docs/adr/0007-per-mark-colour.md). + +**Decimation happens in `Build`, never in `Train`.** A geom trains on every row +and reduces only when it draws, so an axis reports the data rather than the +subset that survived — [ADR 0011](../docs/adr/0011-decimation.md). Reducing in +`Train`, or in the data layer, would make a chart's axis depend on how wide the +chart is, and there is a test that catches it. + +**The reduction runs on device coordinates.** A pixel column is the unit the +whole exercise is about, and on a log axis equal steps in data are not equal +steps on screen. `stat.LTTB` and `stat.MinMax` are generic over `float32` and +`float64` precisely so the device-space path costs no conversion. + +**A geom that holds data implements `geom.Faceter`; one that does not, must +not.** Faceting splits the layers that have rows and replicates the ones that +do not, which is why an `HLine` appears on every panel. Adding `Source`/`Subset` +to an annotation would make a threshold vanish from every panel but the one its +value happens to fall in. + +**A geom reports its rows separately from what it draws, and that is the +whole point.** `geom.Rows` takes the positions a row landed at, not the points +of a drawing call — a smoothed line is a Bézier path whose control points are +not measurements, a staircase draws two points per row, a bar is four corners +around one value. Attributing rows to a call's points would attribute them to +whichever encoding the geom happened to use, and would be wrong for three of +the six geoms that have rows. There is a test per geom. + +**Row reporting is gated on `Frame.Rows != nil` at every step.** `acquire(f)` +records it on the scratch as `wantRows`, and `rowsOf`, `sourceRows` and the +interpolated series' row list all check it. An ordinary render must keep +costing exactly what it did — `BenchmarkFrame1k` did not move when row +identity landed (76 allocations then; the current count is in +[docs/benchmarks.md](../docs/benchmarks.md)), and `BenchmarkWatchedFrame` +against `BenchmarkWatchedFrameRows` is pinned flat. + +**A row is reported in the caller's table, not in the cut figure made.** +Faceting cuts each layer with `data.Rows`, and a row number relative to that +cut is a row number in a table nobody holds. `series.origin` comes from +`data.Origins` and `series.rowAt` resolves through it. A geom that collects its +own element list — a scatter, a bar, both for per-mark colour — must report +through `scratch.sourceRows` rather than handing over the element numbers: the +two lists look identical and mean different things, and a faceted chart is +where that shows. + +**An error bar's orientation is its encoding, and its bounds are derived in +`Train`.** `Y2`/`ErrorBy` runs it vertically and `X2`/`ErrorXBy` horizontally — +the rule `Rect` already follows about its edges, which is why there is no +orientation option to contradict — and naming both is `ErrBothAxes` rather than +a guess that depends on option order ([ADR 0036](../docs/adr/0036-error-bars.md)). +The bounds are computed in `Train` because the axis has to describe them: an +interval whose top runs off the plot is the reading the chart was opened for, +which is the same boundary ADR 0019 draws for a stack's totals. `errorGeom.half` +is measured once per `Train` out of a buffer the layer keeps — `smallestGap` +sorts, and asking it per row is what made a bar layer quadratic once already. +And every segment goes through the coord: a cap drawn as two device points +would be a straight line under a polar coord, where the mark is an arc. + +**Redundant encoding is a default, not an override.** `theme.Redundant` fills in +a dash and a marker ladder, and `config.dashFor`/`markerFor` use them only when +the layer set neither `geom.Dash` nor `geom.Shape`. That is why `config` carries +`markerSet` beside `dashSet` and why `geom.Desc` carries `MarkerSet`: a circle +is both the zero value and a shape somebody may have asked for, and without the +flag a round trip through the spec turns an unset shape into a pinned one. + +**A position adjustment is derived in `Train` and drawn in `Build`, and both +halves are forced.** `render.Draw` trains every layer before it measures +anything, because tick labels need a domain — so a stacked bar's Y scale has to +be trained on the *totals*, or the tallest stack runs off the top of an axis +that describes rows nobody can see. `geom.groups.train` therefore computes the +per-row `(lo, hi)` pair, and `Build` only maps it through the scales. This is +the same boundary ADR 0011 draws for decimation, drawn for the same reason: what +a chart's axis says must not depend on how wide the chart is. See +[ADR 0019](../docs/adr/0019-position-adjustments.md). + +**A stacked layer's holes are decided once, and both traversals read that +answer.** `groups.ok` is computed in `Train` and an unplottable row gets `NaN` +bounds, so the cumulative sum and the drawing traversal agree about where the +holes are. A NaN the sum skipped but the draw did not would shift every segment +above it — there is a test, and it compares a table with a hole against the same +table with the row removed. + +**A grouped layer's buffers live on the layer, not in the frame's pool.** The +group index, the row lists and the derived bounds are refilled by every `Train` +out of memory the geom keeps: `Train` runs as often as `Build` does, and a chart +redrawn over a live table would otherwise allocate its group index per frame. +`TestAStackedLayerDoesNotAllocatePerPoint` is what holds that. Note that the +rows of each group are listed once, in `groups.split`, rather than found by +scanning the table per group — the scan is what makes a chart with many series +quadratic. + +**There is exactly one scratch per `Build`, and a helper takes the caller's +rather than acquiring its own.** Two scratches held at once put two objects with +*disjoint* buffers into one pool; whichever comes back in the other's role next +frame has to grow the other's buffers, which is a per-row allocation on the path +whose whole point is not having one. `geom.eachGroup` therefore takes a +`*scratch` parameter. This shipped broken for exactly one commit and cost a +grouped frame 127 kB and seven allocations it did not need; nothing failed +except the allocation gate, which is what the gate is for. + +**Group order is order of first appearance, and `geom.Order` is the only thing +that changes it.** Map iteration order is not an order; ADR 0012 requires a +parallel render to be byte-identical to a serial one, and `scale.Qualitative`, +`geom.groupByColor` and `boxplot.summarise` all already establish the +convention. + +**A grouped `Bar` and `Area` stack by default; nothing else does.** That is +`config.stackFor`, and it is why `geom.Desc` carries `Stack` *and* `StackSet` — +`NoStack` is both the zero value and an adjustment somebody may have asked for, +exactly as `Dash`/`DashSet` and `Marker`/`MarkerSet` already are. Without the +flag, a round trip through the spec turns a grouped bar's default into a pinned +"do not stack", and the chart silently changes. + +**Which guide a layer contributes follows from the kind of colour scale it was +handed.** `scale.Qualitative` is a `ColorScale` — it rides that interface the way +`scale.Categorical` rides `Scale` — so `geom.ColorBy` takes either kind, and +`config.colorGuide` returns false for a discrete one while `config.legends` +returns an entry per category. A colourbar over eight categories would be a ramp +through colours nothing is painted with. + +**A layer that implements `geom.Legender` is not asked for `Legend` as well.** +`geom.Legends` prefers the list; `geom.LegendsOr` is the fallback written once, +and a geom that answers `Legends` without it silently loses its single entry. +There is a test — it was the first thing that broke when the interface landed. + +**A geom works in mapped space and lets the coord place the point.** What +`scale.Map` returns is a position in an interval, which under Cartesian happens +to be a device coordinate and under Polar is an angle or a radius. So a geom +that computes a midpoint, a corner or a staircase step computes it *before* the +coord, never after: `geom.stepColumns` builds the staircase out of the mapped +columns for exactly this reason, because the corner of a step is a statement +about the data and not about where two device points happened to land. + +**A run's displacement buffer is tested by length, not against nil.** The +batching runs come back from the scratch pool emptied rather than cleared away, +so a layer that breaks nothing out is handed a non-nil `offs` with nothing in +it. `geom.offsetAt` therefore compares `i >= len(offs)`. Testing for nil there +compiles, passes every test with a fresh pool, and panics on the second frame of +a chart drawn after a broken-out one. + +**A bar's slot is measured once per Train, out of a buffer the layer keeps.** +Two mistakes lived in one line here, and both are worth recognising again. +`smallestGap` sorts, and `barGeom.halfWidth` asked it for the answer *per row* — +which made a bar layer quadratic in its rows: a ring of sixteen thousand slices +spent 2.5 seconds a frame, of which 64 % was that sort. And `smallestGap` +allocated the copy it sorted, so even once per `Train` it was a copy of the +column **per frame** — 800 kB of the 810 kB a hundred-thousand-slice frame +allocated, which is also enough garbage to drive the collections that empty the +scratch pool. It is `barGeom.gap` now, measured in `Train` out of `barGeom.gaps` +— `smallestGap(buf, vs)` hands the buffer back — and `Rect` and `Boxplot` keep +one each for the same reason. The buffer lives on the layer rather than in the +frame's pool because `Train` runs outside a `Build`, where there is no scratch +to take; that is the same argument the group index already makes. + +**A distribution stat runs in `Train`; a device-space one runs in `Build`.** +ADR 0011 puts decimation in `Build` on the rule that what a chart's axis reports +must not depend on how wide the chart is. A histogram, a violin, an ECDF and a +trend are the same rule pointing the other way: their output *is* what the axis +has to describe — counts, a fraction, a fit — so they are computed in `Train` +and the scales are trained on the answer. Two marks are the exception because +what they compute is a length on screen: `geom.Hexbin` bins over the plot +rectangle, and `geom.Beeswarm` places its marks against a marker diameter. See +[ADR 0028](../docs/adr/0028-distribution-stats.md). + +**A hexbin has no colourbar, and that is the price of regular hexagons.** Its +counts are not known until the plot rectangle is, and the guide column is +measured before that. Adding one means either binning in data space — cells that +are hexagons in the data and something else on screen — or measuring the guides +twice. Both are worse than shading from a faded colour to the full one. + +**A sized layer draws circles, not markers, and that is the IR's doing.** +`ir.Backend.Markers` carries one `MarkerStyle` per call, so a per-row size would +be a drawing call per row — the cost ADR 0007 refused for colour. `geom.SizeBy` +therefore emits one path per colour with a circle per subpath, which also gives +a pointer the bubble it is inside rather than the nearest centre. Do not +"restore" marker shapes there: it would be a call per row again. + +**A histogram ignores `GroupBy` on purpose.** Two overlapping histograms hide +each other exactly where the comparison is. `Violin`, `Ridgeline` and `ECDF` are +the three marks that answer that question without overplotting, and each takes +the series column. Do not "fix" it by stacking or dodging bins. + +**A text layer measures while it builds, and that is the one call it may +make.** `geom.Text` asks `ir.Backend.Measure` how wide each label is, because a +label that overruns its box reads as belonging to the neighbouring row and only +the layer knows both. `render.syncMeasurer` serialises those calls onto one font +stack: panels build on separate goroutines, and two of them disagreeing about +how wide a label is would draw different text in the same box. Measure is the +*only* backend call a geom may make during `Build`; anything else belongs in the +drawing calls it emits. + +**A truncated label is cached per row, and that is what keeps the text path off +the allocation gate.** Cutting a label builds a string, which is the one place a +per-row allocation could hide behind work that has to happen anyway. +`textGeom.remember` hands back last frame's string when the cut has not moved, so +a chart redrawn at the same size builds none — `BenchmarkLabelled1k` against +`BenchmarkLabelled10k` and `TestALabelledRenderDoesNotAllocatePerPoint` are what +hold it. The cache lives on the layer rather than in the scratch pool because it +has to survive a `Build`, the same argument `barGeom.gaps` makes. + +**A text layer's box is the box `Rect` would draw, and its anchor is clamped to +what is visible.** The same options handed to both marks label the rectangles +exactly, which is why the slot rule for an unnamed edge is `spanOn` rather than +anything of its own. The clamp is against `coord.Extent` rather than the plot +rectangle — that is the interval the scales map into, so it means something +under a polar coord too — and it is what puts the label in the middle of a bar +that is half scrolled off the edge rather than off-screen with the box's true +centre. The room a label has is measured as the chord between the box's mapped +edges, because under polar the box's width is an angle and what a label needs is +a length. + +**`geom.Align` records having been told, for the reason `Dash` and `Shape` do.** +The start of a run on the baseline is the zero value *and* an alignment somebody +may have asked for, and a text layer centres a label in its box when nobody has. +Without `config.alignSet` and `Desc.AlignSet` a round trip through the spec turns +that default into a pinned left edge and the chart silently changes. + +### A relational layout is in the unit square, and the two coords disagree about Y + +`Treemap`, `Icicle`, `Sankey` and `Arc` all put their span on X in `[0, 1]` and +their height on Y in `[0, 1]`, and both scales are trained on exactly that. Four +things about that will bite. + +**The rim is `y = 1` and the hub is `y = 0`, and the choice is not free.** A +Cartesian panel flips Y — `y.SetRange(area.Max.Y, area.Min.Y)` in +`coord/coord.go` — so `y = 1` is the top of the plot. A polar one does not — +`rad.SetRange(q.r0, q.r1)` in `coord/polar.go` — so `y = 1` is the outer rim. +`rim = y1` is the one convention that makes a sunburst and a chord diagram work +with one pair of scales. It also means the Cartesian readings are unusually +oriented: an icicle grows upward from a root along the bottom. That is the +price, and it is written down in +[ADR 0039](../docs/adr/0039-relational-layouts.md) rather than worked around. + +**A recipe wants `coord.Polar()` and never `coord.Pie()`.** `Pie` is +`Polar(Theta(FromY))`, which sweeps the *Y* axis round the circle. These marks' +Y is their depth, so a sunburst under `Pie` draws concentric wedges of the depth +axis — which is nonsense that renders without erroring. + +**The interning is in the geom, not in `stat`.** `stat` takes `[]int` node ids +and never sees a name. Which node is "first" decides everything downstream — +the column a sankey's node stands in, the way round a chord diagram goes, the +palette entry each node takes — and that order has to come from the table rather +than from a map ([ADR 0012](../docs/adr/0012-parallel-panels.md)). The map in +`geom/relational.go` is only ever asked *whether* it has seen a name, never what +it holds, and it is `clear`ed rather than replaced so the buckets survive a +frame. A map made per `Train` is the allocation the gate exists to catch. + +**A treemap squarifies in `Build`, against the panel.** It optimises an aspect +ratio *on screen*, so packing the unit square and stretching the result into a +wide panel defeats the algorithm. It is the third instance of +[ADR 0028](../docs/adr/0028-distribution-stats.md)'s exception, after the hexagonal +lattice and the beeswarm. It walks the tree breadth-first out of a pooled queue +rather than recursing, and writes only to the scratch — `Build` has to be safe +to run concurrently with itself. + +**`coord.Edge` takes device points.** Handing it the values the scales produced +asks a polar coord to read an angle as an abscissa, and it draws a shape nobody +can recognise — which is exactly the bug the chord diagram's first golden file +caught and no unit test did. `geom.edgeAlong` is the shared spelling, and it +splits a wide span because `Edge` joins two points the *short* way round. + +**A stroked outline hit-tests above the shape it outlines.** `interact` ranks a +vertex above an area, so bordering a treemap cell would make every hover report +a corner. That is why the separation between cells is `geom.Padding` — room — +and not ink, and why these marks stroke only when the caller named both a +`Fill` and a `Color`. `geom.Rect` has the same rule for the same reason. + +## Deliberately not done + +Deliberately not done. There is **no force simulation** — not because one +cannot be made repeatable, which a fixed start and a fixed budget do, but +because it descends no objective, so what stopping it early costs cannot be +said. The chart it was once refused for is drawn: `geom.NodeLink` places nodes +by stress majorization, a descent that never goes uphill, stopped after a +constant number of sweeps — so +[ADR 0012](../docs/adr/0012-parallel-panels.md) is satisfied the way every other +layout here satisfies it ([ADR 0077](../docs/adr/0077-a-node-link-layout.md)). +Two things there are load-bearing and were wrong once: a sweep writes each +node's position back **before the next node reads it**, because the +simultaneous form is not a descent at all and cycles; and the starting +directions are chosen by eigenvalue **value** rather than magnitude, because +graph distances are often not Euclidean and the biggest by magnitude can be +negative. It refuses a graph of more +than `stat.MaxStressNodes` nodes rather than drawing a hairball. There is **no area-proportional Venn and no Venn of four sets** — the +first is a construction at two sets and an optimiser from three on, where seven +region areas have six free numbers to hit them with; the second is refused +because this mark writes each count *into* its region at one type size in a +fixed arrangement, and a four-set diagram has regions that hold nothing under +those conditions — a decision about this mark's promise rather than a fact about +four sets, and not because no fixed arrangement of four exists. +`geom.Venn` draws the two- and three-set diagram, whose positions are a table +rather than a solution, and `geom.Intersections` is the chart that keeps working +past three ([ADR 0074](../docs/adr/0074-sets-are-counted.md) and its +[amendment](../docs/adr/0074-sets-are-counted.md#amendment-two-refusals-restated)). +**An UpSet plot is a count and not a layout**, which is why it is three ordinary +marks and a track rather than anything new below `geom` — and why the set-size +bars beside the matrix are a mark reading that same count rather than arithmetic +repeated in the caller's code, though the panel they stand in is still the +caller's ([ADR 0076](../docs/adr/0076-the-other-half-of-the-count.md)). A +relational mark +**ignores `geom.SizeBy`**, because a size per node is +meaningless when the value already is the size. A **sankey does not reorder its +nodes to reduce crossings**: that means a sort per sweep, and a sort is where a +layout stops being a pure function of its input and starts depending on how a +tie was broken — `geom.Order` is how a caller asks for a different order, by +sorting its own rows. A **treemap draws its leaves only**, because an internal +node's rectangle is the union of its children's and the nesting shows as +padding. A **parallel-sets diagram counts complete rows only**: a row missing a +category anywhere is counted nowhere, which is the one place in this library +where an absent value costs a row rather than gapping what it is part of — +each of its columns is a partition of the same total, and a count that skipped +only the crossings beside the gap would leave one column adding up to less than +the next, after which no two thicknesses in the diagram mean the same thing. +Its ribbons also **report no row**, because a ribbon is a count over rows and a +count is not a row; and its boxes are **not painted from the colour column's +scale**, because asking a discrete scale for a box's name is what registers +that name, and the legend beside it is naming classes +([ADR 0079](../docs/adr/0079-parallel-sets.md)). And a **hit on one of these reports the layout's own coordinates** +rather than anything in the table: for these marks the row is the reading, which +is the first time that has been true and is +[ADR 0015](../docs/adr/0015-hit-testing.md)'s revisit clause rather than this +record's. + +Deliberately not done. A **nearest-neighbour partition is none of the above and +sits at the other end of the same question**: its rows have coordinates, so +`geom.Voronoi` reads a pair of axes, and each cell *is* one row and reports it. +It **draws no dots** — a `geom.Scatter` layer over the same table does that — +and **no labels**; it **ignores `GroupBy`**, because there is one partition +over every row of the layer and a series inside it partitions nothing; and it +gives **one of two rows at the same point no cell at all**, because the +bisector between them is undefined and two cells drawn on top of each other are +two marks nobody can point at separately. It **outlines a cell only when both a +`Fill` and a `Color` are named**, which is `geom.Rect`'s rule for `interact`'s +reason, and the treemap's padding is not an alternative here: a cell that had +been inset would no longer be the set of points nearest its row, which is the +only thing the mark asserts. There is **no Lloyd relaxation, no weighted or +power diagram and no Voronoi treemap** — each is the optimiser +[ADR 0039](../docs/adr/0039-relational-layouts.md) refuses — and **no Delaunay +triangulation**, because a half-plane intersection does not produce one and an +interpolated surface over scattered samples is a claim about the values +*between* the rows where a cell is a claim about which row is nearest +([ADR 0080](../docs/adr/0080-nearest-neighbour-cells.md)). + +Deliberately not done. A **hexbin has no colourbar**, for the +ordering reason above. A **histogram ignores `GroupBy`**. A **sized layer draws +circles** and ignores `geom.Shape`: a marker ladder is a redundant encoding for +telling series apart, and a bubble cloud is one series. A **violin's widths are +normalised against the widest density in the layer**, so the violins are compared +by shape rather than by sample size — `geom.Bandwidth` is what makes two groups +strictly comparable, and without it each group is smoothed by its own spread. +There is **no contour and no QQ plot**: the first needs a marching-squares stat +that nothing else shares, and the second is an ECDF against a theoretical +quantile function, which is a distribution library rather than a chart. And +`geom.Ridgeline` is the **first geom that refuses a scale outright** — it errors +on a continuous Y axis rather than drawing every ridge on top of the last. + +Deliberately not done. There is no `geom.Slice` and +there are no `Inner`/`Outer` channels: `Geom.Train` is handed the two scales and +no coord, so a layer cannot know at training time which of them is the radius — +a channel that only exists under one coord would be the pie geom this project +does not have. The break-out is **per row rather than per group**, because that +is what a channel means everywhere else; a donut has one row per slice, so the +distinction only shows on a stack of several rows per series, whose segments +move independently. Only `Bar` and `Rect` honour it, because they are the marks +that draw an annular sector — a broken-out line has no ring to leave. And a +layer that asks for a break-out under a coord that cannot answer draws what it +drew, silently: an error would make every Cartesian chart's option list +conditional on a coord chosen somewhere else. + +Deliberately not done. A grouped **line, step and scatter do not +stack**: two series drawn over one another are two readings, and adding them +would invent a third nobody measured. Stacking accumulates in group order, so a +stack of mixed signs runs each segment from where the last one ended rather than +splitting into a positive and a negative half. `geom.WidthBy` gives a bar its +width from a column and does **not** reposition the slots — a marimekko is one +layer whose X column already holds each column's centre, and unequal slots that +label themselves are an axis question rather than an adjustment one. A group +index is per layer, so a facet whose panels hold different groups needs an +explicit `scale.Qualitative` for a series to keep its colour across panels. And +a group column that is numeric or temporal is formatted into a label per row, +which is a cost of naming a category with a number rather than of grouping: the +allocation gate uses a text column, which is what a series column is. diff --git a/interact/AGENTS.md b/interact/AGENTS.md new file mode 100644 index 0000000..ffbd95d --- /dev/null +++ b/interact/AGENTS.md @@ -0,0 +1,41 @@ +# Working in `interact` + +Notes for changing `interact`, moved here from the root +[AGENTS.md](../AGENTS.md), which holds the rules that apply everywhere — read +that one first. This file covers watched renders, hit-testing per subpath and +against outlines, and keys read from the plot's layer. + +## Things that will bite + +**A watched render must draw exactly what an unwatched one draws.** +`interact.Index.Watch` wraps a backend and indexes what it sees; every method +forwards first and indexes second. There is a test comparing the two traces +call for call, and `TestAWatchedRenderDrawsWhatAnUnwatchedOneDoes` compares the +SVG bytes. A probe that changed anything would silently halve the coverage of +every golden file, the same way a scheduling-dependent panel order would. + +**Hit-testing indexes one mark per subpath, not one per call.** A layer draws +all its bars in a single path, because `geom.groupByColor` batches by colour. A +mark per call would make the row of bars one shape, so pointing at the fourth +bar would report whichever corner of whichever bar happened to be nearest. +There is a test. + +**A hit on a filled mark is decided against the outline, not the box.** +`interact.inside` ray-casts the subpath the drawing call carried. Before the +coordinate stage +every filled mark figure drew was a rectangle, so its bounding box *was* its +shape; a pie's wedges have boxes that overlap almost completely, and a hit +decided on the box alone names whichever wedge was indexed last. The row behind +an area hit is then the nearest reported position *inside that shape's box*, +measured from the pointer rather than from the corner the hit reports — a corner +of a tall bar is nearer to the neighbouring bar's row than to its own, and every +slice of a pie shares the corner in the middle. + +**A key is read from the *plot's* layer, never the panel's.** On a faceted +chart those are different objects: a panel holds a `geom.Faceter` `Subset` copy +whose `Source` is the cut, one panel's worth of rows, while a `Hit.Row` has +already been resolved back through `data.Subset` to the table the caller handed +in. Reading the cut with a handed-in row number indexes the wrong table — and +does it silently, with a plausible answer, which is the worst kind. The layer +index is the same in both because a facet preserves layer order. +`TestKeyIsReadFromTheHandedInTable` is the bug written down. diff --git a/ir/AGENTS.md b/ir/AGENTS.md new file mode 100644 index 0000000..015b3ea --- /dev/null +++ b/ir/AGENTS.md @@ -0,0 +1,30 @@ +# Working in `ir` + +Notes for changing `ir`, moved here from the root [AGENTS.md](../AGENTS.md), +which holds the rules that apply everywhere — read that one first. This file +covers damage, comparing styles, and wrappers that hide optional interfaces. + +## Things that will bite + +**Damage is per drawing call, and reports `ok == false` rather than guessing.** +`ir.Damage` compares two recordings call for call; a different call count, a +different kind, or a moved transform means the chart's *structure* changed and +the answer is a full repaint. Do not make it clever about realigning: a list of +rectangles that describes half a frame is worse than repainting the frame. + +**`ir.Partial.Damage(nil)` means the whole frame, and an empty list never +arrives.** A frame identical to the last one is not painted at all rather than +painted with no damage, which is why the nil case is unambiguous. + +**A Stroke cannot be compared with `==`.** It holds a dash slice. `ir` carries +`Stroke.same`, `Fill.same` and `MarkerStyle.same` for this; reach for those +rather than adding a comparison that compiles today because the field you would +have missed happens not to be there yet. + +**A backend wrapper hides the optional interfaces of what it wraps.** `Damage`, +`Resize` and `Describe` are all reached by type assertion, so a wrapper that +does not declare them silently drops them. `ir.Recorder` and `interact`'s probe +both forward `Describe`; `render.Draw` keeps the *unwrapped* backend for the +semantics question, because it wraps the backend to install a typesetter. A +`<title>` that quietly disappears from interactive charts only is what this +costs when it is forgotten, and there is a test. diff --git a/render/AGENTS.md b/render/AGENTS.md new file mode 100644 index 0000000..828cef2 --- /dev/null +++ b/render/AGENTS.md @@ -0,0 +1,103 @@ +# Working in `render` and `internal/layout` + +Notes for changing `render` and `internal/layout`, moved here from the root +[AGENTS.md](../AGENTS.md), which holds the rules that apply everywhere — read +that one first. This file covers shared scale objects across panels, tracks, +the layout's row arithmetic, second axes, guides, watched and resized renders. + +## Things that will bite + +**Panels sharing an axis share the scale object.** So the device range is set +per panel, twice: once before the furniture pass and once before the data pass. +Dropping the second call leaves every panel but the last drawing its data where +the last panel's axis is. There is a test. + +**A track shares the panel's scale object, and that is the whole feature.** +`Plot.tracked` gives every track panel the chart's own scale for the axis it +runs along — `c.X` for a bottom or top band, `c.Y` for a left or right one. A zoom reaches a scale +through `scale.Zoomer.SetDomain`, so one object means the panel and its bands +move together by construction rather than by two handlers agreeing. Cloning it +there — which is what `freeScale` does for a *free facet axis*, and looks like +the tidier thing to do — compiles, draws a chart that looks right, and breaks +every acceptance criterion the feature has. The same trap is why +`scale.Cloner` and `scale.Snapshotter` are opposites; see +[ADR 0031](../docs/adr/0031-tracks.md). A track's own Y is unzoomable for free, +because `zoomAxis` no-ops on a scale that is not a `Zoomer` and `scale.Ordinal` +deliberately is not one. There is a test for each half. + +**A fixed row's arithmetic is written to be bit-identical when nothing is +fixed.** `layout.rowHeights` divides once and multiplies once rather than +summing, because a float32 sum of n equal terms is not always their product, +and the guide column is measured against that total. Rewriting it as the +obvious loop moves every golden file in the repository by an ulp — which the +structural comparison will *not* catch, because it tolerates exactly that. + +**A watched render is serial, on purpose.** `render.Chart.Observer` forces the +serial path in `concurrent`. The observer is told which layer is drawing so a +caller can attribute the calls that follow; two panels drawing at once have no +order to be told in. Do not "optimise" this by giving each panel its own +observer — the index would then depend on scheduling, and so would every +tooltip. + +**A second axis is a scale on the chart and a binding on the layer, and five +places had to learn it.** `render.Panel.axesOf` asks the layer through +`geom.Describe` — not a method on `Geom`, which never gains one — so the chart +and the document agree by construction +([ADR 0037](../docs/adr/0037-secondary-axis.md)). The two directions are +independent: a layer may name `OnX2` and `OnY2` together. Four consequences are +load-bearing. `Panel.setRange` frames the coord against the **secondary** pair as +well as the primary one, or the layers on a second axis map through a scale +with no device range. `coord.Opposite` is an optional interface and `Polar` deliberately does +not implement it — a ring has no far side — so a chart that names a second axis +under a polar coord simply does not draw one. The second axis draws **no grid +lines**, and there is a test comparing the count against a one-axis chart: +two ladders of rules at different values are a moiré, and which scale a line +belongs to is unanswerable by looking. And the scales on `render.LayerInfo` are what make a +hit report the right number — an index that inverted every mark through the +panel's own scales would name 4200 on a chart whose right axis reads 12 %, +which is wrong by a *unit* on the feature whose whole purpose is that the units +differ. The layout's right and top gutters are zero for a column or row with no +second axis, which is what leaves every golden file unchanged; the guide column +is anchored past the right one, because the width was already reserved and an +anchor on the panel edge puts a legend on top of the labels. A facet's strip +sits **outside** the top gutter: a strip between a panel and its own tick +labels reads as though it named the axis. + +Steering has to move both. `Live.Wheel`, `ZoomTo`, `PanBy` and `Autoscale` all +reach `Panel.Y2` as well as `Panel.Y`, or the two series slide apart under the +reader's hand — a chart with two axes is one chart, so a zoom is one zoom. +`interact.Panel` learns about the second axis from the scales on +`render.LayerInfo` rather than from `Observer.Panel`, which carries the panel's +own two. + +**A typeset label is measured by laying it out.** `render`'s `mathBackend` +answers `Measure` from the typesetter and `Text` from the same layout, so the +margin a title is given is the width the title turns out to have. Measuring the +markup and drawing the notation would leave a fraction hanging out of the +canvas, and nothing would fail. + +**A resized frame is not comparable with the last one.** `Live.Resize` clears +`drawn`, because every coordinate moved and there is no damage to compute. It +also keeps whatever the scales were zoomed to, on purpose: a reader who dragged +a view into place has not asked to leave it. + +**A size scale's range is set by `render`, not by the geom.** A geom cannot set +it in `Build` — panels are built on separate goroutines and a shared scale +written from two of them is a data race with no `Snapshotter` to fix it — and +`Geom.Train` has no theme. So `sizeGuides` sets it once per scale on the serial +path, before the guides are measured and before any mark reads it. A range the +caller pinned with `scale.SizeRange` outranks it, exactly as a pinned domain +outranks training. + +**The guide column is one list, and a fourth kind must not make it four.** +`layout.Guide` carries what the solver needs of any guide and `GridResult.Guides` +is the boxes, parallel and in order. It was generalised once rather than +extending it twice — see +[ADR 0027](../docs/adr/0027-size-channel-and-the-guide-column.md). Adding a kind is +a `GuideKind` constant, a measuring function and a drawing function; adding a +field to `Grid` is the thing that arrangement exists to refuse. + +**Watching a render is serial, and animating a watched one is too.** An +`Observer` or a `RowSink` takes the serial path in `render/parallel.go`, so a +chart that is being hovered does not build its panels concurrently. That is a +property of watching, not of animating, but it is where someone will notice it. diff --git a/scale/AGENTS.md b/scale/AGENTS.md new file mode 100644 index 0000000..1a76e61 --- /dev/null +++ b/scale/AGENTS.md @@ -0,0 +1,79 @@ +# Working in `scale` + +Notes for changing `scale`, moved here from the root [AGENTS.md](../AGENTS.md), +which holds the rules that apply everywhere — read that one first. This file +covers domains, axis breaks, endpoint snapping, pinned domains, tick-label +formats, locales and time origins. + +## Things that will bite + +**A domain is ordered, and an axis's direction is `scale.Reverse`.** `Domain`, +`LogDomain`, `SymLogDomain` and `Zoomer.SetDomain` all order the bounds they are +given. Writing them backwards to flip an axis half-works, which is why it is not +allowed to: `Map` and `Invert` mirror, and then `Zero` and `Nice` reorder the +pair, the containment test in `Ticks` drops every tick there is, and the first +pan turns the axis back round. What reverses is the device range — see +[ADR 0075](../docs/adr/0075-an-axis-has-a-direction.md). Anything that walks ticks +across a panel walks them in **screen** order for the same reason: a tick +sequence is ascending by value, and on a reversed axis that is right to left. + +**An axis break is off until the renderer switches it on, and a value inside +one is not missing.** `scale.Break`, `scale.Fold` and their time forms keep +`Map` continuous: a value in a cut maps linearly across the gap and the panel's +clip hides it, which is what keeps `Invert` exact and a bar across the break one +bar. Do not "fix" that by answering NaN or `Defined == false` — a point there +would vanish silently and the tall bar the break exists for would be cut. The +gap is a device length the scale cannot know, so `render.breakGaps` sets it +through `scale.Breaker` once per render, and sets it **off** under any coord +that is not `coord.Breakable` and on every second axis: a break drawn without +its mark is an axis whose ruler is wrong where nobody says so. The cuts are +resolved on the stack of every call rather than cached, so a pan needs nothing +invalidated and a snapshot shares nothing it writes; per piece, `place` and the +endpoint snap apply exactly as they do to a whole axis. With no active cut, +`framedCartesian.Clip` is the panel rectangle and its furniture is two-point +polylines — which is why no golden file moved, and why that branch must stay. +See [ADR 0083](../docs/adr/0083-an-axis-break-is-marked-or-not-drawn.md). + +**Scales snap their endpoints.** `Map` returns the exact range bounds for the +exact domain bounds. Without that, a tick on the plot edge lands a float32 ulp +outside it and gets culled. There is a test; do not "simplify" it away. Every +scale does this. + +**A pinned scale domain skips nicing, and that is not an oversight.** +`scale.Zoomer.SetDomain` sets `pinned` as well as `fixed`, and `effective()` +returns the pinned domain before nicing or zero-forcing get a chance. An axis +that snapped to round numbers after every wheel notch would not follow the +pointer, and on a log axis nicing rounds the view out to whole decades. `fixed` +alone stops *training*; `pinned` also stops *framing*. + +**A tick label has two spellings and the Go one wins, but both are written +down.** `scale.Format` takes a function and `scale.NumberFormat` takes a spec; +`Desc` carries `Formatted` *and* `Format`, because a Desc that dropped the spec +when a function was present would silently change the chart the day somebody +deleted the Go code — [ADR 0035](../docs/adr/0035-label-format-and-locale.md). Two +things there are easy to break. A spec that names no precision must keep the +axis's own, which is derived from the tick *step* and is what keeps a column of +labels aligned: that is why `autoFor` returns a description rather than a +formatter, and why the two meet in `numberFormat.label`. And an unlocalised +scale must take the *old* path exactly — `punctuate` with English's separators +is the identity on `strconv`'s output, and a time scale with no locale calls +`time.Format` itself rather than the layout-splitting path — because that is +what leaves every golden file in the repository unchanged. There is a test +asserting that naming English changes nothing; do not "simplify" the default +branch away. + +**A locale reaches a chart's axes by a walk, and the walk is the feature.** +`figure.Locale` localises the scales in the *chart description*, after it is +built, which is what reaches a track's own scale and a free facet axis's clone +— neither of which the caller holds. Setting it in `Plot.X` instead compiles +and misses both. It happens before the parallel path, and a locale is read +from then on and never written, so there is nothing for `Snapshotter` to fix. + +**A time domain is nanoseconds since the scale's origin, not since 1970.** +`scale.Origin` moves it, `scale.ValueOf`/`InstantOf` convert across it, and +`geom.column` uses them — so a time column is read in the axis's own space. +The default origin is the Unix epoch, which is exactly `scale.Nanos`, so nothing +changes for a scale that never asked. What does change is that `scale.Nanos` is +the wrong conversion to reach for near a rebased axis: the domain values, the +`Invert` results and the `Desc` bounds are all measured from the origin, and the +JSON spec writes it out for that reason. diff --git a/spec/AGENTS.md b/spec/AGENTS.md new file mode 100644 index 0000000..1257ec5 --- /dev/null +++ b/spec/AGENTS.md @@ -0,0 +1,33 @@ +# Working in `spec` + +Notes for changing `spec`, moved here from the root [AGENTS.md](../AGENTS.md), +which holds the rules that apply everywhere — read that one first. This file +covers what a document writes for a mark, complete descriptions, and marks the +encoding tells apart. + +## Things that will bite + +**The JSON spec writes what a mark uses, not what it was given.** A geom +accepts every option and ignores the ones it has no use for, which is what +keeps the option set one namespace; a *document* listing a line's whisker +extent would read as though that meant something. `spec.writeMarkProps` decides +per mark. Adding an option means adding it there too, and the round-trip test +in `spec/` is what catches forgetting. + +**`geom.Desc` and `scale.Desc` are complete, not partial.** Every field with a +non-zero default — `BarWidth`, `Whisker`, `Outliers`, `Extend`, `Opacity` — +carries the value the layer is actually using, so nothing downstream has to +know what the defaults are. `Opacity` is `-1` when unset, matching `config`. + +**A rect and a region are both `("rect", "")` in the document, and the encoding +is what tells them apart.** `spec.geomMark` is passed the layer's encoding for +that one reason: a rect with a *field* is data, a rect with a *datum* is an +annotation. Dropping the parameter compiles and turns every heatmap into a +four-literal annotation. + +**A note and a text layer are both `"text"` in the document, and the encoding is +what tells them apart.** `spec.geomMark` asks `hasField`, exactly as it does for +a rect against a region: a text mark with a `text` *field* is data, one placed at +literal values is an annotation. Adding a channel to `spec.Encoding` means adding +it to `hasField` too, or a layer encoded only by that channel reads back as an +annotation. diff --git a/stat/AGENTS.md b/stat/AGENTS.md new file mode 100644 index 0000000..d892e57 --- /dev/null +++ b/stat/AGENTS.md @@ -0,0 +1,67 @@ +# Working in `stat` + +Notes for changing `stat`, moved here from the root [AGENTS.md](../AGENTS.md), +which holds the rules that apply everywhere — read that one first. This file +covers stress layout, evaluation grids, no sorting, histograms and the +hexagonal lattice. + +## Things that will bite + +**A stress layout's row order decides which minimum it reaches, and that is a +bigger number than it sounds.** `stat.Stress` descends a non-convex objective, +and both the arrangement it starts from and the order a sweep visits the nodes +in come from the order the caller's rows interned them. So relabelling the same +edges is not a relabelling of the same picture: the collaboration graph in +`docs/images/network.png` settles at a stress of 3.47 in the order its rows +arrive in and at 2.30 under one relabelling — a third lower, from the same code +at the same budget. Picking the start rows more cleverly does not fix it; that +was measured and only moves which numbering is the unlucky one +([ADR 0077](../docs/adr/0077-a-node-link-layout.md)'s second amendment has the +table). And **`geom.Order` is not the way to ask for another one**: it reaches +the grouped marks and the set charts, `geom/relational.go`'s edge reader never +looks at it, and a `NodeLink` given one draws exactly what it drew. A caller +who wants a different node order re-orders the rows of the table. `stat.StressSweeps` is a *budget* and not a convergence point — about +four percent of stress is still on the table at fifty sweeps for a 127-node +tree — and a monotone descent on the stress is not a monotone improvement in +legibility, because nothing here counts an overlap or a crossing. + +**A stat evaluated on a grid pins the grid's ends, and never truncates a +kernel.** Both halves of that are the same bug, and it shipped for exactly one +CI run — green on amd64, red on macOS. `lo + float64(i)*step` is a multiply and +an add, which Go may contract into an FMA "possibly across statements"; arm64 +takes it and amd64 does not, so a grid of sixty-one points over [-3, 3] ended +at 3 on one machine and 3.0000000000000004 on the other. That is one ulp, and +one ulp is invisible — until it lands on the far side of a *decision*. `AppendKDE` +skipped any sample past four bandwidths, so the endpoint's kernel was summed on +one architecture and dropped on the other, and a density that was symmetric on +one was not on the other. + +`stat.gridAt` now hands back the ends exactly rather than computing them, which +is the same "do not compute what is known" fix `scale.place` carries for the +same arithmetic; `AppendKDE` and `AppendLoess` both use it. And the kernel is +summed in full: a cutoff is a discontinuity, so the estimate depended on the +last bit of its argument, and it was not buying an order of growth either — the +loop visits every row either way and the cutoff saved an `exp`. +`TestADensityHasNoCliffInItsTail` and `TestAnEvaluationGridEndsExactlyOnItsBounds` +are what hold both, and the first fails on *every* architecture, which is the +point: a property that only one machine can check is a property nobody checks. + +**`stat` does no sorting, and the geoms keep the buffers.** `Quantile`, `ECDF` +and `Loess` take ordered columns; `Silverman` takes two spread measures rather +than computing an IQR. Sorting inside a stat means either mutating the caller's +column or allocating a copy of it per frame, and a chart redrawn every frame +already keeps a buffer. Every distribution geom therefore carries its own sort +buffer on the layer, for the reason `barGeom.gaps` does: `Train` runs outside a +`Build`, where there is no scratch to take. + +**`stat.Bin` is the 1-D histogram now.** The 2-D binner that used to be called +`Bin` is `stat.BinGrid`, beside `stat.BinHex`. The three are named after what +they fill, and "bin" without a qualifier means the histogram. + +**A hexagonal lattice is not d3-hexbin's.** `Hex.Cell` follows its structure and +corrects its metric: both work in lattice coordinates where a column step is 1 +and a row step is 1, but on screen those are √3·r and 1.5·r, so comparing +`px² + py²` there mixes units and misplaces points near the interlocking band. +The vertical term carries `(dy/dx)² = 3/4`, and +`TestEveryHexPointLandsInItsNearestCell` checks the defining property directly. +Without it the picture grows seams along every second row. diff --git a/three/AGENTS.md b/three/AGENTS.md new file mode 100644 index 0000000..ae67a61 --- /dev/null +++ b/three/AGENTS.md @@ -0,0 +1,136 @@ +# Working in `three` + +Notes for changing `three`, moved here from the root [AGENTS.md](../AGENTS.md), +which holds the rules that apply everywhere — read that one first. This file +covers the painter's order, the depth key, occlusion tests, batching faces, the +fitted cube, scene scratch and projected axis labels. + +## Things that will bite + +**`figure/three` paints in its own order, and `render` did not gain a second +one.** A `three.Layer` is deliberately not a `geom.Geom`: a geom's `Build` +streams ink, which makes a layer a paint unit, and a projected scene has no +paint unit smaller than the view. So a layer emits primitives into a `Sink` and +one painter projects, orders and draws all of them at once. If a change here +starts wanting `render` to record layers and merge the recordings, that is the +thing [ADR 0010](../docs/adr/0010-panel-layout.md) exists to prevent and +[ADR 0056](../docs/adr/0056-three-dimensional-charts.md) refuses again. + +**The depth key is the centroid's depth along the view direction, one formula +for every primitive of every layer, ties to the emission index.** Two things +that look like improvements are not, and both were tried: + +*Letting a layer pick its own measure* is two numbers on two scales — they +differ by the height times the view direction's z — so one layer sorts wholly +before the other however the geometry runs. + +*Keying on the centroid dropped to the floor* is the subtler one, because its +argument is half true: that key does vary less over a steep primitive, and it +is monotone along every view ray. It still does not follow, and this is the +sentence to remember — **monotone along a ray says nothing about two +centroids, which lie on two different rays.** Two sheets at different heights +whose footprints overlap without coinciding come out backwards. +`TestASheetIsNotPaintedOverTheOneInFrontOfIt` is that case with the numbers in +it; run it before believing any replacement key. + +**What the key promises is smaller than "correct", and the difference is the +part to know.** Two primitives are ordered correctly when their depth *ranges* +are disjoint. Where the ranges interleave, no per-primitive number decides +between them and this package does not split them apart — splitting is a BSP +tree, which is a renderer. Real charts stay inside the promise because the +shapes emitted here are already small: one quad per cell, one face per bar +side, one primitive per path segment. The case that leaves it is several layers +stacked over a grid coarse enough that one cell spans more depth than the +layers are apart. + +**Letting a layer pick its own depth measure is the same bug one level up.** +Two layers keyed by two different formulas are two numbers on two scales, and +merging them is arithmetic rather than geometry: one layer sorts wholly before +the other however the geometry runs. `TestASurfaceAndAPathAreOrderedAgainstEachOther` +is what catches it, and it is invisible in any picture with one layer in it. + +**The occlusion tests cast rays; they do not restate the sort.** A test whose +expected answer recomputes the ordering rule proves only that the sort sorts. +`checkOcclusion` intersects the view ray through each sample point with the +plane of every primitive covering it and insists the nearest is painted last — +so it fails for any key that gets the visible picture wrong, including the one +the implementation happens to use. Keep it that way when the key changes. + +**The depth key is computed in float64 and stored as float32, on purpose.** The +narrowing turns a near-tie into an exact tie, and an exact tie is broken by +emission index, which is the same on every architecture. A float64 key would +let two primitives a ulp apart order one way on arm64 and the other on amd64 — +and `internal/svgdiff` tolerates exactly that much coordinate difference, so +the reorder would *not* be caught. It is `scale.place`'s and `stat.LTTB`'s +lesson in a third place. + +**Faces batch by run, never by colour — and only where the merge is provably +invisible.** `geom.groupByColor` merges every mark of one colour into one call +because order within a flat layer does not matter. In a scene the order *is* +the thing being computed, so only primitives already adjacent in it are +candidates at all. Adjacency is not sufficient either: two adjacent faces can +still overlap on screen, and a run that draws all its fills and then all its +outlines puts a farther face's outline over a nearer face's fill, while a union +filled once is not what several translucent fills compose to. So `mergeable` +takes the run only for an opaque, unoutlined style, where the colour is the +same everywhere in the union either way. Widening that condition is how the +painter's order gets undone by the optimisation meant to be invisible. + +**A surface fills and outlines only when asked.** `interact` ranks a stroked +vertex above the area it outlines, so a mesh that always drew its own outline +would report a corner on every hover. It is `geom.Rect`'s rule and it is +load-bearing rather than cosmetic. + +**`three` announces its panels with nil X and Y.** A projected scene has no +screen axes to invert a device position through, and `interact.Index.At` +already checks before it inverts — so a hit reports `Kind`, `Layer`, `Series` +and `Row`, and leaves `Hit.X` and `Hit.Y` at zero. Filling them in with the +scene's scales would name a value nothing was drawn at. + +**The cube is fitted to its own circumscribed sphere, not to its projected +box.** The sphere's radius is a constant of the scene and the box's is not, so +the scene keeps its size while it turns. Fitting the box is the tighter fit and +makes the picture breathe under the reader's hand, and an instrument whose +scale moves while it is being read is not one. `three.Dolly` is how the reader +reclaims the room this costs. + +**A `three.Live` keeps its own scratch; a one-shot render borrows from the +pool.** A scene large enough to be worth turning is megabytes of vertex arena, +so drawing one allocates enough between frames to run a collection — and +`sync.Pool` is emptied by one. A chart redrawn on every pointer move would find +an empty pool and rebuild its arenas every frame. `BenchmarkOrbit32` and +`BenchmarkOrbit96` are what catch it going back. + +**A scene's scales are trained once per frame however many views look at it.** +`scale.Scale.Train` accumulates, so training per view gives every layer as many +times its weight as there are cameras — and the symptom is a domain that +changes when an author adds a picture, which looks entirely reasonable and is +wrong. There is a test that counts the calls. + +**A shaded surface is one drawing call per quad, and a trajectory one per +segment.** The IR carries no per-mark colour +([ADR 0007](../docs/adr/0007-per-mark-colour.md)), so faces that differ in shade +cannot be merged, and a path with one depth would sort as one thing. That is a +cost model rather than a bug, but it is still a count, and +`backend/stilus/cmd/gallery`'s tests render every figure about five times over in +each of two formats. `TestNoFigureIsDrawnWithTooManyCalls` is the wall, and it +counts calls rather than seconds because a timing assertion on a shared runner +is a gate people learn to ignore. + +**A projected axis labels itself only if at least two of its labels survive.** +Turn a scene until an axis points at the reader and it projects to a few +pixels: every value on it lands in the same place. A pile of overlapping +numbers there looks wrong at a glance and a reader discounts it; the single +number a greedy collision pass leaves behind looks like a label and reads like +one, while naming a position that cannot be told from any other on that axis. +So `three`'s label pass runs twice, once to count and once to draw, and an +axis that keeps fewer than two gives its boxes back to the next axis. Its +line, its tick marks and its title stay: a mark is a position, a number is a +claim about how much room there is. + +**An axis title is placed past its own tick labels, and both the room and the +placement come from `furnitureReach`.** They were computed separately once: the +title was put a guessed distance out, its box overlapped the labels', it won +the collision because a title is placed first, and the axis quietly lost most +of its numbers. A guess and a measurement of the same distance are two numbers; +that function exists so there is one.