PineCanvas: A Native High-Resolution Graphics Engine

Alien_Algorithms · library · 5924 行 · 点赞 13 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// For commercial use licensing, contact https://www.tradingview.com/u/Alien_Algorithms/
// © Alien_Algorithms
 
//@version=6
 
// @description PineCanvas - A contour rendering engine for TradingView Pine Script.
//              Renders value fields, palette fields, rolling sources, and filled shapes.
//              Packs same-color regions into shared polylines and reuses cached tile geometry.
library("PineCanvas", overlay = false)
 
// Same-color regions share filled polylines. Contour loops are joined by
// zero-area links aligned with the grid to reduce rasterization artifacts.
// Tile geometry is cached and reused when its quantized cells are unchanged.
 
// ============================================================================
// CONSTANTS
// ============================================================================
 
const int MAX_POLYLINES = 100
const int MAX_POINTS    = 10000
const int MAX_CELLS     = 100000
const int MAX_ARRAY_ELEMENTS = 100000
const int FLAT_CELL_LIMIT = 100000
const int MAX_PAST_BARS = 10000
const int MAX_FUTURE_BARS = 500
// Sort keys combine a loop's first corner with its insertion index.
// RAIL_SPAN exceeds the number of loops that fit in one polyline.
const int RAIL_SPAN = 4096
const int TILE_SIZE = 32
const int TILE_EDGE_CAPACITY = TILE_SIZE * TILE_SIZE * 4
const int PAGE_ELEMENTS = 65536
const int PARTITION_TARGET_POINTS = 9000
// Stride for packed tile-slot and local-chain references.
const int CHAIN_REFERENCE_BASE = MAX_CELLS * 128 + 1
// Stride for packed world-space row and column coordinates.
const int WORLD_STRIDE = 1000000
const int TILE_KEY_STRIDE = 100000
const int GENERIC_WORLD_ORIGIN = 100000
 
_findRoot(array<int> parents, int cell) =>
    root = cell
    parent = parents.get(root)
    while parent != root
        root := parent
        parent := parents.get(root)
    cursor = cell
    while cursor != root
        next = parents.get(cursor)
        parents.set(cursor, root)
        cursor := next
    root
 
// Merge a neighbor into the current component, retaining its smallest cell
// as the root. currentRoot is -1 or an already-resolved root.
_mergeRoot(array<int> parents, int currentRoot, int neighbor) =>
    neighborRoot = parents.get(neighbor) == currentRoot ?
      currentRoot : _findRoot(parents, neighbor)
    if currentRoot >= 0 and neighborRoot != currentRoot
        parents.set(currentRoot > neighborRoot ? currentRoot : neighborRoot,
          currentRoot < neighborRoot ? currentRoot : neighborRoot)
    currentRoot < 0 or neighborRoot < currentRoot ? neighborRoot : currentRoot
 
_tileRoot(
  array<int> owners,
  array<int> roots,
  int rowStart,
  int columnStart,
  int columnEnd,
  int row,
  int worldColumn,
  int columns,
  int worldOrigin
  ) =>
    result = -1
    if roots.size() > 0
        localColumns = columnEnd - columnStart
        localCell = (row - rowStart) * localColumns +
          worldColumn - columnStart
        localRoot = owners.size() == 1 and owners.first() == -2 ?
          0 : owners.get(localCell)
        if localRoot >= 0
            rootRow = int(localRoot / localColumns)
            result := (rowStart + rootRow) * columns + columnStart +
              localRoot - rootRow * localColumns - worldOrigin
    result
 
_compileTileOwnership(
  array<int> halo,
  int haloColumns,
  int localRows,
  int localColumns,
  int uniformLevel,
  array<int> owners,
  array<int> roots
  ) =>
    localCells = localRows * localColumns
    roots.clear()
    if uniformLevel >= -1
        owners.clear()
        if uniformLevel >= 0
            owners.push(-2)
            roots.push(0)
    else
        while owners.size() < localCells
            owners.push(-1)
        owners.fill(-1, 0, localCells)
        // Label 8-connected cells with the smallest cell as root. Test west and
        // north first; only merge diagonals not already connected through them.
        // Parents point to earlier cells, so one forward pass resolves all roots.
        cell = 0
        for localRow = 0 to localRows - 1
            center = (localRow + 1) * haloColumns + 1
            previousRoot = -1
            for localColumn = 0 to localColumns - 1
                level = halo.get(center)
                if level < 0
                    previousRoot := -1
                else
                    upSame = localRow > 0 and
                      halo.get(center - haloColumns) == level
                    root = -1
                    if localColumn > 0 and halo.get(center - 1) == level
                        root := previousRoot
                    else if upSame
                        root := _findRoot(owners, cell - localColumns)
                    else if localRow > 0 and localColumn > 0 and
                      halo.get(center - haloColumns - 1) == level
                        root := _mergeRoot(
                          owners, root, cell - localColumns - 1)
                    if not upSame and localRow > 0 and
                      localColumn < localColumns - 1 and
                      halo.get(center - haloColumns + 1) == level
                        root := _mergeRoot(
                          owners, root, cell - localColumns + 1)
                    previousRoot := root < 0 ? cell : root
                    owners.set(cell, previousRoot)
                    if root < 0
                        roots.push(cell)
                cell += 1
                center += 1
        for localCell = 0 to localCells - 1
            owner = owners.get(localCell)
            if owner >= 0
                owners.set(localCell, owners.get(owner))
        retained = 0
        candidateCount = roots.size()
        if candidateCount > 0
            for candidateIndex = 0 to candidateCount - 1
                candidate = roots.get(candidateIndex)
                if owners.get(candidate) == candidate
                    roots.set(retained, candidate)
                    retained += 1
        while roots.size() > retained
            roots.pop()
    0
 
// ============================================================================
// PUBLIC TYPES
// ============================================================================
 
//@enum Selects how automatic value normalization is calculated.
//@field wholeGrid Use one minimum and maximum across the complete value source.
//@field eachColumn Normalize every time/X column independently.
//@field eachRow Normalize every Y row independently.
export enum ScaleMode
    wholeGrid = "Whole grid"
    eachColumn = "Each column"
    eachRow = "Each row"
 
//@type Rendering configuration for a Canvas.
//@field colorLevels Number of colors sampled from the gradient, from 2 to 100.
//@field lowOpacity Visible opacity percentage assigned to the lowest color.
//@field highOpacity Visible opacity percentage assigned to the highest color.
//@field autoScale Automatically map the supplied finite values from their minimum/maximum to 0..1.
//@field valueMin Manual input value mapped to 0 when autoScale is false.
//@field valueMax Manual input value mapped to 1 when autoScale is false.
//@field gamma Positive exponent applied to normalized values before color selection.
//@field logarithmicY Use logarithmically spaced Y edges in regular-grid drawing functions.
//@field invertRows Map row 0 to the top of the rendered field.
//@field forceOverlay Force generated polylines into the main chart pane.
//@field scaleMode Scope used by automatic normalization when autoScale is true.
//@field drawingLimit Maximum polyline objects this Canvas may own, from 1 to 100.
export type Style
    int colorLevels = 64
    float lowOpacity = 15.0
    float highOpacity = 90.0
    bool autoScale
    float valueMin = 0.0
    float valueMax = 1.0
    float gamma = 1.0
    bool logarithmicY
    bool invertRows
    bool forceOverlay
    ScaleMode scaleMode = ScaleMode.wholeGrid
    int drawingLimit = 100
 
// ============================================================================
// RASTER SOURCES
// ============================================================================
//
// Fixed and rolling fields store row-major cells in complete-row bands.
// The renderer selects the flat or large path from the source layout.
 
//@type One complete-row band of a ValueField or ValueScroll.
//@field rowStart First logical row stored in this band.
//@field rowCount Complete rows stored in this band.
//@field values Flat row-major storage. Do not resize it.
export type ValueBand
    int rowStart = 0
    int rowCount = 0
    array<float> values
 
//@type One complete-row band of a PaletteField, a PaletteScroll, or an internal integer plane.
//@field rowStart First logical row stored in this band.
//@field rowCount Complete rows stored in this band.
//@field values Flat row-major storage. Do not resize it.
export type PaletteBand
    int rowStart = 0
    int rowCount = 0
    array<int> values
 
//@type A fixed 2D field of continuous values, scaled by the Canvas configuration.
//@field rows Logical row count.
//@field columns Logical column count.
//@field bandHeight Maximum complete rows stored in each physical band.
//@field bands Internal complete-row storage. Prefer row() or band() for procedural writes.
export type ValueField
    int rows = 0
    int columns = 0
    int bandHeight = 0
    array<ValueBand> bands
 
//@type A fixed 2D field of exact palette indices. -1 is transparent.
//@field rows Logical row count.
//@field columns Logical column count.
//@field bandHeight Maximum complete rows stored in each physical band.
//@field bands Internal complete-row storage. Prefer row() or band() for procedural writes.
export type PaletteField
    int rows = 0
    int columns = 0
    int bandHeight = 0
    array<PaletteBand> bands
 
// The ring head is the next column to overwrite and, once full, the oldest
// column. Chronological reads use one interval before wrapping and two after.
 
//@type A rolling 2D field of continuous value columns.
//@field rows Cell rows in every pushed column.
//@field capacity Maximum columns retained.
//@field written Columns pushed so far, saturating at capacity.
//@field head Next physical ring column to overwrite.
//@field origin Logical index of the oldest visible column.
//@field revision Number of calls to push().
//@field bandHeight Maximum complete rows stored in each physical band.
//@field bands Internal rows x capacity ring storage.
export type ValueScroll
    int rows = 0
    int capacity = 0
    int written = 0
    int head = 0
    int origin = 0
    int revision = 0
    int bandHeight = 0
    array<ValueBand> bands
 
//@type A rolling 2D field of exact palette-index columns. -1 is transparent.
//@field rows Cell rows in every pushed column.
//@field capacity Maximum columns retained.
//@field written Columns pushed so far, saturating at capacity.
//@field head Next physical ring column to overwrite.
//@field origin Logical index of the oldest visible column.
//@field revision Number of calls to push().
//@field bandHeight Maximum complete rows stored in each physical band.
//@field bands Internal rows x capacity ring storage.
export type PaletteScroll
    int rows = 0
    int capacity = 0
    int written = 0
    int head = 0
    int origin = 0
    int revision = 0
    int bandHeight = 0
    array<PaletteBand> bands
 
//@type Internal scalable integer plane.
export type _IntPlane
    int rows = 0
    int columns = 0
    int bandRows = 0
    array<PaletteBand> bands
 
//@type One primitive page used by scalable metadata streams.
export type _IntPage
    array<int> values
 
//@type A logical integer vector backed by bounded primitive pages.
export type _IntPages
    int size = 0
    array<_IntPage> pages
 
//@type One exact tile-aligned render fragment of an oversized component.
export type _Fragment
    int componentId = -1
    int rowStart = 0
    int rowEnd = 0
    int columnStart = 0
    int columnEnd = 0
    int exactPoints = -1
 
//@type Exact topology for one world-aligned 32 x 32 tile.
// Chains end at tile seams and ambiguous junctions. chainExit caches the
// preferred continuation; chainComponents maps chains to global components.
export type _TileProgram
    int key = -1
    int rowStart = -1
    int rowEnd = -1
    int columnStart = -1
    int columnEnd = -1
    int activeGeneration = -1
    array<int> boundaryCell
    array<int> boundaryMask
    array<int> edgeChain
    array<int> chainEnd
    array<int> chainFirstEdge
    array<int> chainState
    array<int> vertices
    array<int> chainExit
    array<int> chainComponents
 
// Per-draw parameters shared by render stages. Not retained between calls.
type _Frame
    array<int> xEdges
    array<float> yEdges
    array<color> gradient
    Style style
    bool indexed
    bool timeCoordinates
    int rows
    int columns
 
//@type Internal persistent Canvas renderer storage.
// Exported because Canvas contains this type. Internal fields are not part
// of the supported API.
export type _CanvasScratch
    array<int> xEdges
    array<float> yEdges
    int regularYRows = -1
    float regularYMin
    float regularYMax
    bool regularYLog
    array<float> groupMin
    array<float> groupMax
    array<int> bins
    // Packed start vertices used to replay a backward-traced chain in order.
    array<int> prefixVertices
    array<int> componentParent
    array<int> componentOrder
    array<int> boundaryOrder
    array<int> gapComponents
    // Cached per-component point counts: straight-link cost, grid-link bound,
    // and palette level. Rebuilt when topology changes.
    array<int> flatUnitPoints
    array<int> flatUnitFit
    array<int> flatUnitLevels
    int flatVisibleUnits = 0
    array<int> corners
    // Staged contour loops, sort keys, and row stamps for the current polyline.
    // linked holds the finished path; overflowDrawings counts budget excess.
    array<int> anchors
    array<int> chunkVertices
    array<int> railKeys
    array<int> railStarts
    array<int> railStamps
    array<int> linked
    int railSerial = 1
    int railCount = 0
    int overflowDrawings = 0
    array<chart.point> points
    array<int> lastXEdges
    array<float> lastYEdges
    array<color> lastPalette
    // Previous quantized cells. Swapped with bins to avoid copying each frame.
    array<int> lastBins
    int lastRows = -1
    int lastColumns = -1
    int lastStyleKey = -1
    float lastLowOpacity
    float lastHighOpacity
    int lastDrawCount = -1
    bool lastLargeField
    // Tile cache keyed by world-cell position. Recompile changed and clipped
    // tiles; retain complete tiles across scrolling.
    // Keep exported type fields free of foreign-library types to avoid requiring
    // transitive imports in callers. Slot order determines chain order.
    map<int, int> tileLookup
    array<_TileProgram> tilePrograms
    array<int> activeTileSlots
    array<int> previousTileSlots
    array<int> freeTileSlots
    // Generation stamps and tile slots in discovery order. Do not sort this list.
    array<int> dirtyTileSlots
    array<int> tileDirtyStamp
    array<int> tileRoots
    int tileGeneration = 0
    int activeTileColumns = 0
    int firstWorldTileColumn = 0
    int worldOrigin = 0
    int lastWorldOrigin = 0
    bool hasProducerOrigin
    int dirtyCellCount = 0
    // Chronological buffers for flat rolling sources. Large sources are read
    // directly from their storage bands.
    array<float> scrollValues
    array<int> scrollIndices
    // Reusable Style for exact palette sources.
    Style paletteStyle
    // Queued vertices in time and price coordinates. shapeEnd stores exclusive
    // end offsets; linked lists group shapes by fill color.
    array<int> shapeTime
    array<float> shapeY
    array<int> shapeEnd
    array<int> shapeNext
    array<color> shapePalette
    array<int> shapeLevelFirst
    array<int> shapeLevelLast
    // Temporary input buffers consumed synchronously by the shape queue.
    array<chart.point> shapeInputPoints
    array<int> shapeInputTime
    array<float> shapeInputY
    // Connected same-color region count from the most recent field render.
    int lastComponentCount = 0
    // Banded raster state for the large renderer.
    _IntPlane largeBins
    _IntPlane largeLastBins
    _IntPlane largeParents
    _IntPlane largeFragmentBins
    _IntPlane largeFragmentParents
    array<int> candidateSameTileStamp
    array<int> candidateShiftTileStamp
    array<int> candidateSameTiles
    array<int> candidateShiftTiles
    int candidateGeneration = 0
    // Stamp identifying the current chain walk.
    int chainStamp = 0
    array<int> largeTileHalo
    // Paged component metadata and compressed sparse row lists of chains.
    _IntPages largeComponentRoot
    _IntPages largeComponentNext
    _IntPages largeComponentChainCount
    _IntPages largeComponentChainOffset
    _IntPages largeComponentChainFill
    _IntPages largeComponentPointBound
    _IntPages largeComponentExactPoints
    _IntPages largeComponentMinTileRow
    _IntPages largeComponentMaxTileRow
    _IntPages largeComponentMinTileColumn
    _IntPages largeComponentMaxTileColumn
    _IntPages largeChainSlots
    _IntPages largeChainLocals
    _IntPages largeTraceVertices
    _IntPages largeTraceLoopStart
    _IntPages largeTraceLoopEnd
    _IntPages largeFragmentVertices
    _IntPages largeFragmentLoopStart
    _IntPages largeFragmentLoopEnd
    _IntPages largeFragmentFirstLoop
    _IntPages largeFragmentLoopCount
    array<int> largeLevelFirst
    array<int> largeLevelLast
    array<int> largeLevelRegions
    array<int> largeLevelRenderUnits
    array<int> largeLevelMandatoryDrawings
    array<_Fragment> largeFragments
    array<_Fragment> largePendingFragments
    array<int> largePartitionFirst
    array<int> largePartitionComponents
    array<int> partitionXWeight
    array<int> partitionYWeight
    array<int> partitionCuts
 
//@type A persistent 2D canvas. Create one with newCanvas() or heatmap().
//@field drawings Polyline IDs currently owned by this Canvas.
//@field rows Row count from the most recent field render; 0 after clear().
//@field columns Column count from the most recent field render; 0 after clear().
//@field usesTime True when the most recent draw used bar-time coordinates.
//@field scaledMin Effective minimum used by the most recent value normalization.
//@field scaledMax Effective maximum used by the most recent value normalization.
//@field colors Configured value gradient or exact palette.
//@field style Rendering configuration.
//@field _scratch Internal reusable renderer storage.
export type Canvas
    array<polyline> drawings
    int rows = 0
    int columns = 0
    bool usesTime
    float scaledMin
    float scaledMax
    array<color> colors
    Style style
    _CanvasScratch _scratch
 
// ============================================================================
// INTERNAL UTILITIES
// ============================================================================
 
// The frame cache compares quantized cells and drawing inputs. It does not
// require a source ID, so equal content can reuse geometry across sources.
 
_renderStyleKey(_Frame frame) =>
    Style style = frame.style
    style.colorLevels + style.drawingLimit * 128 +
      (style.invertRows ? 1 : 0) * 16384 +
      (style.forceOverlay ? 1 : 0) * 32768 +
      (frame.timeCoordinates ? 1 : 0) * 65536 +
      (frame.indexed ? 1 : 0) * 131072
 
_clamp(float value, float lower, float upper) =>
    math.max(lower, math.min(upper, value))
 
// Direction of one axis-aligned step between distinct packed vertices:
// 0 right, 1 up, 2 left, 3 down.
_axisDirection(int delta) =>
    delta > 0 ? (delta < WORLD_STRIDE ? 0 : 1) : (delta > -WORLD_STRIDE ? 2 : 3)
 
 
_styleOrDefault(Style style) =>
    var Style defaultStyle = Style.new()
    na(style) ? defaultStyle : style
 
 
_defaultGradient() =>
    array.from(#0c0a26, #460553, #800080, #ff6600, #ffe600)
 
_validatePalette(array<color> colors) =>
    if na(colors)
        runtime.error("palette is na")
    colorCount = colors.size()
    if colorCount < 2 or colorCount > MAX_POLYLINES
        runtime.error("palettes needs 2..100 colors")
    for paletteColor in colors
        if na(paletteColor)
            runtime.error("palette colors is na")
    0
 
_validateStyle(Style style) =>
    if na(style)
        runtime.error("Style is na")
    if na(style.colorLevels) or na(style.drawingLimit) or
      na(style.lowOpacity) or na(style.highOpacity) or na(style.gamma) or
      (not style.autoScale and (na(style.valueMin) or na(style.valueMax)))
        runtime.error("Style numeric settings is na")
    if style.colorLevels < 2 or style.colorLevels > MAX_POLYLINES
        runtime.error("colorLevels must be 2..100")
    if style.drawingLimit < 1 or style.drawingLimit > MAX_POLYLINES
        runtime.error("drawingLimit must be 1..100")
    if style.lowOpacity < 0 or style.lowOpacity > 100 or
      style.highOpacity < 0 or style.highOpacity > 100
        runtime.error("opacity must be 0..100")
    if style.gamma <= 0
        runtime.error("gamma must be >0")
    if not style.autoScale and style.valueMax <= style.valueMin
        runtime.error("manual range must have max>min")
    0
 
_lookbackBounds(int columns, int lookback, int rightOffset) =>
    span = lookback == 0 ? columns : lookback
    if span < columns
        runtime.error("lookback must be 0 or >=columns")
    right = bar_index + rightOffset
    [right - span, right]
 
_canvasStyle(bool heat = false) =>
    Style.new(
      heat ? 64 : 2, heat ? 15.0 : 100.0, heat ? 90.0 : 100.0,
      heat, 0.0, 1.0, 1.0, false, false, false,
      ScaleMode.wholeGrid, MAX_POLYLINES)
 
_ensureScratch(Canvas canvas) =>
    if na(canvas._scratch)
        canvas._scratch := _CanvasScratch.new()
    canvas._scratch
 
_ensureConfigured(Canvas canvas) =>
    if na(canvas)
        runtime.error("Canvas is na; use newCanvas()")
    if na(canvas.drawings)
        canvas.drawings := array.new<polyline>()
    if na(canvas.colors)
        canvas.colors := _defaultGradient()
    if na(canvas.style)
        canvas.style := _canvasStyle()
    _ensureScratch(canvas)
    0
 
_growIntArray(array<int> source, int size, int fillValue = 0) =>
    result = source
    if na(result)
        result := array.new_int(size, fillValue)
    else if result.size() < size
        capacity = math.min(
          MAX_CELLS, math.max(size, result.size() * 2))
        result := array.new_int(capacity, fillValue)
    result
 
_growFloatArray(array<float> source, int size, float fillValue = na) =>
    result = source
    if na(result)
        result := array.new_float(size, fillValue)
    else if result.size() < size
        capacity = math.min(
          MAX_CELLS, math.max(size, result.size() * 2))
        result := array.new_float(capacity, fillValue)
    result
 
// Compare frame inputs element by element. Float comparisons intentionally
// use Pine's comparison semantics.
_sameIntArray(array<int> current, array<int> stored) =>
    same = not na(current) and not na(stored)
    if same
        same := current.size() == stored.size()
    if same
        for [i, value] in current
            if stored.get(i) != value
                same := false
                break
    same
 
_sameFloatArray(array<float> current, array<float> stored) =>
    same = not na(current) and not na(stored)
    if same
        same := current.size() == stored.size()
    if same
        for [i, value] in current
            // Invalid Y edges cannot match a cached frame.
            if na(value) or stored.get(i) != value
                same := false
                break
    same
 
_samePalette(array<color> current, array<color> stored) =>
    same = not na(current) and not na(stored)
    if same
        same := current.size() == stored.size()
    if same
        for [i, value] in current
            if stored.get(i) != value
                same := false
                break
    same
 
_sameFrameIdentity(
  Canvas canvas, _CanvasScratch scratch, _Frame frame, int styleKey
  ) =>
    styleKey == scratch.lastStyleKey and
      frame.style.lowOpacity == scratch.lastLowOpacity and
      frame.style.highOpacity == scratch.lastHighOpacity and
      canvas.drawings.size() == scratch.lastDrawCount and
      _sameIntArray(frame.xEdges, scratch.lastXEdges) and
      _sameFloatArray(frame.yEdges, scratch.lastYEdges) and
      _samePalette(frame.gradient, scratch.lastPalette)
 
// Detect a one-column shift from overlapping X edges. Bin equality is
// checked separately before reusing tile geometry.
_horizontalEdgeShift(
  array<int> current,
  array<int> previous,
  int columns
  ) =>
    result = 0
    if not na(previous) and previous.size() == columns + 1
        shiftedRight = current.first() == previous.get(1)
        if shiftedRight
            for edge = 1 to columns - 1
                if current.get(edge) != previous.get(edge + 1)
                    shiftedRight := false
                    break
        if shiftedRight
            result := 1
        else
            shiftedLeft = current.get(1) == previous.first()
            if shiftedLeft
                for edge = 1 to columns - 1
                    if current.get(edge + 1) != previous.get(edge)
                        shiftedLeft := false
                        break
            if shiftedLeft
                result := -1
    result
 
_storeIntSnapshot(array<int> previous, array<int> current) =>
    result = previous
    if na(result)
        result := current.copy()
    else
        result.clear()
        result.concat(current)
    result
 
_storeFloatSnapshot(array<float> previous, array<float> current) =>
    result = previous
    if na(result)
        result := current.copy()
    else
        result.clear()
        result.concat(current)
    result
 
_storeColorSnapshot(array<color> previous, array<color> current) =>
    result = previous
    if na(result)
        result := current.copy()
    else
        result.clear()
        result.concat(current)
    result
 
_storeFrameIdentity(
  _CanvasScratch scratch,
  _Frame frame,
  int styleKey,
  int drawCount
  ) =>
    // Bin buffers retain the cells. Cache both dimensions because different
    // grid shapes can have the same cell count.
    scratch.lastRows := frame.rows
    scratch.lastColumns := frame.columns
    scratch.lastStyleKey := styleKey
    scratch.lastLowOpacity := frame.style.lowOpacity
    scratch.lastHighOpacity := frame.style.highOpacity
    // Copy frame inputs; generated edge arrays are mutated on later draws.
    scratch.lastXEdges := _storeIntSnapshot(scratch.lastXEdges, frame.xEdges)
    scratch.lastYEdges := _storeFloatSnapshot(scratch.lastYEdges, frame.yEdges)
    scratch.lastPalette := _storeColorSnapshot(scratch.lastPalette, frame.gradient)
    scratch.lastDrawCount := drawCount
    0
 
_commitFrame(
  Canvas canvas,
  _CanvasScratch scratch,
  _Frame frame,
  bool foundValues,
  float scaleMin,
  float scaleMax,
  int worldOrigin,
  bool producerBacked
  ) =>
    canvas.rows := frame.rows
    canvas.columns := frame.columns
    canvas.usesTime := frame.timeCoordinates
    canvas.scaledMin := foundValues ? scaleMin : na
    canvas.scaledMax := foundValues ? scaleMax : na
    scratch.lastWorldOrigin := worldOrigin
    scratch.hasProducerOrigin := producerBacked
    canvas.drawings.size()
 
_clearDrawings(Canvas canvas) =>
    if na(canvas)
        runtime.error("Canvas is na; use newCanvas()")
    // Deleting Canvas drawings invalidates the frame cache.
    if not na(canvas._scratch)
        canvas._scratch.lastDrawCount := -1
    if not na(canvas.drawings)
        count = canvas.drawings.size()
        if count > 0
            for id in canvas.drawings
                id.delete()
            canvas.drawings.clear()
    0
 
_newFilledPolyline(
  array<chart.point> points,
  color fillColor,
  bool timeCoordinates,
  bool forceOverlay
  ) =>
    polyline id = na
    if forceOverlay
        // force_overlay requires literal const bool arguments.
        id := polyline.new(
          points,
          curved = false,
          closed = true,
          xloc = timeCoordinates ? xloc.bar_time : xloc.bar_index,
          line_color = color.new(fillColor, 100),
          fill_color = fillColor,
          line_style = line.style_solid,
          line_width = 1,
          force_overlay = true)
    else
        id := polyline.new(
          points,
          curved = false,
          closed = true,
          xloc = timeCoordinates ? xloc.bar_time : xloc.bar_index,
          line_color = color.new(fillColor, 100),
          fill_color = fillColor,
          line_style = line.style_solid,
          line_width = 1)
    id
 
_regularXEdges(
  int left,
  int right,
  int columns,
  bool timeCoordinates,
  array<int> scratch = na
  ) =>
    if na(left) or na(right)
        runtime.error("X bounds is na")
    if columns < 2
        runtime.error("Columns must be >=2")
    span = right - left
    if span < columns
        if timeCoordinates
            runtime.error("rightTime must exceed leftTime")
        else
            runtime.error("X span must be >=columns")
    // Reuse regular X edges when their count and both bounds match.
    reusable = not na(scratch)
    if reusable
        reusable := scratch.size() == columns + 1
    if reusable
        reusable := scratch.first() == left and scratch.last() == right
    edges = scratch
    if not reusable
        if na(edges)
            edges := array.new_int()
        else
            edges.clear()
        for column = 0 to columns
            edges.push(left + int(math.round(column * span / float(columns))))
    edges
 
_nativeRowExtrema(array<float> cells, int start, int count) =>
    float minimum = na
    float maximum = na
    if count > 0
        if count == 1
            // A wrapped tail can be one cell: no view allocation is needed.
            minimum := cells.get(start)
            maximum := minimum
        else
            // Temporary read-only slice. Native extrema ignore na.
            run = cells.slice(start, start + count)
            minimum := run.min()
            maximum := run.max()
    [minimum, maximum]
 
_regularYEdges(
  float yMin,
  float yMax,
  int rows,
  bool logarithmic,
  array<float> scratch = na
  ) =>
    if na(yMin) or na(yMax)
        runtime.error("Y bounds is na")
    if rows < 2
        runtime.error("Rows must be >=2")
    if yMax <= yMin
        runtime.error("yMax must exceed yMin")
    if logarithmic and yMin <= 0
        runtime.error("log Y requires yMin>0")
    // Y bounds alone do not identify linear or logarithmic spacing. Cache
    // reuse must also check the spacing mode.
    edges = scratch
    if na(edges)
        edges := array.new_float()
    else
        edges.clear()
    // Select the spacing mode before the loop. Preserve arithmetic order
    // because the frame cache compares generated edges directly.
    if logarithmic
        logMin = math.log(yMin)
        logMax = math.log(yMax)
        logSpan = logMax - logMin
        for row = 0 to rows
            fraction = row / float(rows)
            edges.push(math.exp(logMin + logSpan * fraction))
    else
        span = yMax - yMin
        for row = 0 to rows
            fraction = row / float(rows)
            edges.push(yMin + span * fraction)
    edges
 
_cachedRegularYEdges(
  _CanvasScratch state,
  float yMin,
  float yMax,
  int rows,
  bool logarithmic
  ) =>
    // Use subtraction to detect changes finer than Pine's float comparisons.
    // Cache the key only after edge generation succeeds.
    reusable = rows == state.regularYRows and
      logarithmic == state.regularYLog and not na(state.yEdges)
    if reusable
        reusable := state.yEdges.size() == rows + 1 and
          math.sign(yMin - state.regularYMin) == 0 and
          math.sign(yMax - state.regularYMax) == 0
    if not reusable
        state.yEdges := _regularYEdges(yMin, yMax, rows, logarithmic, state.yEdges)
        state.regularYRows := rows
        state.regularYMin := yMin
        state.regularYMax := yMax
        state.regularYLog := logarithmic
    state.yEdges
 
_validateIndexBounds(int leftIndex, int rightIndex) =>
    if leftIndex < 0
        runtime.error("bar index is negative")
    if leftIndex < bar_index - MAX_PAST_BARS
        runtime.error("X is >10000 bars back; use time")
    if rightIndex > bar_index + MAX_FUTURE_BARS
        runtime.error("X is >500 future bars")
    0
 
// Validate the first edge separately, then carry the previous edge through
// the monotonicity check.
_validateCoordinates(array<int> xEdges, array<float> yEdges, bool timeCoordinates) =>
    if na(xEdges) or na(yEdges)
        runtime.error("edge arrays is na")
    xCount = xEdges.size()
    yCount = yEdges.size()
    if xCount < 3 or yCount < 3
        runtime.error("X/Y edges need >=3 values")
 
    previousX = xEdges.get(0)
    if na(previousX)
        runtime.error("X edges contain na")
    for i = 1 to xCount - 1
        currentX = xEdges.get(i)
        if na(currentX)
            runtime.error("X edges contain na")
        if currentX <= previousX
            runtime.error("X edges must increase")
        previousX := currentX
 
    previousY = yEdges.get(0)
    if na(previousY)
        runtime.error("Y edges contain na")
    for i = 1 to yCount - 1
        currentY = yEdges.get(i)
        if na(currentY)
            runtime.error("Y edges contain na")
        if currentY <= previousY
            runtime.error("Y edges must increase")
        previousY := currentY
 
    if not timeCoordinates
        _validateIndexBounds(xEdges.first(), xEdges.last())
    0
 
_validateCoordinateMode(
  array<int> xEdges,
  array<float> yEdges,
  bool timeCoordinates,
  bool generatedCoordinates
  ) =>
    if generatedCoordinates
        if not timeCoordinates
            _validateIndexBounds(xEdges.first(), xEdges.last())
    else
        _validateCoordinates(xEdges, yEdges, timeCoordinates)
    0
 
_markTileSlotDirty(_CanvasScratch scratch, int slot) =>
    if scratch.tileDirtyStamp.get(slot) != scratch.tileGeneration
        scratch.tileDirtyStamp.set(slot, scratch.tileGeneration)
        scratch.dirtyTileSlots.push(slot)
    0
 
// Prepare the world-tile directory before quantization.
_prepareTileDirectory(
  _CanvasScratch scratch,
  int rows,
  int columns,
  int worldOrigin
  ) =>
    // Tile-cache arrays share one lifetime; initialize them from one sentinel.
    if na(scratch.tileLookup)
        scratch.tileLookup := map.new<int, int>()
        scratch.tilePrograms := array.new<_TileProgram>()
        scratch.activeTileSlots := array.new_int()
        scratch.previousTileSlots := array.new_int()
        scratch.freeTileSlots := array.new_int()
        scratch.dirtyTileSlots := array.new_int()
        scratch.tileDirtyStamp := array.new_int()
        scratch.tileRoots := array.new_int()
        scratch.boundaryOrder := array.new_int()
        scratch.prefixVertices := array.new_int()
    previousWorldOrigin = scratch.worldOrigin
    previousWorldEnd = previousWorldOrigin + scratch.lastColumns
    lookup = scratch.tileLookup
    programs = scratch.tilePrograms
    oldActive = scratch.activeTileSlots
    hadActiveTiles = oldActive.size() > 0
    scratch.tileGeneration += 1
    scratch.dirtyTileSlots.clear()
 
    // Reuse the previous slot list as this frame's active list.
    activeSlots = scratch.previousTileSlots
    scratch.activeTileSlots := activeSlots
    scratch.previousTileSlots := oldActive
    activeSlots.clear()
 
    firstTileColumn = int(worldOrigin / TILE_SIZE)
    lastWorldColumn = worldOrigin + columns - 1
    lastTileColumn = int(lastWorldColumn / TILE_SIZE)
    tileColumns = lastTileColumn - firstTileColumn + 1
    tileRows = int((rows + TILE_SIZE - 1) / TILE_SIZE)
    if tileRows * tileColumns > MAX_ARRAY_ELEMENTS
        runtime.error("E3")
    scratch.firstWorldTileColumn := firstTileColumn
    scratch.activeTileColumns := tileColumns
    scratch.worldOrigin := worldOrigin
 
    for tileRow = 0 to tileRows - 1
        rowStart = tileRow * TILE_SIZE
        rowEnd = math.min(rows, rowStart + TILE_SIZE)
        for tileColumn = firstTileColumn to lastTileColumn
            key = tileRow * TILE_KEY_STRIDE + tileColumn
            columnStart = math.max(worldOrigin, tileColumn * TILE_SIZE)
            columnEnd = math.min(
              worldOrigin + columns,
              (tileColumn + 1) * TILE_SIZE)
            slot = lookup.get(key)
            created = na(slot)
            if created
                if lookup.size() >= 50000
                    runtime.error("E4")
                if scratch.freeTileSlots.size() > 0
                    slot := scratch.freeTileSlots.pop()
                else
                    slot := programs.size()
                    _TileProgram createdProgram = _TileProgram.new()
                    createdProgram.boundaryCell := array.new_int()
                    createdProgram.boundaryMask := array.new_int()
                    createdProgram.edgeChain := array.new_int()
                    createdProgram.chainEnd := array.new_int()
                    createdProgram.chainFirstEdge := array.new_int()
                    createdProgram.chainState := array.new_int()
                    createdProgram.vertices := array.new_int()
                    createdProgram.chainExit := array.new_int()
                    programs.push(createdProgram)
                    scratch.tileDirtyStamp.push(-1)
                _TileProgram record = programs.get(slot)
                record.key := key
                lookup.put(key, slot)
 
            _TileProgram record = programs.get(slot)
            clipChanged = record.rowStart != rowStart or
              record.rowEnd != rowEnd or
              record.columnStart != columnStart or
              record.columnEnd != columnEnd
            record.rowStart := rowStart
            record.rowEnd := rowEnd
            record.columnStart := columnStart
            record.columnEnd := columnEnd
            record.activeGeneration := scratch.tileGeneration
            activeSlots.push(slot)
            if created or clipChanged
                _markTileSlotDirty(scratch, slot)
 
    for slot in oldActive
        _TileProgram record = programs.get(slot)
        if record.activeGeneration != scratch.tileGeneration
            lookup.remove(record.key)
            record.key := -1
            scratch.freeTileSlots.push(slot)
    oldActive.clear()
    // Invalidate changed tile bounds. Generation stamps prevent duplicate entries.
    if hadActiveTiles and worldOrigin != previousWorldOrigin
        activeCount = activeSlots.size()
        activeIndex = 0
        while activeIndex < activeCount
            _markTileSlotDirty(scratch, activeSlots.get(activeIndex))
            activeIndex += tileColumns
    if hadActiveTiles and worldOrigin + columns != previousWorldEnd
        activeCount = activeSlots.size()
        activeIndex = tileColumns - 1
        while activeIndex < activeCount
            _markTileSlotDirty(scratch, activeSlots.get(activeIndex))
            activeIndex += tileColumns
    0
 
_markTileDirtyAt(
  _CanvasScratch scratch,
  int row,
  int column
  ) =>
    worldColumn = scratch.worldOrigin + column
    tileRow = int(row / TILE_SIZE)
    tileColumn = int(worldColumn / TILE_SIZE)
    activeColumn = tileColumn - scratch.firstWorldTileColumn
    tileColumns = scratch.activeTileColumns
    slots = scratch.activeTileSlots
    activeIndex = tileRow * tileColumns + activeColumn
    _markTileSlotDirty(scratch, slots.get(activeIndex))
 
    // Invalidate the changed cell's tile and orthogonal neighbors sharing its
    // edge. Diagonal junctions are resolved dynamically by the contour walker.
    localRow = row % TILE_SIZE
    localColumn = worldColumn % TILE_SIZE
    if localColumn == 0 and activeColumn > 0
        _markTileSlotDirty(scratch, slots.get(activeIndex - 1))
    if localColumn == TILE_SIZE - 1 and activeColumn < tileColumns - 1
        _markTileSlotDirty(scratch, slots.get(activeIndex + 1))
    if localRow == 0 and activeIndex >= tileColumns
        _markTileSlotDirty(scratch, slots.get(activeIndex - tileColumns))
    if localRow == TILE_SIZE - 1 and
      activeIndex + tileColumns < slots.size()
        _markTileSlotDirty(scratch, slots.get(activeIndex + tileColumns))
    0
 
// Whether the boundary of a level leaves a vertex along outgoing (0 right,
// 1 up, 2 left, 3 down), given which of the four surrounding cells hold it.
_leaves(bool lowerRight, bool upperRight, bool upperLeft, bool lowerLeft, int outgoing) =>
    outgoing == 0 ? lowerRight and not upperRight :
      outgoing == 1 ? upperRight and not upperLeft :
      outgoing == 2 ? upperLeft and not lowerLeft : lowerLeft and not lowerRight
 
// Return an unconsumed outgoing chain as slot * TILE_EDGE_CAPACITY +
// localChain, or -1. Chain states are compared with the current walk stamp.
_junctionChain(_CanvasScratch scratch, int vertexRow, int vertexColumn, int outgoing, int stamp) =>
    candidateRow = outgoing % 3 == 0 ? vertexRow - 1 : vertexRow
    candidateColumn = outgoing >= 2 ? vertexColumn - 1 : vertexColumn
    candidateSlot = scratch.activeTileSlots.get(int(candidateRow / TILE_SIZE) *
      scratch.activeTileColumns + int(candidateColumn / TILE_SIZE) -
      scratch.firstWorldTileColumn)
    _TileProgram candidate = scratch.tilePrograms.get(candidateSlot)
    localColumns = candidate.columnEnd - candidate.columnStart
    localEdge = ((candidateRow - candidate.rowStart) * localColumns +
      candidateColumn - candidate.columnStart) * 4 + outgoing + 1 - outgoing % 2 * 2
    localChain = candidate.edgeChain.get(localEdge)
    localChain >= 0 and candidate.chainFirstEdge.get(localChain) == localEdge and
      candidate.chainState.get(localChain) != stamp ?
      candidateSlot * TILE_EDGE_CAPACITY + localChain : -1
 
_calcBandRows(int columns) =>
    if na(columns) or columns < 1
        runtime.error("field Columns must be >=1")
    possibleRows = int(MAX_ARRAY_ELEMENTS / columns)
    if possibleRows < 1
        runtime.error("field row >100000 cells")
    result = possibleRows
    if result >= TILE_SIZE
        result -= result % TILE_SIZE
    result < 1 ? 1 : result
 
_validateFieldDimensions(int rows, int columns) =>
    if na(rows) or rows < 1
        runtime.error("field Rows must be >=1")
    bandRows = _calcBandRows(columns)
    bandCount = int((rows + bandRows - 1) / bandRows)
    if bandCount > MAX_ARRAY_ELEMENTS
        runtime.error("storage bands exceed capacity")
    bandRows
 
_validateFieldEdgeCapacity(int rows, int columns) =>
    if rows >= MAX_ARRAY_ELEMENTS or columns >= MAX_ARRAY_ELEMENTS
        runtime.error("coordinate edges exceed capacity")
    0
 
// Validate ring storage against capacity, which is its physical row stride.
// Drawing requires at least two rows and columns.
_validateScrollDimensions(int rows, int capacity) =>
    if rows < 2
        runtime.error("scroll rows must be >=2")
    if capacity < 2
        runtime.error("scroll capacity must be >=2")
    _validateFieldDimensions(rows, capacity)
    _validateFieldEdgeCapacity(rows, capacity)
    0
 
_ensureIntPlaneLayout(
  _IntPlane plane,
  int rows,
  int columns,
  int fillValue,
  bool clearSame
  ) =>
    bandRows = _calcBandRows(columns)
    same = not na(plane) and plane.rows == rows and
      plane.columns == columns and plane.bandRows == bandRows
    _IntPlane result = plane
    if not same
        if na(result)
            result := _IntPlane.new()
        result.rows := rows
        result.columns := columns
        result.bandRows := bandRows
        if na(result.bands)
            result.bands := array.new<PaletteBand>()
        else
            result.bands.clear()
        bandCount = int((rows + bandRows - 1) / bandRows)
        for bandIndex = 0 to bandCount - 1
            rowStart = bandIndex * bandRows
            rowCount = math.min(bandRows, rows - rowStart)
            result.bands.push(PaletteBand.new(
              rowStart, rowCount,
              array.new_int(rowCount * columns, fillValue)))
    else if clearSame
        for band in result.bands
            band.values.fill(fillValue)
    result
 
_ensureIntPlane(_IntPlane plane, int rows, int columns, int fillValue) =>
    _ensureIntPlaneLayout(plane, rows, columns, fillValue, true)
 
_planeGetRC(_IntPlane plane, int row, int column) =>
    bandIndex = int(row / plane.bandRows)
    PaletteBand band = plane.bands.get(bandIndex)
    band.values.get((row - band.rowStart) * plane.columns + column)
 
_planeSetRC(_IntPlane plane, int row, int column, int value) =>
    bandIndex = int(row / plane.bandRows)
    PaletteBand band = plane.bands.get(bandIndex)
    band.values.set((row - band.rowStart) * plane.columns + column, value)
    0
 
_parentGet(_IntPlane plane, int cell) =>
    row = int(cell / plane.columns)
    _planeGetRC(plane, row, cell - row * plane.columns)
 
_parentSet(_IntPlane plane, int cell, int value) =>
    row = int(cell / plane.columns)
    _planeSetRC(plane, row, cell - row * plane.columns, value)
 
_newPages() =>
    _IntPages.new(0, array.new<_IntPage>())
 
_pagesClear(_IntPages pages) =>
    pages.size := 0
    0
 
_pagesEnsureIndex(_IntPages pages, int index, int fillValue) =>
    pageIndex = int(index / PAGE_ELEMENTS)
    if pageIndex >= MAX_ARRAY_ELEMENTS
        runtime.error("E5")
    while pages.pages.size() <= pageIndex
        pages.pages.push(_IntPage.new(
          array.new_int(PAGE_ELEMENTS, fillValue)))
    0
 
_pagesResize(_IntPages pages, int size, int fillValue) =>
    if size > 0
        _pagesEnsureIndex(pages, size - 1, fillValue)
        remaining = size
        for page in pages.pages
            active = remaining < PAGE_ELEMENTS ? remaining : PAGE_ELEMENTS
            if active > 0
                page.values.fill(fillValue, 0, active)
            remaining -= active
            if remaining <= 0
                break
    pages.size := size
    0
 
_pagesGet(_IntPages pages, int index) =>
    pageIndex = int(index / PAGE_ELEMENTS)
    pages.pages.get(pageIndex).values.get(index - pageIndex * PAGE_ELEMENTS)
 
_pagesSet(_IntPages pages, int index, int value) =>
    pageIndex = int(index / PAGE_ELEMENTS)
    pages.pages.get(pageIndex).values.set(
      index - pageIndex * PAGE_ELEMENTS, value)
    0
 
_pagesPush(_IntPages pages, int value) =>
    index = pages.size
    _pagesEnsureIndex(pages, index, 0)
    _pagesSet(pages, index, value)
    pages.size += 1
    index
 
// Append source[first, finish) in page-sized runs. Requires finish > first.
_pagesAppendRange(_IntPages pages, array<int> source, int first, int finish) =>
    _pagesEnsureIndex(pages, pages.size + finish - first - 1, 0)
    offset = first
    while offset < finish
        pageIndex = int(pages.size / PAGE_ELEMENTS)
        target = pages.pages.get(pageIndex).values
        start = pages.size - pageIndex * PAGE_ELEMENTS
        count = math.min(finish - offset, PAGE_ELEMENTS - start)
        for step = 0 to count - 1
            target.set(start + step, source.get(offset + step))
        pages.size += count
        offset += count
    0
 
_largeChainPage(_CanvasScratch scratch, int index, int remaining) =>
    pageIndex = int(index / PAGE_ELEMENTS)
    pageOffset = index - pageIndex * PAGE_ELEMENTS
    slots = scratch.largeChainSlots.pages.get(pageIndex).values
    locals = scratch.largeChainLocals.pages.get(pageIndex).values
    available = math.min(remaining, PAGE_ELEMENTS - pageOffset)
    [slots, locals, pageOffset, available]
 
_ensureLargeMetadata(_CanvasScratch scratch) =>
    // Initialize metadata arrays together using one shared sentinel.
    if na(scratch.largeComponentRoot)
        scratch.largeComponentRoot := _newPages()
        scratch.largeComponentNext := _newPages()
        scratch.largeComponentChainCount := _newPages()
        scratch.largeComponentChainOffset := _newPages()
        scratch.largeComponentChainFill := _newPages()
        scratch.largeComponentPointBound := _newPages()
        scratch.largeComponentExactPoints := _newPages()
        scratch.largeComponentMinTileRow := _newPages()
        scratch.largeComponentMaxTileRow := _newPages()
        scratch.largeComponentMinTileColumn := _newPages()
        scratch.largeComponentMaxTileColumn := _newPages()
        scratch.largeChainSlots := _newPages()
        scratch.largeChainLocals := _newPages()
        scratch.largeTraceVertices := _newPages()
        scratch.largeTraceLoopStart := _newPages()
        scratch.largeTraceLoopEnd := _newPages()
        scratch.largeFragmentVertices := _newPages()
        scratch.largeFragmentLoopStart := _newPages()
        scratch.largeFragmentLoopEnd := _newPages()
        scratch.largeFragmentFirstLoop := _newPages()
        scratch.largeFragmentLoopCount := _newPages()
        scratch.largeLevelFirst := array.new_int(MAX_POLYLINES, -1)
        scratch.largeLevelLast := array.new_int(MAX_POLYLINES, -1)
        scratch.largeLevelRegions := array.new_int(MAX_POLYLINES, 0)
        scratch.largeLevelRenderUnits := array.new_int(MAX_POLYLINES, 0)
        scratch.largeLevelMandatoryDrawings := array.new_int(MAX_POLYLINES, 0)
    0
 
// ============================================================================
// CHRONOLOGICAL RUNS
// ============================================================================
//
// Chronological reads use [0, written) before the ring fills, then
// [head, capacity) followed by [0, head). Fixed fields use one full-width run.
 
_scrollRuns(int written, int capacity, int head) =>
    partial = written < capacity
    firstStart = partial ? 0 : head
    firstCount = partial ? written : capacity - head
    [firstStart, firstCount, written - firstCount]
 
// Materialize flat rolling sources in chronological order with at most two
// array slices per row. Large sources are read directly by the quantizer.
_materializeValueRuns(
  _CanvasScratch scratch,
  array<ValueBand> bands,
  int stride,
  int firstStart,
  int firstCount,
  int secondCount
  ) =>
    result = scratch.scrollValues
    if na(result)
        result := array.new_float()
        scratch.scrollValues := result
    else
        result.clear()
    bandCount = bands.size()
    if bandCount > 0
        lastBand = bandCount - 1
        for bandIndex = 0 to lastBand
            ValueBand band = bands.get(bandIndex)
            array<float> cells = band.values
            rowsHere = band.rowCount
            if rowsHere > 0
                lastRow = rowsHere - 1
                for localRow = 0 to lastRow
                    rowBase = localRow * stride
                    if firstCount > 0
                        result.concat(cells.slice(rowBase + firstStart,
                          rowBase + firstStart + firstCount))
                    if secondCount > 0
                        result.concat(cells.slice(rowBase,
                          rowBase + secondCount))
    result
 
_materializePaletteRuns(
  _CanvasScratch scratch,
  array<PaletteBand> bands,
  int stride,
  int firstStart,
  int firstCount,
  int secondCount
  ) =>
    result = scratch.scrollIndices
    if na(result)
        result := array.new_int()
        scratch.scrollIndices := result
    else
        result.clear()
    bandCount = bands.size()
    if bandCount > 0
        lastBand = bandCount - 1
        for bandIndex = 0 to lastBand
            PaletteBand band = bands.get(bandIndex)
            array<int> cells = band.values
            rowsHere = band.rowCount
            if rowsHere > 0
                lastRow = rowsHere - 1
                for localRow = 0 to lastRow
                    rowBase = localRow * stride
                    if firstCount > 0
                        result.concat(cells.slice(rowBase + firstStart,
                          rowBase + firstStart + firstCount))
                    if secondCount > 0
                        result.concat(cells.slice(rowBase,
                          rowBase + secondCount))
    result
 
_loadTileHalo(
  _CanvasScratch scratch,
  array<int> flatBins,
  _IntPlane bandedBins,
  _TileProgram record,
  int rows,
  int columns
  ) =>
    localRows = record.rowEnd - record.rowStart
    localColumns = record.columnEnd - record.columnStart
    haloRows = localRows + 2
    haloColumns = localColumns + 2
    halo = scratch.largeTileHalo
    if na(halo)
        halo := array.new_int()
        scratch.largeTileHalo := halo
    else
        halo.clear()
    worldOrigin = scratch.worldOrigin
    logicalStart = record.columnStart - 1 - worldOrigin
    logicalEnd = record.columnEnd + 1 - worldOrigin
    sourceStart = logicalStart < 0 ? 0 : logicalStart
    sourceEnd = logicalEnd > columns ? columns : logicalEnd
    leading = sourceStart - logicalStart
    trailing = logicalEnd - sourceEnd
    // Clipped tile bounds require at most one padding cell on either side.
    for haloRow = 0 to haloRows - 1
        globalRow = record.rowStart + haloRow - 1
        if globalRow >= 0 and globalRow < rows
            source = flatBins
            sourceBase = globalRow * columns
            if not na(bandedBins)
                PaletteBand sourceBand = bandedBins.bands.get(
                  int(globalRow / bandedBins.bandRows))
                source := sourceBand.values
                sourceBase := (globalRow - sourceBand.rowStart) * columns
            if leading > 0
                halo.push(-1)
            halo.concat(source.slice(
              sourceBase + sourceStart, sourceBase + sourceEnd))
            if trailing > 0
                halo.push(-1)
        else
            halo.concat(array.new_int(haloColumns, -1))
    if halo.size() != haloRows * haloColumns
        runtime.error("E1")
    haloColumns
 
_compileTileHalo(
  _CanvasScratch scratch,
  _TileProgram record,
  int haloColumns,
  array<int> boundaryCell,
  array<int> boundaryMask,
  bool retainOwnership
  ) =>
    rowStart = record.rowStart
    rowEnd = record.rowEnd
    columnStart = record.columnStart
    columnEnd = record.columnEnd
    localRows = rowEnd - rowStart
    localColumns = columnEnd - columnStart
    localCells = localRows * localColumns
    halo = scratch.largeTileHalo
    boundaryOrder = scratch.boundaryOrder
    localEdges = localCells * 4
    edgeChain = _growIntArray(record.edgeChain, localEdges, -1)
    record.edgeChain := edgeChain
    chainEnd = record.chainEnd
    chainFirstEdge = record.chainFirstEdge
    vertices = record.vertices
    chainExit = record.chainExit
    edgeChain.fill(-1, 0, localEdges)
    boundaryCell.clear()
    boundaryMask.clear()
    chainEnd.clear()
    chainFirstEdge.clear()
    vertices.clear()
    chainExit.clear()
 
    haloMin = halo.min()
    haloMax = halo.max()
    // Skip uniform halos and transparent rows, which contain no exposed edges.
    if haloMin != haloMax
        for localRow = 0 to localRows - 1
            center = (localRow + 1) * haloColumns + 1
            if haloMin < 0 and halo.slice(center, center + localColumns).max() < 0
                continue
            labelCell = localRow * localColumns
            for localColumn = 0 to localColumns - 1
                level = halo.get(center)
                mask = 0
                if level >= 0
                    if halo.get(center - 1) != level
                        mask += 1
                    if halo.get(center + haloColumns) != level
                        mask += 2
                    if halo.get(center + 1) != level
                        mask += 4
                    if halo.get(center - haloColumns) != level
                        mask += 8
                if mask > 0
                    boundaryCell.push(labelCell)
                    boundaryMask.push(mask)
                labelCell += 1
                center += 1
 
    // Trace chains in tile-local coordinates, carrying the selected cell and
    // side. Record backward-prefix vertices for replay in forward order.
    boundaryCount = boundaryCell.size()
    if boundaryCount > 0
        prefixVertices = scratch.prefixVertices
        for boundaryIndex = 0 to boundaryCount - 1
            cell = boundaryCell.get(boundaryIndex)
            // The low bit of the shifted mask is this side's exposure bit.
            mask = boundaryMask.get(boundaryIndex)
            for side = 0 to 3
                firstEdge = cell * 4 + side
                exposed = mask % 2 == 1
                mask := int(mask / 2)
                if exposed
                    if edgeChain.get(firstEdge) < 0
                        chain = chainEnd.size()
                        startRow = int(cell / localColumns)
                        startColumn = cell - startRow * localColumns
                        level = halo.get(
                          (startRow + 1) * haloColumns + startColumn + 1)
                        localRow = startRow
                        localColumn = startColumn
                        edgeSide = side
                        edge = firstEdge
                        boundaryOrder.clear()
                        prefixVertices.clear()
                        prefixComplete = false
                        while not prefixComplete
                            boundaryOrder.push(edge)
                            edgeChain.set(edge, -2)
                            aRow = localRow +
                              (edgeSide == 1 or edgeSide == 2 ? 1 : 0)
                            aColumn = localColumn +
                              (edgeSide == 2 or edgeSide == 3 ? 1 : 0)
                            prefixVertices.push((rowStart + aRow) * WORLD_STRIDE +
                              columnStart + aColumn)
                            quadrant = aRow * haloColumns + aColumn
                            lowerRight = halo.get(quadrant + 1) == level
                            upperRight = halo.get(
                              quadrant + haloColumns + 1) == level
                            upperLeft = halo.get(
                              quadrant + haloColumns) == level
                            lowerLeft = halo.get(quadrant) == level
                            preceding = -1
                            if (lowerRight != upperLeft or
                              upperRight != lowerLeft) and aRow > 0 and
                              aRow < localRows and aColumn > 0 and
                              aColumn < localColumns
                                candidateSide = lowerLeft and not upperLeft ? 1 :
                                  lowerRight and not lowerLeft ? 0 :
                                  upperRight and not lowerRight ? 3 : 2
                                localRow := aRow - (candidateSide <= 1 ? 1 : 0)
                                localColumn := aColumn -
                                  (candidateSide == 1 or candidateSide == 2 ? 1 : 0)
                                edgeSide := candidateSide
                                preceding := (localRow * localColumns +
                                  localColumn) * 4 + candidateSide
                            prefixComplete := preceding < 0 or
                              edgeChain.get(preceding) != -1
                            if not prefixComplete
                                edge := preceding
                            if boundaryOrder.size() > TILE_EDGE_CAPACITY
                                runtime.error("E2")
 
                        chainFirstEdge.push(edge)
                        previousDirection = -1
                        steps = boundaryOrder.size()
                        reverseIndex = steps - 1
                        while reverseIndex >= 0
                            edge := boundaryOrder.get(reverseIndex)
                            edgeSide := edge % 4
                            direction = edgeSide == 0 ? 1 : edgeSide == 1 ? 0 : edgeSide == 2 ? 3 : 2
                            if direction != previousDirection
                                vertices.push(prefixVertices.get(reverseIndex))
                            edgeChain.set(edge, chain)
                            previousDirection := direction
                            reverseIndex -= 1
 
                        localRow := startRow
                        localColumn := startColumn
                        edgeSide := side
                        complete = false
                        while not complete
                            bRow = localRow + (edgeSide <= 1 ? 1 : 0)
                            bColumn = localColumn + (edgeSide == 1 or edgeSide == 2 ? 1 : 0)
                            quadrant = bRow * haloColumns + bColumn
                            lowerRight = halo.get(quadrant + 1) == level
                            upperRight = halo.get(quadrant + haloColumns + 1) == level
                            upperLeft = halo.get(quadrant + haloColumns) == level
                            lowerLeft = halo.get(quadrant) == level
                            following = -1
                            if (lowerRight != upperLeft or
                              upperRight != lowerLeft) and bRow > 0 and
                              bRow < localRows and bColumn > 0 and
                              bColumn < localColumns
                                candidateSide = lowerRight and not upperRight ? 1 :
                                  upperRight and not upperLeft ? 0 :
                                  upperLeft and not lowerLeft ? 3 : 2
                                localRow := bRow - (candidateSide == 1 or candidateSide == 2 ? 1 : 0)
                                localColumn := bColumn - (candidateSide >= 2 ? 1 : 0)
                                edgeSide := candidateSide
                                following := (localRow * localColumns +
                                  localColumn) * 4 + candidateSide
                            complete := following < 0 or edgeChain.get(following) != -1
                            vertex = (rowStart + bRow) * WORLD_STRIDE + columnStart + bColumn
                            if complete
                                vertices.push(vertex)
                                // Cache the first continuation in right, straight, left, back order.
                                // Tile corners require dynamic lookup because diagonal changes do not
                                // recompile this tile.
                                choice = -1
                                if bRow % localRows != 0 or bColumn % localColumns != 0
                                    for priority = 0 to 3
                                        outgoing = (previousDirection + 3 + priority) % 4
                                        if _leaves(lowerRight, upperRight, upperLeft, lowerLeft, outgoing)
                                            choice := outgoing
                                            break
                                chainExit.push(choice)
                            else
                                direction = edgeSide == 0 ? 1 : edgeSide == 1 ? 0 : edgeSide == 2 ? 3 : 2
                                if direction != previousDirection
                                    vertices.push(vertex)
                                edgeChain.set(following, chain)
                                previousDirection := direction
                                steps += 1
                            if steps > TILE_EDGE_CAPACITY
                                runtime.error("E2")
                        chainEnd.push(vertices.size())
    if retainOwnership
        _compileTileOwnership(
          halo, haloColumns, localRows, localColumns,
          haloMin == haloMax ? haloMin : -2,
          record.boundaryCell, record.boundaryMask)
    0
 
_compileTile(
  _CanvasScratch scratch,
  _TileProgram record,
  array<int> bins,
  int rows,
  int columns
  ) =>
    haloColumns = _loadTileHalo(
      scratch, bins, na, record, rows, columns)
    _compileTileHalo(
      scratch, record, haloColumns,
      record.boundaryCell, record.boundaryMask, false)
 
_compileTileLarge(
  _CanvasScratch scratch,
  _TileProgram record,
  _IntPlane bins,
  int rows,
  int columns
  ) =>
    haloColumns = _loadTileHalo(
      scratch, na, bins, record, rows, columns)
    // Retain local ownership in the tile record; boundary discovery is temporary.
    _compileTileHalo(
      scratch, record, haloColumns,
      scratch.candidateSameTiles, scratch.candidateShiftTiles, true)
 
_countComponents(
  _CanvasScratch scratch,
  array<int> bins,
  int rows,
  int columns
  ) =>
    cells = rows * columns
    scratch.componentParent := _growIntArray(
      scratch.componentParent, cells, -1)
    parents = scratch.componentParent
    // Label 8-connected components with their smallest cell as root.
    // The dry trace records the component count.
    cell = 0
    for row = 0 to rows - 1
        hasBelow = row > 0
        previousRoot = -1
        for column = 0 to columns - 1
            level = bins.get(cell)
            if level >= 0
                below = cell - columns
                belowSame = hasBelow and bins.get(below) == level
                root = -1
                if column > 0 and bins.get(cell - 1) == level
                    root := previousRoot
                else if belowSame
                    root := _findRoot(parents, below)
                else if hasBelow and column > 0 and bins.get(below - 1) == level
                    root := _mergeRoot(parents, root, below - 1)
                if not belowSame and hasBelow and column < columns - 1 and
                  bins.get(below + 1) == level
                    root := _mergeRoot(parents, root, below + 1)
                previousRoot := root < 0 ? cell : root
                parents.set(cell, previousRoot)
            else
                parents.set(cell, -1)
            cell += 1
    0
 
// Retrace all anchors except the last, where the current path already ends.
_finishConnectorChain(array<int> vertices, array<int> anchors) =>
    if anchors.size() > 1
        anchors.pop()
        anchors.reverse()
        vertices.concat(anchors)
    0
 
// ----------------------------------------------------------------------------
// Chains: one colour's loops joined into polylines
// ----------------------------------------------------------------------------
//
// Zero-area connectors retrace the same vertices in reverse. Grid-aligned
// links reduce rasterization artifacts from sloped overlapping edges.
// Sort loops by their first corner so loops on the same row share a link.
 
// Initialize chain storage for an emission of the given field height.
_beginChains(_CanvasScratch scratch, int rows) =>
    if na(scratch.points)
        scratch.points := array.new<chart.point>()
    if na(scratch.railKeys)
        scratch.railKeys := array.new_int()
        scratch.railStarts := array.new_int()
        scratch.linked := array.new_int()
    scratch.anchors := _growIntArray(scratch.anchors, 0)
    scratch.chunkVertices := _growIntArray(scratch.chunkVertices, 0)
    scratch.railStamps := _growIntArray(scratch.railStamps, rows + 1)
    scratch.chunkVertices.clear()
    scratch.railKeys.clear()
    scratch.railStarts.clear()
    scratch.railSerial += 1
    scratch.railCount := 0
    scratch.overflowDrawings := 0
    0
 
// Packers stage closed loops with sort keys and starting-row stamps.
 
// Join staged loops in sorted order. Grid links use a straight axis-aligned
// segment or a two-segment elbow, with a simplified return path. Reserve
// at most four connector points per starting row. Straight links are used
// as a fallback when one component exceeds the grid-link point bound.
_linkChain(_CanvasScratch scratch, bool grid) =>
    staged = scratch.chunkVertices
    starts = scratch.railStarts
    walk = scratch.anchors
    linked = scratch.linked
    linked.clear()
    walk.clear()
    // Return-path heading: 0 unset, 1 right, 2 up, 3 left. Sorted anchors
    // never decrease in row or, within one row, in column.
    heading = 0
    previous = 0
    for key in scratch.railKeys
        index = key % RAIL_SPAN
        loopFrom = starts.get(index)
        first = staged.get(loopFrom)
        last = walk.size() - 1
        if last < 0 or not grid
            walk.push(first)
        else if first != previous
            column = previous % WORLD_STRIDE
            if first - previous + column < WORLD_STRIDE
                // Join anchors on the same row directly.
                if heading == 1
                    walk.set(last, first)
                else
                    walk.push(first)
                    heading := 1
            else
                // Move vertically to the next row, then horizontally if needed.
                elbow = first - first % WORLD_STRIDE + column
                if heading == 2
                    walk.set(last, elbow)
                else
                    walk.push(elbow)
                    heading := 2
                if elbow != first
                    linked.push(elbow)
                    walk.push(first)
                    heading := first > elbow ? 1 : 3
        previous := first
        linked.concat(staged.slice(loopFrom, starts.get(index + 1)))
    _finishConnectorChain(linked, walk)
    linked
 
_gradientColor(array<color> gradient, float fraction) =>
    gradientCount = gradient.size()
    position = _clamp(fraction, 0.0, 1.0) * (gradientCount - 1)
    lowerIndex = int(math.floor(position))
    upperIndex = int(math.min(gradientCount - 1, lowerIndex + 1))
    color.from_gradient(
      position - lowerIndex, 0.0, 1.0,
      gradient.get(lowerIndex), gradient.get(upperIndex))
 
_withOpacity(color base, float opacity) =>
    sourceOpacity = 100.0 - color.t(base)
    combinedOpacity = sourceOpacity *
      _clamp(opacity, 0.0, 100.0) / 100.0
    color.new(base, 100.0 - combinedOpacity)
 
// Join and emit the staged loops. Count drawings beyond the budget
// without creating them; _requireDrawingRoom reports the total required.
_emitWorldChain(Canvas canvas, int level, _Frame frame) =>
    _CanvasScratch scratch = canvas._scratch
    staged = scratch.chunkVertices
    if staged.size() > 0
        scratch.railStarts.push(staged.size())
        scratch.railKeys.sort(order.ascending)
        vertices = _linkChain(scratch, true)
        // A single component can exceed the grid-link bound while still fitting
        // with straight links. Its dry trace provides the exact fallback count.
        if vertices.size() > MAX_POINTS
            vertices := _linkChain(scratch, false)
        if vertices.size() > MAX_POINTS
            runtime.error("E14")
        Style style = frame.style
        if canvas.drawings.size() >= style.drawingLimit
            scratch.overflowDrawings += 1
        else
            points = scratch.points
            points.clear()
            worldOrigin = scratch.worldOrigin
            invertRows = style.invertRows
            rows = frame.rows
            xEdges = frame.xEdges
            yEdges = frame.yEdges
            timeCoordinates = frame.timeCoordinates
            for vertex in vertices
                row = int(vertex / WORLD_STRIDE)
                column = vertex % WORLD_STRIDE - worldOrigin
                yIndex = invertRows ? rows - row : row
                x = xEdges.get(column)
                y = yEdges.get(yIndex)
                points.push(timeCoordinates ?
                  chart.point.from_time(x, y) : chart.point.from_index(x, y))
            fraction = level / (style.colorLevels - 1.0)
            opacity = style.lowOpacity +
              (style.highOpacity - style.lowOpacity) * fraction
            base = frame.indexed ? frame.gradient.get(level) :
              _gradientColor(frame.gradient, fraction)
            fillColor = _withOpacity(base, opacity)
            canvas.drawings.push(_newFilledPolyline(
              points,
              fillColor,
              timeCoordinates,
              style.forceOverlay))
        staged.clear()
        scratch.railKeys.clear()
        scratch.railStarts.clear()
        scratch.railSerial += 1
        scratch.railCount := 0
    0
 
// Reject an emission that required more drawings than the Canvas budget.
_requireDrawingRoom(_CanvasScratch scratch, Style style) =>
    if scratch.overflowDrawings > 0
        runtime.error(
          "need " +
          str.tostring(style.drawingLimit + scratch.overflowDrawings) +
          " drawings, above this Canvas's drawingLimit.")
    0
 
// Count visible components and validate their point bounds. Reuse cached
// counts until topology changes.
_planFlatDrawings(_CanvasScratch scratch, Style style) =>
    visibleUnits = 0
    activeLevel = -1
    visible = false
    for [unit, points] in scratch.flatUnitPoints
        level = scratch.flatUnitLevels.get(unit)
        if level != activeLevel
            activeLevel := level
            visible := style.lowOpacity +
              (style.highOpacity - style.lowOpacity) *
              (level / (style.colorLevels - 1.0)) > 0
        if visible
            if points > MAX_POINTS
                runtime.error("complete component >10000 points")
            visibleUnits += 1
    visibleUnits
 
_emitChainPrograms(
  Canvas canvas,
  array<int> bins,
  _Frame frame,
  int dirtyTileCount,
  bool countOnly = false
  ) =>
    _CanvasScratch scratch = canvas._scratch
    Style style = frame.style
    rows = frame.rows
    columns = frame.columns
    if na(scratch.componentOrder)
        scratch.componentOrder := array.new_int()
    if na(scratch.corners)
        scratch.corners := array.new_int()
 
    if na(scratch.flatUnitPoints)
        scratch.flatUnitPoints := array.new_int()
        scratch.flatUnitFit := array.new_int()
        scratch.flatUnitLevels := array.new_int()
    if countOnly
        scratch.flatUnitPoints.clear()
        scratch.flatUnitFit.clear()
        scratch.flatUnitLevels.clear()
    // Use a separate row-stamp serial for each component during the dry trace.
    _beginChains(scratch, rows)
    railKeys = scratch.railKeys
    railStarts = scratch.railStarts
    stamps = scratch.railStamps
    countSerial = scratch.railSerial
    unitPoints = scratch.flatUnitPoints
    unitFit = scratch.flatUnitFit
    unitIndex = -1
    priorUnitPayload = -1
    cells = rows * columns
    worldOrigin = scratch.worldOrigin
    worldEnd = worldOrigin + columns
    drawingLimit = style.drawingLimit
    tilePrograms = scratch.tilePrograms
    chainKeys = scratch.componentOrder
    corners = scratch.corners
    staged = scratch.chunkVertices
    chainOrderSpan = cells
    // These arrays remain valid until the next frame initialization.
    activeSlots = scratch.activeTileSlots
    componentParents = scratch.componentParent
    // A chain is consumed when its state equals this walk's stamp.
    stamp = scratch.chainStamp + 1
    scratch.chainStamp := stamp
 
    // Tile seams and ambiguous vertices terminate chains. Sort chain starts
    // and consume each chain once. dirtyCount was captured before compilation.
    rebuildOrder = dirtyTileCount > 0 or
      chainKeys.size() == 0
    if rebuildOrder
        chainKeys.clear()
 
    for slot in activeSlots
        _TileProgram record = tilePrograms.get(slot)
        localChainCount = record.chainEnd.size()
        if localChainCount > 0
            record.chainState := _growIntArray(
              record.chainState, localChainCount, -1)
            if rebuildOrder
                if chainKeys.size() + localChainCount > MAX_CELLS
                    runtime.error(
                      "ambiguous chains exceed 100000")
                int localColumns =
                  record.columnEnd - record.columnStart
                for localChain = 0 to localChainCount - 1
                    int firstEdge =
                      record.chainFirstEdge.get(localChain)
                    localCell = int(firstEdge / 4)
                    localRow = int(localCell / localColumns)
                    int localColumn =
                      localCell - localRow * localColumns
                    row = record.rowStart + localRow
                    int worldColumn =
                      record.columnStart + localColumn
                    cell = row * columns +
                      worldColumn - worldOrigin
                    level = bins.get(cell)
                    // Emit components in ascending root order to keep grid links short.
                    int reference =
                      slot * TILE_EDGE_CAPACITY + localChain
                    chainKeys.push(
                      (level * chainOrderSpan +
                      _findRoot(componentParents, cell)) *
                      CHAIN_REFERENCE_BASE + reference)
    if rebuildOrder
        chainKeys.sort(order.ascending)
 
    // Give each visible component its own drawing when the budget permits.
    roomForAll = scratch.flatVisibleUnits <= drawingLimit
    activeLevel = -1
    activeOpacity = 0.0
    packedComponentRank = -1
 
    for encoded in chainKeys
        orderPayload = int(encoded / CHAIN_REFERENCE_BASE)
        level = int(orderPayload / chainOrderSpan)
        componentRank = orderPayload % chainOrderSpan
        if orderPayload != priorUnitPayload
            unitIndex += 1
            priorUnitPayload := orderPayload
            if countOnly
                unitPoints.push(0)
                unitFit.push(0)
                scratch.flatUnitLevels.push(level)
                countSerial += 1
        if level != activeLevel
            if not countOnly and activeLevel >= 0
                _emitWorldChain(canvas, activeLevel, frame)
            activeLevel := level
            fraction = level / (style.colorLevels - 1.0)
            activeOpacity := style.lowOpacity +
              (style.highOpacity - style.lowOpacity) * fraction
            packedComponentRank := -1
 
        reference = encoded % CHAIN_REFERENCE_BASE
        seedSlot = int(reference / TILE_EDGE_CAPACITY)
        seedLocalChain = reference % TILE_EDGE_CAPACITY
        _TileProgram seedRecord = tilePrograms.get(seedSlot)
        if (countOnly or activeOpacity > 0) and
          seedRecord.chainState.get(seedLocalChain) != stamp
            corners.clear()
            seedFrom = seedLocalChain > 0 ?
              seedRecord.chainEnd.get(seedLocalChain - 1) : 0
            seedVertex = seedRecord.vertices.get(seedFrom)
            firstDirection = -1
            previousDirection = -1
            endVertex = seedVertex
            currentReference = reference
            chainSteps = 0
 
            while true
                slot = int(
                  currentReference / TILE_EDGE_CAPACITY)
                int localChain =
                  currentReference % TILE_EDGE_CAPACITY
                _TileProgram record = tilePrograms.get(slot)
                record.chainState.set(localChain, stamp)
                fromIndex = localChain > 0 ?
                  record.chainEnd.get(localChain - 1) : 0
                toIndex = record.chainEnd.get(localChain)
                source = record.vertices
                // Cached chains contain turning vertices only. Test the first vertex for
                // collinearity with the preceding chain, then append the interior directly.
                head = source.get(fromIndex)
                direction = _axisDirection(source.get(fromIndex + 1) - head)
                if firstDirection < 0
                    firstDirection := direction
                    corners.push(head)
                else if direction != previousDirection
                    corners.push(head)
                previousDirection := direction
                endVertex := source.get(toIndex - 1)
                if toIndex - fromIndex > 2
                    corners.concat(source.slice(fromIndex + 1, toIndex - 1))
                    previousDirection := _axisDirection(
                      endVertex - source.get(toIndex - 2))
 
                chainSteps += 1
                if endVertex == seedVertex
                    break
                vertexRow = int(endVertex / WORLD_STRIDE)
                vertexColumn = endVertex % WORLD_STRIDE
                // Use the cached first-choice continuation only if it is unconsumed.
                recorded = record.chainExit.get(localChain)
                nextReference = recorded < 0 ? -1 :
                  _junctionChain(scratch, vertexRow, vertexColumn, recorded, stamp)
                if nextReference < 0
                    lowerRight = vertexRow > 0 and
                      vertexColumn < worldEnd and
                      bins.get((vertexRow - 1) * columns +
                      vertexColumn - worldOrigin) == level
                    upperRight = vertexRow < rows and
                      vertexColumn < worldEnd and
                      bins.get(vertexRow * columns +
                      vertexColumn - worldOrigin) == level
                    upperLeft = vertexRow < rows and
                      vertexColumn > worldOrigin and
                      bins.get(vertexRow * columns +
                      vertexColumn - 1 - worldOrigin) == level
                    lowerLeft = vertexRow > 0 and
                      vertexColumn > worldOrigin and
                      bins.get((vertexRow - 1) * columns +
                      vertexColumn - 1 - worldOrigin) == level
                    for priority = 0 to 3
                        outgoing = (previousDirection + 3 + priority) % 4
                        if _leaves(lowerRight, upperRight, upperLeft, lowerLeft, outgoing)
                            nextReference := _junctionChain(scratch,
                              vertexRow, vertexColumn, outgoing, stamp)
                            if nextReference >= 0
                                break
                if nextReference < 0
                    runtime.error("E6")
                currentReference := nextReference
                if chainSteps > cells * 4 + 1
                    runtime.error("E7")
 
            int cornerOffset =
              firstDirection == previousDirection ? 1 : 0
            storedCornerCount = corners.size()
            cornerCount = storedCornerCount - cornerOffset
            if cornerCount < 3
                runtime.error("E8")
            if countOnly
                accumulated = unitPoints.get(unitIndex)
                unitPoints.set(unitIndex,
                  accumulated + cornerCount + (accumulated > 0 ? 2 : 1))
                // Reserve closed loops plus four link points per distinct starting row.
                loopRoom = cornerCount + 1
                countRow = int(corners.get(cornerOffset) / WORLD_STRIDE)
                if stamps.get(countRow) != countSerial
                    stamps.set(countRow, countSerial)
                    loopRoom += 4
                unitFit.set(unitIndex, unitFit.get(unitIndex) + loopRoom)
            else
                // Reserve the complete component before staging any loop; keep holes
                // with their enclosing contour.
                if packedComponentRank >= 0 and
                  componentRank != packedComponentRank and (roomForAll or
                  staged.size() + 4 * scratch.railCount + unitFit.get(unitIndex) >
                  MAX_POINTS + 3)
                    _emitWorldChain(canvas, level, frame)
 
                // Repeat the first corner to close the staged loop.
                firstVertex = corners.get(cornerOffset)
                railKeys.push(firstVertex * RAIL_SPAN + railStarts.size())
                railStarts.push(staged.size())
                stampRow = int(firstVertex / WORLD_STRIDE)
                if stamps.get(stampRow) != scratch.railSerial
                    stamps.set(stampRow, scratch.railSerial)
                    scratch.railCount += 1
                staged.concat(corners.slice(cornerOffset, storedCornerCount))
                staged.push(firstVertex)
                packedComponentRank := componentRank
 
    if countOnly
        // Start emission with a fresh row-stamp serial.
        scratch.railSerial := countSerial
    else
        if activeLevel >= 0
            _emitWorldChain(canvas, activeLevel, frame)
        _requireDrawingRoom(scratch, style)
    canvas.drawings.size()
 
_renderFlat(
  Canvas canvas,
  array<float> values,
  array<int> xEdges,
  array<float> yEdges,
  array<color> gradient,
  Style requestedStyle,
  bool timeCoordinates,
  bool generatedCoordinates = false,
  array<int> indices = na,
  int producerOrigin = na
  ) =>
    if na(canvas)
        runtime.error("Canvas is na; use newCanvas()")
    indexed = not na(indices)
    if not indexed and na(values)
        runtime.error("values is na")
    if na(xEdges) or na(yEdges)
        runtime.error("edge arrays are na")
    _validatePalette(gradient)
 
    _CanvasScratch scratch = _ensureScratch(canvas)
    // Initialize drawing storage before validation and frame-cache checks.
    if na(canvas.drawings)
        canvas.drawings := array.new<polyline>()
    Style style = _styleOrDefault(requestedStyle)
    _validateStyle(style)
    _validateCoordinateMode(
      xEdges, yEdges, timeCoordinates, generatedCoordinates)
 
    columns = xEdges.size() - 1
    rows = yEdges.size() - 1
    cells = rows * columns
 
    if cells > MAX_CELLS
        runtime.error("flat field >100000 cells")
    if indexed
        if indices.size() != cells
            runtime.error("index count must be rows*columns")
    else if values.size() != cells
        runtime.error("value count must be rows*columns")
    if not indexed and style.colorLevels > cells
        runtime.error("colorLevels exceeds cell count")
 
    producerBacked = not na(producerOrigin)
    currentWorldOrigin = producerBacked ?
      producerOrigin : scratch.worldOrigin
    if not producerBacked and
      (scratch.lastRows < 0 or scratch.hasProducerOrigin)
        currentWorldOrigin := GENERIC_WORLD_ORIGIN
    // Before swapping, bins contains the preceding frame and lastBins is
    // the older reusable buffer.
    previousColumns = scratch.lastColumns
    sameColumns = columns == previousColumns
    // A previous large render leaves stale flat buffers. Compare flat bins
    // only when the preceding frame also used this renderer.
    binComparable = not scratch.lastLargeField and
      rows == scratch.lastRows and
      (sameColumns or producerBacked) and previousColumns >= 2 and
      producerBacked == scratch.hasProducerOrigin and
      not na(scratch.bins) and
      scratch.bins.size() >= rows * previousColumns
    detectedShift = 0
    if binComparable and not producerBacked
        detectedShift := _horizontalEdgeShift(
          xEdges, scratch.lastXEdges, columns)
        currentWorldOrigin += detectedShift
    originShift = binComparable ?
      currentWorldOrigin - scratch.lastWorldOrigin : 0
    if binComparable
        // Current column c corresponds to previous column c + originShift.
        binComparable := originShift < previousColumns and
          originShift + columns > 0
    sameBinLayout = binComparable and sameColumns and originShift == 0
    // Compare unchanged logical bins and coordinate-shifted bins before
    // updating the tile directory. tileRoots temporarily stores shifted changes.
    deferredTranslation = binComparable and
      not producerBacked and detectedShift != 0
    if deferredTranslation
        scratch.tileRoots.clear()
    // Reuse the active tile directory when viewport bounds are unchanged.
    tileDirectoryStable = scratch.lastRows >= 0 and
      rows == scratch.lastRows and columns == scratch.lastColumns and
      currentWorldOrigin == scratch.worldOrigin and
      not na(scratch.activeTileSlots)
    if not deferredTranslation
        if tileDirectoryStable
            scratch.tileGeneration += 1
            scratch.dirtyTileSlots.clear()
        else
            _prepareTileDirectory(scratch, rows, columns, currentWorldOrigin)
    scratch.dirtyCellCount := 0
    if not binComparable
        for slot in scratch.activeTileSlots
            _markTileSlotDirty(scratch, slot)
        scratch.dirtyCellCount := cells
 
    // Calculate value ranges before quantization. Palette indices bypass scaling.
    groupedScale = not indexed and style.autoScale and style.scaleMode != ScaleMode.wholeGrid
    scaleColumns = style.scaleMode == ScaleMode.eachColumn
    scaleGroupCount = scaleColumns ? columns : rows
    scaleMin = indexed ? 0.0 : style.autoScale ? na : style.valueMin
    scaleMax = indexed ? style.colorLevels - 1.0 : style.autoScale ? na : style.valueMax
    foundValues = indexed ? false : not style.autoScale
 
    if groupedScale
        scratch.groupMin := _growFloatArray(scratch.groupMin, scaleGroupCount)
        scratch.groupMax := _growFloatArray(scratch.groupMax, scaleGroupCount)
        scratch.groupMin.fill(na, 0, scaleGroupCount)
        scratch.groupMax.fill(na, 0, scaleGroupCount)
 
    // Swap buffers to retain the preceding frame without copying. Every
    // quantization path overwrites all cells in the destination buffer.
    recycledBins = scratch.lastBins
    scratch.lastBins := scratch.bins
    scratch.bins := _growIntArray(recycledBins, cells, -1)
    bins = scratch.bins
    lastBins = scratch.lastBins
    if indexed
        // Validate palette bounds with native reductions, which ignore na.
        lowestIndex = indices.min()
        highestIndex = indices.max()
        if lowestIndex < -1 or highestIndex >= style.colorLevels
            runtime.error(
              "index must be -1 or 0.." +
              str.tostring(style.colorLevels - 1) + ".")
        foundValues := highestIndex >= 0
        for [i, index] in indices
            // Convert na indices to -1 so neighbor comparisons and contour tracing
            // use one transparent sentinel.
            level = nz(index, -1)
            bins.set(i, level)
            if binComparable
                if sameBinLayout
                    if lastBins.get(i) != level
                        row = int(i / columns)
                        column = i - row * columns
                        scratch.dirtyCellCount += 1
                        _markTileDirtyAt(scratch, row, column)
                else
                    row = int(i / columns)
                    column = i - row * columns
                    oldColumn = column + originShift
                    changed = oldColumn < 0 or
                      oldColumn >= previousColumns
                    if not changed
                        oldCell = row * previousColumns + oldColumn
                        changed := lastBins.get(oldCell) != level
                    if changed
                        scratch.dirtyCellCount += 1
                        if deferredTranslation
                            scratch.tileRoots.push(i)
                        else
                            _markTileDirtyAt(scratch, row, column)
    else if style.autoScale
        // Native extrema ignore na and return na for an all-na grid.
        scaleMin := values.min()
        scaleMax := values.max()
        foundValues := not na(scaleMax)
        if groupedScale
            if scaleColumns
                // Use matrix columns for native per-column extrema; na values are ignored.
                grid = matrix.new<float>()
                grid.add_row(0, values)
                grid.reshape(rows, columns)
                for column = 0 to columns - 1
                    columnValues = grid.col(column)
                    scratch.groupMin.set(column, columnValues.min())
                    scratch.groupMax.set(column, columnValues.max())
            else
                cell = 0
                for row = 0 to rows - 1
                    [localMin, localMax] = _nativeRowExtrema(values, cell, columns)
                    cell += columns
                    scratch.groupMin.set(row, localMin)
                    scratch.groupMax.set(row, localMax)
 
    // Quantize before replacing drawings so identical and empty frames can
    // reuse the cache. Keep division and gamma evaluation unchanged; reciprocal
    // multiplication can move values across quantization boundaries.
    if not indexed
        maxBin = style.colorLevels - 1
        levelSpan = style.colorLevels
        gammaExponent = style.gamma
        unitGamma = math.sign(gammaExponent - 1.0) == 0
        if not groupedScale
            localMin = scaleMin
            localMax = scaleMax
            constantScale = localMax <= localMin
            scaleSpan = localMax - localMin
            if sameBinLayout
                for [i, value] in values
                    bin = -1
                    if not na(value)
                        normalized = constantScale ? 1.0 :
                          math.max(0.0, math.min(
                            1.0, (value - localMin) / scaleSpan))
                        curved = unitGamma ? normalized :
                          math.pow(normalized, gammaExponent)
                        bin := int(math.min(maxBin, math.floor(curved * levelSpan)))
                    bins.set(i, bin)
                    if binComparable
                        if lastBins.get(i) != bin
                            row = int(i / columns)
                            column = i - row * columns
                            scratch.dirtyCellCount += 1
                            _markTileDirtyAt(scratch, row, column)
            else
                cell = 0
                for row = 0 to rows - 1
                    for column = 0 to columns - 1
                        value = values.get(cell)
                        bin = -1
                        if not na(value)
                            normalized = constantScale ? 1.0 :
                              math.max(0.0, math.min(
                                1.0, (value - localMin) / scaleSpan))
                            curved = unitGamma ? normalized :
                              math.pow(normalized, gammaExponent)
                            bin := int(math.min(maxBin,
                              math.floor(curved * levelSpan)))
                        bins.set(cell, bin)
                        if binComparable
                            oldColumn = column + originShift
                            changed = oldColumn < 0 or
                              oldColumn >= previousColumns
                            if not changed
                                oldCell = row * previousColumns + oldColumn
                                changed := lastBins.get(oldCell) != bin
                            if changed
                                scratch.dirtyCellCount += 1
                                if deferredTranslation
                                    scratch.tileRoots.push(cell)
                                else
                                    _markTileDirtyAt(scratch, row, column)
                        cell += 1
        else if scaleColumns
            groupMin = scratch.groupMin
            groupMax = scratch.groupMax
            cell = 0
            for row = 0 to rows - 1
                for column = 0 to columns - 1
                    value = values.get(cell)
                    bin = -1
                    if not na(value)
                        localMin = groupMin.get(column)
                        localMax = groupMax.get(column)
                        normalized = localMax <= localMin ? 1.0 :
                          math.max(0.0, math.min(
                            1.0,
                            (value - localMin) / (localMax - localMin)))
                        curved = unitGamma ? normalized :
                          math.pow(normalized, gammaExponent)
                        bin := int(math.min(maxBin, math.floor(curved * levelSpan)))
                    bins.set(cell, bin)
                    if binComparable
                        oldColumn = column + originShift
                        changed = oldColumn < 0 or
                          oldColumn >= previousColumns
                        if not changed
                            oldCell = row * previousColumns + oldColumn
                            changed := lastBins.get(oldCell) != bin
                        if changed
                            scratch.dirtyCellCount += 1
                            if deferredTranslation
                                scratch.tileRoots.push(cell)
                            else
                                _markTileDirtyAt(scratch, row, column)
                    cell += 1
        else
            cell = 0
            for row = 0 to rows - 1
                localMin = scratch.groupMin.get(row)
                localMax = scratch.groupMax.get(row)
                constantScale = localMax <= localMin
                scaleSpan = localMax - localMin
                for column = 0 to columns - 1
                    value = values.get(cell)
                    bin = -1
                    if not na(value)
                        normalized = constantScale ? 1.0 :
                          math.max(0.0, math.min(
                            1.0, (value - localMin) / scaleSpan))
                        curved = unitGamma ? normalized :
                          math.pow(normalized, gammaExponent)
                        bin := int(math.min(maxBin, math.floor(curved * levelSpan)))
                    bins.set(cell, bin)
                    if binComparable
                        oldColumn = column + originShift
                        changed = oldColumn < 0 or
                          oldColumn >= previousColumns
                        if not changed
                            oldCell = row * previousColumns + oldColumn
                            changed := lastBins.get(oldCell) != bin
                        if changed
                            scratch.dirtyCellCount += 1
                            if deferredTranslation
                                scratch.tileRoots.push(cell)
                            else
                                _markTileDirtyAt(scratch, row, column)
                    cell += 1
 
    if deferredTranslation
        // Choose the alignment with fewer changed cells. Ties retain the existing
        // tile directory.
        if na(scratch.gapComponents)
            scratch.gapComponents := array.new_int()
        else
            scratch.gapComponents.clear()
        sameLogicalChanges = 0
        for cell = 0 to cells - 1
            if bins.get(cell) != lastBins.get(cell)
                sameLogicalChanges += 1
                scratch.gapComponents.push(cell)
                if sameLogicalChanges > scratch.dirtyCellCount
                    break
        if sameLogicalChanges <= scratch.dirtyCellCount
            currentWorldOrigin := scratch.worldOrigin
            originShift := 0
            scratch.dirtyCellCount := sameLogicalChanges
            scratch.tileGeneration += 1
            scratch.dirtyTileSlots.clear()
            for changedCell in scratch.gapComponents
                changedRow = int(changedCell / columns)
                changedColumn = changedCell - changedRow * columns
                _markTileDirtyAt(
                  scratch, changedRow, changedColumn)
        else
            _prepareTileDirectory(
              scratch, rows, columns, currentWorldOrigin)
            for changedCell in scratch.tileRoots
                changedRow = int(changedCell / columns)
                changedColumn = changedCell - changedRow * columns
                _markTileDirtyAt(
                  scratch, changedRow, changedColumn)
 
    // Normalization inputs are represented by the quantized bins. Opacity,
    // palette, coordinates, and drawing budget also affect frame identity.
    _Frame frame = _Frame.new(
      xEdges, yEdges, gradient, style, indexed, timeCoordinates, rows, columns)
    styleKey = _renderStyleKey(frame)
 
    // Dirty cells were counted while writing the quantized bins.
    binsEqual = binComparable and scratch.dirtyCellCount == 0
 
    // Invalidate cached contour programs only when quantized cells change.
    cacheHit = scratch.lastDrawCount >= 0 and binsEqual
    scratch.lastLargeField := false
    if cacheHit
        // Refuse the skip if a caller changed this Canvas's public drawings.
        cacheHit := _sameFrameIdentity(canvas, scratch, frame, styleKey)
 
    if cacheHit
        // Retain existing drawings and refresh reported metadata.
        _commitFrame(
          canvas, scratch, frame, foundValues, scaleMin, scaleMax,
          currentWorldOrigin, producerBacked)
    else if not foundValues
        _clearDrawings(canvas)
        // Replace stale tile programs with empty records before caching an empty frame.
        for slot in scratch.dirtyTileSlots
            _TileProgram record = scratch.tilePrograms.get(slot)
            record.boundaryCell.clear()
            record.boundaryMask.clear()
            record.chainEnd.clear()
            record.chainFirstEdge.clear()
            record.vertices.clear()
        scratch.lastComponentCount := 0
        _commitFrame(
          canvas, scratch, frame, false, scaleMin, scaleMax,
          currentWorldOrigin, producerBacked)
        _storeFrameIdentity(scratch, frame, styleKey, 0)
        0
    else
        dirtySlots = scratch.dirtyTileSlots
        dirtyTileCount = dirtySlots.size()
        for slot in dirtySlots
            _compileTile(
              scratch, scratch.tilePrograms.get(slot),
              scratch.bins, rows, columns)
        // Reuse topology and component counts when only placement or styling changes.
        if dirtyTileCount > 0 or na(scratch.flatUnitPoints)
            _countComponents(scratch, scratch.bins, rows, columns)
            // Use the emission walker for exact component point counts.
            _emitChainPrograms(canvas, scratch.bins, frame, dirtyTileCount, true)
            scratch.lastComponentCount := scratch.flatUnitPoints.size()
        scratch.flatVisibleUnits := _planFlatDrawings(scratch, style)
        _clearDrawings(canvas)
        _emitChainPrograms(canvas, scratch.bins, frame, 0)
        _commitFrame(
          canvas, scratch, frame, true, scaleMin, scaleMax,
          currentWorldOrigin, producerBacked)
        _storeFrameIdentity(scratch, frame, styleKey, canvas.drawings.size())
        canvas.drawings.size()
 
_prepareLargeCandidates(_CanvasScratch scratch, int tileCount) =>
    scratch.candidateSameTileStamp := _growIntArray(
      scratch.candidateSameTileStamp, tileCount, -1)
    scratch.candidateShiftTileStamp := _growIntArray(
      scratch.candidateShiftTileStamp, tileCount, -1)
    if na(scratch.candidateSameTiles)
        scratch.candidateSameTiles := array.new_int()
        scratch.candidateShiftTiles := array.new_int()
    else
        scratch.candidateSameTiles.clear()
        scratch.candidateShiftTiles.clear()
    scratch.candidateGeneration += 1
    0
 
_markLargeCandidate(
  array<int> stamps,
  array<int> tiles,
  int generation,
  int tileIndex
  ) =>
    if stamps.get(tileIndex) != generation
        stamps.set(tileIndex, generation)
        tiles.push(tileIndex)
    0
 
_applyLargeCandidates(
  _CanvasScratch scratch,
  bool keepLogical,
  int columns
  ) =>
    selected = keepLogical ?
      scratch.candidateSameTiles : scratch.candidateShiftTiles
    logicalTileColumns = int((columns + TILE_SIZE - 1) / TILE_SIZE)
    activeTileColumns = scratch.activeTileColumns
    slots = scratch.activeTileSlots
    for tileIndex in selected
        tileRow = int(tileIndex / logicalTileColumns)
        logicalTileColumn = tileIndex - tileRow * logicalTileColumns
        logicalStart = logicalTileColumn * TILE_SIZE
        logicalEnd = math.min(columns, logicalStart + TILE_SIZE) - 1
        firstActiveColumn = int(
          (scratch.worldOrigin + logicalStart) / TILE_SIZE) -
          scratch.firstWorldTileColumn
        lastActiveColumn = int(
          (scratch.worldOrigin + logicalEnd) / TILE_SIZE) -
          scratch.firstWorldTileColumn
        // Include orthogonal tile neighbors for shared-edge invalidation. A shifted
        // logical tile can overlap two cached world tiles.
        for activeColumn = firstActiveColumn to lastActiveColumn
            activeIndex = tileRow * activeTileColumns + activeColumn
            _markTileSlotDirty(scratch, slots.get(activeIndex))
            if activeColumn > 0
                _markTileSlotDirty(scratch, slots.get(activeIndex - 1))
            if activeColumn < activeTileColumns - 1
                _markTileSlotDirty(scratch, slots.get(activeIndex + 1))
            if tileRow > 0
                _markTileSlotDirty(scratch, slots.get(activeIndex - activeTileColumns))
            if activeIndex + activeTileColumns < slots.size()
                _markTileSlotDirty(scratch, slots.get(activeIndex + activeTileColumns))
    0
 
_swapLargeBins(_CanvasScratch scratch, int rows, int columns) =>
    _IntPlane retired = scratch.largeLastBins
    scratch.largeLastBins := scratch.largeBins
    scratch.largeBins := retired
    scratch.largeBins := _ensureIntPlaneLayout(
      scratch.largeBins, rows, columns, -1, false)
    0
 
// ============================================================================
// LARGE QUANTIZATION
// ============================================================================
//
// Fixed and rolling sources supply storage bands, row stride, and one or
// two chronological runs. Traverse destination rows in order and resolve
// band aliases and scaling modes outside the cell loop.
 
// True when one physical run per row already matches the logical layout.
_contiguousRuns(int stride, int columns, int firstStart, int secondCount) =>
    stride == columns and firstStart == 0 and secondCount == 0
 
_quantizeLargePaletteRuns(
  _CanvasScratch scratch,
  array<PaletteBand> bands,
  int bandHeight,
  int stride,
  int columns,
  int firstStart,
  int firstCount,
  int secondCount,
  int colorLevels,
  bool comparable,
  int originShift
  ) =>
    tileColumns = int((columns + TILE_SIZE - 1) / TILE_SIZE)
    generation = scratch.candidateGeneration
    sameChanges = 0
    shiftedChanges = 0
    // Skip repeated dirty marks within the same tile.
    lastSameTile = -1
    lastShiftTile = -1
    // Validate palette bounds with native reductions. Unwritten ring cells
    // and na values remain transparent.
    int lowest = na
    int highest = na
    for band in bands
        localLow = band.values.min()
        localHigh = band.values.max()
        if not na(localHigh)
            lowest := na(lowest) ? localLow : math.min(lowest, localLow)
            highest := na(highest) ? localHigh : math.max(highest, localHigh)
    if lowest < -1 or highest >= colorLevels
        runtime.error(
          "index must be -1 or 0.." +
          str.tostring(colorLevels - 1) + ".")
    if not comparable and
      _contiguousRuns(stride, columns, firstStart, secondCount)
        // Copy matching palette layouts directly into an independent bin plane.
        bandCount = bands.size()
        if bandCount > 0
            lastBand = bandCount - 1
            for bandIndex = 0 to lastBand
                copied = bands.get(bandIndex).values.copy()
                PaletteBand destination =
                  scratch.largeBins.bands.get(bandIndex)
                destination.values := copied
                if copied.includes(na)
                    count = copied.size()
                    for local = 0 to count - 1
                        if na(copied.get(local))
                            copied.set(local, -1)
    else
        // Element iteration also handles empty arrays.
        for [destinationIndex, destinationBand] in scratch.largeBins.bands
            current = destinationBand.values
            previous = comparable ?
              scratch.largeLastBins.bands.get(destinationIndex).values : na
            rowsHere = destinationBand.rowCount
            destinationStart = destinationBand.rowStart
            if rowsHere > 0
                lastLocalRow = rowsHere - 1
                cachedBand = -1
                array<int> sourceCells = na
                sourceStart = 0
                for localRow = 0 to lastLocalRow
                    row = destinationStart + localRow
                    sourceIndex = int(row / bandHeight)
                    if sourceIndex != cachedBand
                        PaletteBand sourceBand = bands.get(sourceIndex)
                        sourceCells := sourceBand.values
                        sourceStart := sourceBand.rowStart
                        cachedBand := sourceIndex
                    sourceBase = (row - sourceStart) * stride
                    destinationBase = localRow * columns
                    tileRowBase = int(row / TILE_SIZE) * tileColumns
                    for runIndex = 0 to 1
                        runStart = runIndex == 0 ? firstStart : 0
                        runCount = runIndex == 0 ? firstCount : secondCount
                        runColumn = runIndex == 0 ? 0 : firstCount
                        if runCount > 0
                            lastOffset = runCount - 1
                            runSource = sourceBase + runStart
                            if not comparable
                                runTarget = destinationBase + runColumn
                                for offset = 0 to lastOffset
                                    current.set(runTarget + offset,
                                      nz(sourceCells.get(
                                      runSource + offset), -1))
                            else
                                for offset = 0 to lastOffset
                                    // Convert na indices to -1 before neighbor comparisons and contour tracing.
                                    level = nz(sourceCells.get(
                                      runSource + offset), -1)
                                    column = runColumn + offset
                                    local = destinationBase + column
                                    current.set(local, level)
                                    if previous.get(local) != level
                                        sameChanges += 1
                                        logicalTile = tileRowBase +
                                          int(column / TILE_SIZE)
                                        if logicalTile != lastSameTile
                                            _markLargeCandidate(
                                              scratch.candidateSameTileStamp,
                                              scratch.candidateSameTiles,
                                              generation, logicalTile)
                                            lastSameTile := logicalTile
                                    // Read the previous cell at the same band row plus originShift.
                                    if originShift != 0
                                        oldColumn = column + originShift
                                        if oldColumn < 0 or
                                          oldColumn >= columns or
                                          previous.get(local + originShift) != level
                                            shiftedChanges += 1
                                            logicalTile = tileRowBase +
                                              int(column / TILE_SIZE)
                                            if logicalTile != lastShiftTile
                                                _markLargeCandidate(
                                                  scratch.candidateShiftTileStamp,
                                                  scratch.candidateShiftTiles,
                                                  generation, logicalTile)
                                                lastShiftTile := logicalTile
    if originShift == 0
        shiftedChanges := sameChanges
    keepLogical = originShift == 0 or sameChanges <= shiftedChanges
    [not na(highest) and highest >= 0, sameChanges, shiftedChanges, keepLogical]
 
// Store extrema by logical column so quantization needs no ring mapping.
_accumulateColumnExtremes(
  _CanvasScratch scratch,
  array<ValueBand> bands,
  int stride,
  int columns,
  int firstStart,
  int firstCount,
  int secondCount
  ) =>
    scratch.groupMin := _growFloatArray(scratch.groupMin, columns)
    scratch.groupMax := _growFloatArray(scratch.groupMax, columns)
    groupMin = scratch.groupMin
    groupMax = scratch.groupMax
    groupMin.fill(na, 0, columns)
    groupMax.fill(na, 0, columns)
    for band in bands
        rowsHere = band.rowCount
        if rowsHere > 0
            // Use matrix columns for native extrema, then merge band ranges into
            // the corresponding logical columns.
            grid = matrix.new<float>()
            grid.add_row(0, band.values)
            grid.reshape(rowsHere, stride)
            for runIndex = 0 to 1
                runStart = runIndex == 0 ? firstStart : 0
                runCount = runIndex == 0 ? firstCount : secondCount
                runColumn = runIndex == 0 ? 0 : firstCount
                if runCount > 0
                    for offset = 0 to runCount - 1
                        physical = grid.col(runStart + offset)
                        bandLow = physical.min()
                        bandHigh = physical.max()
                        if not na(bandHigh)
                            column = runColumn + offset
                            columnLow = groupMin.get(column)
                            columnHigh = groupMax.get(column)
                            groupMin.set(column, na(columnLow) ?
                              bandLow : math.min(columnLow, bandLow))
                            groupMax.set(column, na(columnHigh) ?
                              bandHigh : math.max(columnHigh, bandHigh))
    0
 
// Keep division and gamma evaluation unchanged; reciprocal multiplication
// can move values across quantization boundaries.
_quantizeLargeValueRuns(
  _CanvasScratch scratch,
  array<ValueBand> bands,
  int bandHeight,
  int stride,
  int columns,
  int firstStart,
  int firstCount,
  int secondCount,
  Style style,
  bool groupedScale,
  bool scaleColumns,
  float scaleMin,
  float scaleMax,
  bool comparable,
  int originShift
  ) =>
    if groupedScale and scaleColumns
        _accumulateColumnExtremes(
          scratch, bands, stride, columns,
          firstStart, firstCount, secondCount)
    tileColumns = int((columns + TILE_SIZE - 1) / TILE_SIZE)
    generation = scratch.candidateGeneration
    sameChanges = 0
    shiftedChanges = 0
    lastSameTile = -1
    lastShiftTile = -1
    maxBin = style.colorLevels - 1
    levelSpan = style.colorLevels
    gammaExponent = style.gamma
    unitGamma = math.sign(gammaExponent - 1.0) == 0
    measureRows = groupedScale and not scaleColumns
    for [destinationIndex, destinationBand] in scratch.largeBins.bands
        current = destinationBand.values
        previous = comparable ?
          scratch.largeLastBins.bands.get(destinationIndex).values : na
        rowsHere = destinationBand.rowCount
        destinationStart = destinationBand.rowStart
        if rowsHere > 0
            lastLocalRow = rowsHere - 1
            cachedBand = -1
            array<float> sourceCells = na
            sourceStart = 0
            for localRow = 0 to lastLocalRow
                row = destinationStart + localRow
                sourceIndex = int(row / bandHeight)
                if sourceIndex != cachedBand
                    ValueBand sourceBand = bands.get(sourceIndex)
                    sourceCells := sourceBand.values
                    sourceStart := sourceBand.rowStart
                    cachedBand := sourceIndex
                sourceBase = (row - sourceStart) * stride
                destinationBase = localRow * columns
                tileRowBase = int(row / TILE_SIZE) * tileColumns
                // Measure row extrema over its chronological runs before quantization.
                // Other scale modes reuse the frame range.
                rowLow = scaleMin
                rowHigh = scaleMax
                if measureRows
                    rowLow := na
                    rowHigh := na
                    for runIndex = 0 to 1
                        runStart = runIndex == 0 ? firstStart : 0
                        runCount = runIndex == 0 ? firstCount : secondCount
                        if runCount > 0
                            runSource = sourceBase + runStart
                            [runLow, runHigh] = _nativeRowExtrema(sourceCells, runSource, runCount)
                            if not na(runHigh)
                                rowLow := na(rowLow) ? runLow : math.min(rowLow, runLow)
                                rowHigh := na(rowHigh) ? runHigh : math.max(rowHigh, runHigh)
                constantScale = rowHigh <= rowLow
                scaleSpan = rowHigh - rowLow
                for runIndex = 0 to 1
                    runStart = runIndex == 0 ? firstStart : 0
                    runCount = runIndex == 0 ? firstCount : secondCount
                    runColumn = runIndex == 0 ? 0 : firstCount
                    if runCount > 0
                        lastOffset = runCount - 1
                        runSource = sourceBase + runStart
                        for offset = 0 to lastOffset
                            value = sourceCells.get(runSource + offset)
                            column = runColumn + offset
                            bin = -1
                            if not na(value)
                                float normalized = na
                                if scaleColumns
                                    groupLow = scratch.groupMin.get(column)
                                    groupHigh = scratch.groupMax.get(column)
                                    normalized := groupHigh <= groupLow ?
                                      1.0 : math.max(0.0, math.min(1.0,
                                      (value - groupLow) /
                                      (groupHigh - groupLow)))
                                else
                                    normalized := constantScale ? 1.0 :
                                      math.max(0.0, math.min(1.0,
                                      (value - rowLow) / scaleSpan))
                                curved = unitGamma ? normalized :
                                  math.pow(normalized, gammaExponent)
                                bin := int(math.min(maxBin,
                                  math.floor(curved * levelSpan)))
                            local = destinationBase + column
                            current.set(local, bin)
                            if comparable
                                if previous.get(local) != bin
                                    sameChanges += 1
                                    logicalTile = tileRowBase +
                                      int(column / TILE_SIZE)
                                    if logicalTile != lastSameTile
                                        _markLargeCandidate(
                                          scratch.candidateSameTileStamp,
                                          scratch.candidateSameTiles,
                                          generation, logicalTile)
                                        lastSameTile := logicalTile
                                // Read the previous cell at the same band row plus originShift.
                                if originShift != 0
                                    oldColumn = column + originShift
                                    if oldColumn < 0 or
                                      oldColumn >= columns or
                                      previous.get(local + originShift) != bin
                                        shiftedChanges += 1
                                        logicalTile = tileRowBase +
                                          int(column / TILE_SIZE)
                                        if logicalTile != lastShiftTile
                                            _markLargeCandidate(
                                              scratch.candidateShiftTileStamp,
                                              scratch.candidateShiftTiles,
                                              generation, logicalTile)
                                            lastShiftTile := logicalTile
    if originShift == 0
        shiftedChanges := sameChanges
    keepLogical = originShift == 0 or sameChanges <= shiftedChanges
    [sameChanges, shiftedChanges, keepLogical]
 
_findLargeRoot(_IntPlane parents, int cell) =>
    root = cell
    parent = _parentGet(parents, root)
    while parent != root
        root := parent
        parent := _parentGet(parents, root)
    cursor = cell
    while cursor != root
        next = _parentGet(parents, cursor)
        _parentSet(parents, cursor, root)
        cursor := next
    root
 
_tileOwnershipRootAt(
  _CanvasScratch scratch,
  int row,
  int worldColumn,
  int columns
  ) =>
    tileRow = int(row / TILE_SIZE)
    activeColumn = int(worldColumn / TILE_SIZE) -
      scratch.firstWorldTileColumn
    _TileProgram record = scratch.tilePrograms.get(scratch.activeTileSlots.get(
      tileRow * scratch.activeTileColumns + activeColumn))
    _tileRoot(
      record.boundaryCell, record.boundaryMask,
      record.rowStart, record.columnStart, record.columnEnd,
      row, worldColumn, columns, scratch.worldOrigin)
 
_joinLargeTileCells(
  _CanvasScratch scratch,
  _IntPlane bins,
  _IntPlane parents,
  int leftRow,
  int leftWorldColumn,
  int rightRow,
  int rightWorldColumn,
  int columns
  ) =>
    worldOrigin = scratch.worldOrigin
    level = _planeGetRC(
      bins, leftRow, leftWorldColumn - worldOrigin)
    if level >= 0 and _planeGetRC(
      bins, rightRow, rightWorldColumn - worldOrigin) == level
        left = _tileOwnershipRootAt(
          scratch, leftRow, leftWorldColumn, columns)
        right = _tileOwnershipRootAt(
          scratch, rightRow, rightWorldColumn, columns)
        leftRoot = _findLargeRoot(parents, left)
        rightRoot = _findLargeRoot(parents, right)
        if leftRoot != rightRoot
            _parentSet(parents, leftRoot > rightRoot ? leftRoot : rightRoot,
              leftRoot < rightRoot ? leftRoot : rightRoot)
    0
 
// Join 8-connected neighbors across right and upper tile seams. Empty
// tiles have no roots to join. Alternate-tile passes retain the same
// minimum-cell roots regardless of union order.
_joinLargeSeams(_CanvasScratch scratch, int part) =>
    _IntPlane bins = scratch.largeBins
    rows = bins.rows
    columns = bins.columns
    worldOrigin = scratch.worldOrigin
    worldEnd = worldOrigin + columns
    slots = scratch.activeTileSlots
    count = slots.size()
    if count > part
        for index = part to count - 1 by 2
            _TileProgram record = scratch.tilePrograms.get(slots.get(index))
            if record.boundaryMask.size() > 0
                if record.columnEnd < worldEnd
                    leftColumn = record.columnEnd - 1
                    rightColumn = record.columnEnd
                    for row = record.rowStart to record.rowEnd - 1
                        for offset = -1 to 1
                            neighborRow = row + offset
                            if neighborRow >= 0 and neighborRow < rows
                                _joinLargeTileCells(
                                  scratch, bins, scratch.largeParents, row, leftColumn,
                                  neighborRow, rightColumn, columns)
                if record.rowEnd < rows
                    lowerRow = record.rowEnd - 1
                    upperRow = record.rowEnd
                    for worldColumn = record.columnStart to record.columnEnd - 1
                        for offset = -1 to 1
                            neighborColumn = worldColumn + offset
                            if neighborColumn >= worldOrigin and neighborColumn < worldEnd
                                _joinLargeTileCells(
                                  scratch, bins, scratch.largeParents, lowerRow, worldColumn,
                                  upperRow, neighborColumn, columns)
    0
 
_buildLargeOwnership(_CanvasScratch scratch, int rows, int columns) =>
    scratch.largeParents := _ensureIntPlane(
      scratch.largeParents, rows, columns, -1)
    _IntPlane parents = scratch.largeParents
    worldOrigin = scratch.worldOrigin
    for slot in scratch.activeTileSlots
        _TileProgram record = scratch.tilePrograms.get(slot)
        roots = record.boundaryMask
        rootCount = roots.size()
        if rootCount > 0
            localColumns = record.columnEnd - record.columnStart
            for rootIndex = 0 to rootCount - 1
                localRoot = roots.get(rootIndex)
                localRow = int(localRoot / localColumns)
                root = (record.rowStart + localRow) * columns +
                  record.columnStart + localRoot - localRow * localColumns -
                  worldOrigin
                _parentSet(parents, root, root)
    _joinLargeSeams(scratch, 0)
    _joinLargeSeams(scratch, 1)
 
_findLargeComponent(_IntPlane parents, int cell) =>
    cursor = cell
    parent = _parentGet(parents, cursor)
    while parent >= 0
        cursor := parent
        parent := _parentGet(parents, cursor)
    result = -1
    if parent <= -2
        result := -parent - 2
        path = cell
        next = _parentGet(parents, path)
        while next >= 0
            _parentSet(parents, path, parent)
            path := next
            next := _parentGet(parents, path)
    result
 
// Assign component IDs by ascending minimum-cell root. Sort roots in
// bounded buckets to stay within Pine collection limits.
_buildLargeComponentDirectory(
  _CanvasScratch scratch,
  int rows,
  int columns,
  int colorLevels
  ) =>
    _ensureLargeMetadata(scratch)
    _IntPlane bins = scratch.largeBins
    _IntPlane parents = scratch.largeParents
    worldOrigin = scratch.worldOrigin
    array<_IntPage> buckets = array.new<_IntPage>()
    for bucketIndex = 0 to int(rows * columns / MAX_CELLS)
        buckets.push(_IntPage.new(array.new_int()))
    componentCount = 0
    for slot in scratch.activeTileSlots
        _TileProgram record = scratch.tilePrograms.get(slot)
        localColumns = record.columnEnd - record.columnStart
        for localRoot in record.boundaryMask
            localRow = int(localRoot / localColumns)
            cell = (record.rowStart + localRow) * columns + record.columnStart +
              localRoot - localRow * localColumns - worldOrigin
            if _parentGet(parents, cell) == cell
                buckets.get(int(cell / MAX_CELLS)).values.push(cell)
                componentCount += 1
    // Initialize shared defaults in bulk; write root and next per component.
    _pagesResize(scratch.largeComponentRoot, componentCount, 0)
    _pagesResize(scratch.largeComponentNext, componentCount, -1)
    _pagesResize(scratch.largeComponentChainCount, componentCount, 0)
    _pagesResize(scratch.largeComponentChainOffset, componentCount, 0)
    _pagesResize(scratch.largeComponentChainFill, componentCount, 0)
    _pagesResize(scratch.largeComponentPointBound, componentCount, 0)
    _pagesResize(scratch.largeComponentExactPoints, componentCount, -1)
    _pagesResize(scratch.largeComponentMinTileRow, componentCount, rows)
    _pagesResize(scratch.largeComponentMaxTileRow, componentCount, -1)
    _pagesResize(scratch.largeComponentMinTileColumn, componentCount,
      scratch.firstWorldTileColumn + scratch.activeTileColumns)
    _pagesResize(scratch.largeComponentMaxTileColumn, componentCount, -1)
    levelFirst = scratch.largeLevelFirst
    levelLast = scratch.largeLevelLast
    levelRegions = scratch.largeLevelRegions
    levelFirst.fill(-1, 0, colorLevels)
    levelLast.fill(-1, 0, colorLevels)
    levelRegions.fill(0, 0, colorLevels)
    component = 0
    for bucket in buckets
        roots = bucket.values
        roots.sort(order.ascending)
        for cell in roots
            row = int(cell / columns)
            column = cell - row * columns
            level = _planeGetRC(bins, row, column)
            if level < 0 or level >= colorLevels
                runtime.error("E9")
            _pagesSet(scratch.largeComponentRoot, component, cell)
            prior = levelLast.get(level)
            if prior < 0
                levelFirst.set(level, component)
            else
                _pagesSet(scratch.largeComponentNext, prior, component)
            levelLast.set(level, component)
            levelRegions.set(level, levelRegions.get(level) + 1)
            _parentSet(parents, cell, -(component + 2))
            component += 1
    scratch.lastComponentCount := componentCount
    componentCount
 
// Global component IDs in tile-local root order.
_tileRootComponents(
  _TileProgram record,
  _IntPlane parents,
  int columns,
  int worldOrigin
  ) =>
    localColumns = record.columnEnd - record.columnStart
    result = array.new_int()
    for localRoot in record.boundaryMask
        localRow = int(localRoot / localColumns)
        result.push(_findLargeComponent(parents,
          (record.rowStart + localRow) * columns + record.columnStart +
          localRoot - localRow * localColumns - worldOrigin))
    result
 
// Find a chain's root in the sorted tile root list. Uniform halos contain
// no chains, so this path always has a full owner raster.
_chainRootIndex(_TileProgram record, int localChain) =>
    record.boundaryMask.binary_search(record.boundaryCell.get(
      int(record.chainFirstEdge.get(localChain) / 4)))
 
// Count chains and point bounds per component over alternate tile slots.
// Cache each chain's component for the fill pass.
_countLargeChains(
  _CanvasScratch scratch,
  int columns,
  int part
  ) =>
    _IntPlane parents = scratch.largeParents
    generation = scratch.tileGeneration
    worldOrigin = scratch.worldOrigin
    slotCount = scratch.tilePrograms.size()
    if slotCount > part
        for slot = part to slotCount - 1 by 2
            _TileProgram record = scratch.tilePrograms.get(slot)
            if record.activeGeneration == generation
                chainCount = record.chainEnd.size()
                // Grow chain states as needed; walk stamps make reset passes unnecessary.
                record.chainState := _growIntArray(
                  record.chainState, chainCount, -1)
                if chainCount > 0
                    rootComponents = _tileRootComponents(
                      record, parents, columns, worldOrigin)
                    chainComponents = array.new_int()
                    rootChains = array.new_int(rootComponents.size(), 0)
                    rootPoints = array.new_int(rootComponents.size(), 0)
                    chainFrom = 0
                    for localChain = 0 to chainCount - 1
                        rootAt = _chainRootIndex(record, localChain)
                        chainComponents.push(rootComponents.get(rootAt))
                        chainTo = record.chainEnd.get(localChain)
                        rootChains.set(rootAt, rootChains.get(rootAt) + 1)
                        rootPoints.set(rootAt,
                          rootPoints.get(rootAt) + chainTo - chainFrom + 1)
                        chainFrom := chainTo
                    record.chainComponents := chainComponents
                    tileRow = int(record.rowStart / TILE_SIZE)
                    tileColumn = int(record.columnStart / TILE_SIZE)
                    for [rootIndex, chains] in rootChains
                        if chains > 0
                            component = rootComponents.get(rootIndex)
                            _pagesSet(scratch.largeComponentChainCount, component,
                              _pagesGet(scratch.largeComponentChainCount, component) + chains)
                            _pagesSet(scratch.largeComponentPointBound, component,
                              _pagesGet(scratch.largeComponentPointBound, component) +
                              rootPoints.get(rootIndex))
                            _pagesSet(scratch.largeComponentMinTileRow, component,
                              math.min(_pagesGet(scratch.largeComponentMinTileRow, component), tileRow))
                            _pagesSet(scratch.largeComponentMaxTileRow, component,
                              math.max(_pagesGet(scratch.largeComponentMaxTileRow, component), tileRow))
                            _pagesSet(scratch.largeComponentMinTileColumn, component,
                              math.min(_pagesGet(scratch.largeComponentMinTileColumn, component), tileColumn))
                            _pagesSet(scratch.largeComponentMaxTileColumn, component,
                              math.max(_pagesGet(scratch.largeComponentMaxTileColumn, component), tileColumn))
    0
 
// Fill component chain lists in tile-slot order using the cached IDs.
_buildLargeChainCsr(
  _CanvasScratch scratch,
  int componentCount,
  int columns
  ) =>
    _countLargeChains(scratch, columns, 0)
    _countLargeChains(scratch, columns, 1)
    totalChains = 0
    if componentCount > 0
        for component = 0 to componentCount - 1
            _pagesSet(scratch.largeComponentChainOffset, component, totalChains)
            _pagesSet(scratch.largeComponentChainFill, component, totalChains)
            totalChains += _pagesGet(
              scratch.largeComponentChainCount, component)
    _pagesResize(scratch.largeChainSlots, totalChains, -1)
    _pagesResize(scratch.largeChainLocals, totalChains, -1)
    generation = scratch.tileGeneration
    for [slot, record] in scratch.tilePrograms
        if record.activeGeneration == generation and record.chainEnd.size() > 0
            for [localChain, component] in record.chainComponents
                page = int(component / PAGE_ELEMENTS)
                at = component - page * PAGE_ELEMENTS
                fills = scratch.largeComponentChainFill.pages.get(page).values
                destination = fills.get(at)
                fills.set(at, destination + 1)
                _pagesSet(scratch.largeChainSlots, destination, slot)
                _pagesSet(scratch.largeChainLocals, destination, localChain)
    totalChains
 
_traceLargeComponent(
  _CanvasScratch scratch,
  int component,
  int level,
  int rows,
  int columns
  ) =>
    _IntPages traced = scratch.largeTraceVertices
    _pagesClear(traced)
    _pagesClear(scratch.largeTraceLoopStart)
    _pagesClear(scratch.largeTraceLoopEnd)
    // A chain is consumed when its state equals this trace's stamp.
    stamp = scratch.chainStamp + 1
    scratch.chainStamp := stamp
    tilePrograms = scratch.tilePrograms
    worldOrigin = scratch.worldOrigin
    worldEnd = worldOrigin + columns
    index = _pagesGet(scratch.largeComponentChainOffset, component)
    remaining = _pagesGet(scratch.largeComponentChainCount, component)
    loopCount = 0
    exactPoints = 0
    while remaining > 0
        [slots, locals, pageOffset, available] =
          _largeChainPage(scratch, index, remaining)
        for rangeIndex = 0 to available - 1
            streamOffset = pageOffset + rangeIndex
            seedSlot = slots.get(streamOffset)
            seedLocal = locals.get(streamOffset)
            _TileProgram seedRecord = tilePrograms.get(seedSlot)
            if seedRecord.chainState.get(seedLocal) != stamp
                seedFrom = seedLocal > 0 ?
                  seedRecord.chainEnd.get(seedLocal - 1) : 0
                seedVertex = seedRecord.vertices.get(seedFrom)
                rawStart = traced.size
                firstDirection = -1
                previousDirection = -1
                endVertex = seedVertex
                currentSlot = seedSlot
                currentLocal = seedLocal
                chainSteps = 0
                while true
                    _TileProgram record = tilePrograms.get(currentSlot)
                    record.chainState.set(currentLocal, stamp)
                    fromIndex = currentLocal > 0 ?
                      record.chainEnd.get(currentLocal - 1) : 0
                    toIndex = record.chainEnd.get(currentLocal)
                    // Test the first vertex for collinearity, then copy the chain's turning
                    // vertices as one range.
                    source = record.vertices
                    head = source.get(fromIndex)
                    direction = _axisDirection(source.get(fromIndex + 1) - head)
                    appendFrom = firstDirection < 0 or direction != previousDirection ?
                      fromIndex : fromIndex + 1
                    if firstDirection < 0
                        firstDirection := direction
                    previousDirection := direction
                    endVertex := source.get(toIndex - 1)
                    if toIndex - 1 > appendFrom
                        _pagesAppendRange(traced, source, appendFrom, toIndex - 1)
                    if toIndex - fromIndex > 2
                        previousDirection := _axisDirection(
                          endVertex - source.get(toIndex - 2))
                    chainSteps += 1
                    if endVertex == seedVertex
                        break
                    vertexRow = int(endVertex / WORLD_STRIDE)
                    vertexColumn = endVertex % WORLD_STRIDE
                    // Use the cached first-choice continuation only if it is unconsumed.
                    recorded = record.chainExit.get(currentLocal)
                    nextChain = recorded < 0 ? -1 :
                      _junctionChain(scratch, vertexRow, vertexColumn, recorded, stamp)
                    if nextChain < 0
                        bins = scratch.largeBins
                        lowerRight = vertexRow > 0 and
                          vertexColumn < worldEnd and
                          _planeGetRC(bins, vertexRow - 1, vertexColumn - worldOrigin) == level
                        upperRight = vertexRow < rows and
                          vertexColumn < worldEnd and
                          _planeGetRC(bins, vertexRow, vertexColumn - worldOrigin) == level
                        upperLeft = vertexRow < rows and
                          vertexColumn > worldOrigin and
                          _planeGetRC(bins, vertexRow, vertexColumn - 1 - worldOrigin) == level
                        lowerLeft = vertexRow > 0 and
                          vertexColumn > worldOrigin and
                          _planeGetRC(bins, vertexRow - 1, vertexColumn - 1 - worldOrigin) == level
                        for priority = 0 to 3
                            outgoing = (previousDirection + 3 + priority) % 4
                            if _leaves(lowerRight, upperRight, upperLeft, lowerLeft, outgoing)
                                nextChain := _junctionChain(scratch,
                                  vertexRow, vertexColumn, outgoing, stamp)
                                if nextChain >= 0
                                    break
                    if nextChain < 0
                        runtime.error("E10")
                    currentSlot := int(nextChain / TILE_EDGE_CAPACITY)
                    currentLocal := nextChain % TILE_EDGE_CAPACITY
                    if chainSteps > rows * columns * 4 + 1
                        runtime.error("E11")
                cornerOffset = firstDirection == previousDirection ? 1 : 0
                loopStart = rawStart + cornerOffset
                loopEnd = traced.size
                cornerCount = loopEnd - loopStart
                if cornerCount < 3
                    runtime.error("E12")
                _pagesPush(scratch.largeTraceLoopStart, loopStart)
                _pagesPush(scratch.largeTraceLoopEnd, loopEnd)
                exactPoints += cornerCount + 1
                loopCount += 1
        index += available
        remaining -= available
    if loopCount > 1
        exactPoints += loopCount - 1
    exactPoints
 
_rebuildLargeTopology(
  _CanvasScratch scratch,
  int rows,
  int columns,
  int worldOrigin,
  int colorLevels
  ) =>
    _prepareTileDirectory(scratch, rows, columns, worldOrigin)
    for slot in scratch.activeTileSlots
        _compileTileLarge(
          scratch, scratch.tilePrograms.get(slot),
          scratch.largeBins, rows, columns)
    _buildLargeOwnership(scratch, rows, columns)
    componentCount = _buildLargeComponentDirectory(
      scratch, rows, columns, colorLevels)
    _buildLargeChainCsr(
      scratch, componentCount, columns)
    componentCount
 
_copyTraceToFragment(_CanvasScratch scratch, int rowOffset) =>
    loopCount = scratch.largeTraceLoopStart.size
    if loopCount > 0
        for loop = 0 to loopCount - 1
            sourceStart = _pagesGet(scratch.largeTraceLoopStart, loop)
            sourceEnd = _pagesGet(scratch.largeTraceLoopEnd, loop)
            targetStart = scratch.largeFragmentVertices.size
            for index = sourceStart to sourceEnd - 1
                _pagesPush(scratch.largeFragmentVertices,
                  _pagesGet(scratch.largeTraceVertices, index) +
                  rowOffset * WORLD_STRIDE)
            _pagesPush(scratch.largeFragmentLoopStart, targetStart)
            _pagesPush(scratch.largeFragmentLoopEnd,
              scratch.largeFragmentVertices.size)
    loopCount
 
_countLargeFragment(
  _CanvasScratch scratch,
  _IntPlane membership,
  int membershipRowStart,
  int membershipColumnStart,
  int membershipCount,
  _Fragment fragment
  ) =>
    rowStart = fragment.rowStart
    columnStart = fragment.columnStart
    fragmentRows = fragment.rowEnd - rowStart
    fragmentColumns = fragment.columnEnd - columnStart
    wholeMembership = rowStart == membershipRowStart and
      columnStart == membershipColumnStart and
      fragmentRows == membership.rows and fragmentColumns == membership.columns
    _IntPlane fragmentBins = membership
    memberCount = membershipCount
    if not wholeMembership
        // Copy binary membership by row slices; summing 0/-1 cells gives occupancy.
        fragmentBins := _ensureIntPlaneLayout(
          scratch.largeFragmentBins, fragmentRows, fragmentColumns, -1, false)
        scratch.largeFragmentBins := fragmentBins
        memberCount := 0
        columnOffset = columnStart - membershipColumnStart
        for band in fragmentBins.bands
            cells = band.values
            cells.clear()
            for bandRow = 0 to band.rowCount - 1
                membershipRow = rowStart - membershipRowStart +
                  band.rowStart + bandRow
                PaletteBand source = membership.bands.get(
                  int(membershipRow / membership.bandRows))
                sourceBase = (membershipRow - source.rowStart) *
                  membership.columns + columnOffset
                cells.concat(source.values.slice(
                  sourceBase, sourceBase + fragmentColumns))
            memberCount += cells.size() + int(cells.sum())
    vertexBase = scratch.largeFragmentVertices.size
    loopBase = scratch.largeFragmentLoopStart.size
    exactPoints = 0
    loopCount = 0
    if memberCount > 0
        _IntPlane savedBins = scratch.largeBins
        scratch.largeBins := fragmentBins
        scratch.largeParents := scratch.largeFragmentParents
        temporaryComponents = _rebuildLargeTopology(
          scratch, fragmentRows, fragmentColumns,
          columnStart, 1)
        if temporaryComponents > 0
            temporary = scratch.largeLevelFirst.get(0)
            while temporary >= 0
                componentPoints = _traceLargeComponent(
                  scratch, temporary, 0, fragmentRows, fragmentColumns)
                exactPoints += componentPoints
                // Stop copying once the combined unit exceeds the point budget.
                if exactPoints + temporaryComponents - 1 <= MAX_POINTS
                    loopCount += _copyTraceToFragment(scratch, rowStart)
                temporary := _pagesGet(
                  scratch.largeComponentNext, temporary)
            if temporaryComponents > 1
                exactPoints += temporaryComponents - 1
        if not wholeMembership
            scratch.largeFragmentBins := scratch.largeBins
        scratch.largeFragmentParents := scratch.largeParents
        scratch.largeBins := savedBins
    [exactPoints, memberCount, vertexBase, loopBase, loopCount]
 
_rollbackFragmentTrace(
  _CanvasScratch scratch,
  int vertexBase,
  int loopBase
  ) =>
    scratch.largeFragmentVertices.size := vertexBase
    scratch.largeFragmentLoopStart.size := loopBase
    scratch.largeFragmentLoopEnd.size := loopBase
    0
 
_prefixSums(array<int> values, int count) =>
    if count > 1
        for index = 1 to count - 1
            values.set(index, values.get(index) + values.get(index - 1))
    0
 
_buildComponentHistograms(
  _CanvasScratch scratch,
  int component,
  int tileRows,
  int tileColumns
  ) =>
    xWeight = _growIntArray(scratch.partitionXWeight, tileColumns, 0)
    yWeight = _growIntArray(scratch.partitionYWeight, tileRows, 0)
    scratch.partitionXWeight := xWeight
    scratch.partitionYWeight := yWeight
    xWeight.fill(0, 0, tileColumns)
    yWeight.fill(0, 0, tileRows)
    index = _pagesGet(scratch.largeComponentChainOffset, component)
    remaining = _pagesGet(scratch.largeComponentChainCount, component)
    while remaining > 0
        [slots, locals, pageOffset, available] =
          _largeChainPage(scratch, index, remaining)
        for local = 0 to available - 1
            offset = pageOffset + local
            _TileProgram record = scratch.tilePrograms.get(slots.get(offset))
            chain = locals.get(offset)
            chainFrom = chain > 0 ? record.chainEnd.get(chain - 1) : 0
            weight = record.chainEnd.get(chain) - chainFrom + 1
            tileRow = int(record.rowStart / TILE_SIZE)
            tileColumn = int(record.columnStart / TILE_SIZE) -
              scratch.firstWorldTileColumn
            xWeight.set(tileColumn, xWeight.get(tileColumn) + weight)
            yWeight.set(tileRow, yWeight.get(tileRow) + weight)
        index += available
        remaining -= available
    _prefixSums(xWeight, tileColumns)
    _prefixSums(yWeight, tileRows)
 
_prefixRange(array<int> prefix, int first, int last) =>
    last < first ? 0 : prefix.get(last) -
      (first > 0 ? prefix.get(first - 1) : 0)
 
_fragmentSeam(
  _IntPlane membership,
  int membershipRowStart,
  int membershipColumnStart,
  _Fragment fragment,
  int axis,
  int position
  ) =>
    seam = 0
    if axis == 0
        leftColumn = position - 1 - membershipColumnStart
        rightColumn = position - membershipColumnStart
        for row = fragment.rowStart to fragment.rowEnd - 1
            membershipRow = row - membershipRowStart
            if _planeGetRC(membership, membershipRow, leftColumn) == 0 and
              _planeGetRC(membership, membershipRow, rightColumn) == 0
                seam += 1
    else
        firstRow = position - 1 - membershipRowStart
        secondRow = position - membershipRowStart
        for worldColumn = fragment.columnStart to fragment.columnEnd - 1
            column = worldColumn - membershipColumnStart
            if _planeGetRC(membership, firstRow, column) == 0 and
              _planeGetRC(membership, secondRow, column) == 0
                seam += 1
    seam
 
// The fragment's extent along an axis and its interior tile seams.
_cutSeams(_Fragment fragment, int axis) =>
    start = axis == 0 ? fragment.columnStart : fragment.rowStart
    finish = axis == 0 ? fragment.columnEnd : fragment.rowEnd
    firstSeam = int((start + TILE_SIZE - 1) / TILE_SIZE) * TILE_SIZE
    [start, finish, firstSeam, firstSeam < finish ?
      int((finish - 1 - firstSeam) / TILE_SIZE) + 1 : 0]
 
_chooseLargeCut(
  _CanvasScratch scratch,
  _IntPlane membership,
  int membershipRowStart,
  int membershipColumnStart,
  int firstWorldTileColumn,
  _Fragment fragment
  ) =>
    // The longer axis, unless it has no interior seam.
    preferred = fragment.columnEnd - fragment.columnStart >=
      fragment.rowEnd - fragment.rowStart ? 0 : 1
    [preferredStart, preferredFinish, preferredSeam, preferredCount] =
      _cutSeams(fragment, preferred)
    axis = preferredCount > 0 ? preferred : 1 - preferred
    [start, finish, firstSeam, seamCount] = _cutSeams(fragment, axis)
    if seamCount == 0
        runtime.error("partition failed: >10000 points")
    if na(scratch.partitionCuts)
        scratch.partitionCuts := array.new_int()
    cuts = scratch.partitionCuts
    cuts.clear()
    prefix = axis == 0 ?
      scratch.partitionXWeight : scratch.partitionYWeight
    tileOffset = axis == 0 ? firstWorldTileColumn : 0
    firstTile = int(start / TILE_SIZE) - tileOffset
    lastTile = int((finish - 1) / TILE_SIZE) - tileOffset
    total = _prefixRange(prefix, firstTile, lastTile)
    if seamCount <= 8
        for candidate = 0 to seamCount - 1
            cuts.push(firstSeam + candidate * TILE_SIZE)
    else
        // Weight quantiles 2/8 to 6/8, then the target split and its
        // complement, each at the first seam whose prefix weight reaches it.
        targets = array.new_int()
        for numerator = 2 to 6
            targets.push(int(total * numerator / 8))
        if fragment.exactPoints > PARTITION_TARGET_POINTS
            target = int(total * PARTITION_TARGET_POINTS /
              fragment.exactPoints)
            targets.push(target)
            targets.push(total - target)
        for desired in targets
            selected = firstSeam
            for candidate = 0 to seamCount - 1
                position = firstSeam + candidate * TILE_SIZE
                if _prefixRange(prefix, firstTile,
                  int(position / TILE_SIZE) - tileOffset - 1) >= desired
                    selected := position
                    break
            if cuts.indexof(selected) < 0
                cuts.push(selected)
    midpoint = int(math.round((start + finish) * 0.5 / TILE_SIZE)) * TILE_SIZE
    midpoint := math.max(firstSeam,
      math.min(firstSeam + (seamCount - 1) * TILE_SIZE, midpoint))
    if cuts.indexof(midpoint) < 0
        cuts.push(midpoint)
 
    bestBalance = -1
    for position in cuts
        cutTile = int(position / TILE_SIZE) - tileOffset
        firstWeight = _prefixRange(prefix, firstTile, cutTile - 1)
        secondWeight = _prefixRange(prefix, cutTile, lastTile)
        if firstWeight > 0 and secondWeight > 0
            balance = firstWeight > secondWeight ? firstWeight : secondWeight
            bestBalance := bestBalance < 0 or balance < bestBalance ? balance : bestBalance
    selectedPosition = midpoint
    selectedSeam = -1
    selectedDistance = -1
    if bestBalance >= 0
        balanceLimit = int(math.ceil(bestBalance * 1.1))
        for position in cuts
            cutTile = int(position / TILE_SIZE) - tileOffset
            firstWeight = _prefixRange(prefix, firstTile, cutTile - 1)
            secondWeight = _prefixRange(prefix, cutTile, lastTile)
            if firstWeight > 0 and secondWeight > 0 and
              firstWeight <= balanceLimit and secondWeight <= balanceLimit
                seam = _fragmentSeam(
                  membership, membershipRowStart, membershipColumnStart,
                  fragment, axis, position)
                distance = math.abs(position - midpoint)
                if selectedSeam < 0 or seam < selectedSeam or
                  (seam == selectedSeam and distance < selectedDistance)
                    selectedPosition := position
                    selectedSeam := seam
                    selectedDistance := distance
    [axis, selectedPosition]
 
_partitionLargeComponent(
  _CanvasScratch scratch,
  _IntPlane originalParents,
  int component,
  int rows,
  int columns,
  int worldOrigin
  ) =>
    tileRows = int((rows + TILE_SIZE - 1) / TILE_SIZE)
    tileColumns = scratch.activeTileColumns
    _buildComponentHistograms(
      scratch, component, tileRows, tileColumns)
    firstWorldTileColumn = scratch.firstWorldTileColumn
    if na(scratch.largePendingFragments)
        scratch.largePendingFragments := array.new<_Fragment>()
    pending = scratch.largePendingFragments
    pending.clear()
    minTileRow = _pagesGet(scratch.largeComponentMinTileRow, component)
    maxTileRow = _pagesGet(scratch.largeComponentMaxTileRow, component)
    minTileColumn = _pagesGet(scratch.largeComponentMinTileColumn, component)
    maxTileColumn = _pagesGet(scratch.largeComponentMaxTileColumn, component)
    membershipRowStart = minTileRow * TILE_SIZE
    membershipRowEnd = math.min(rows, (maxTileRow + 1) * TILE_SIZE)
    membershipColumnStart = math.max(
      worldOrigin, minTileColumn * TILE_SIZE)
    membershipColumnEnd = math.min(
      worldOrigin + columns, (maxTileColumn + 1) * TILE_SIZE)
 
    // Snapshot component membership before fragment rebuilds replace the shared
    // tile directory. Resolve each tile-local root once.
    membershipRows = membershipRowEnd - membershipRowStart
    membershipColumns = membershipColumnEnd - membershipColumnStart
    scratch.largeFragmentBins := _ensureIntPlane(
      scratch.largeFragmentBins, membershipRows, membershipColumns, -1)
    _IntPlane membership = scratch.largeFragmentBins
    membershipCount = 0
    for tileRow = minTileRow to maxTileRow
        for tileColumn = minTileColumn to maxTileColumn
            _TileProgram record = scratch.tilePrograms.get(
              scratch.activeTileSlots.get(tileRow * tileColumns +
              tileColumn - firstWorldTileColumn))
            rootComponents = _tileRootComponents(
              record, originalParents, columns, worldOrigin)
            if rootComponents.includes(component)
                // A one-element owner list is a uniform tile (or a one-cell
                // tile), whose only possible owner is local cell 0.
                owners = record.boundaryCell
                localColumns = record.columnEnd - record.columnStart
                for localRow = 0 to record.rowEnd - record.rowStart - 1
                    membershipRow = record.rowStart + localRow - membershipRowStart
                    PaletteBand band = membership.bands.get(
                      int(membershipRow / membership.bandRows))
                    base = (membershipRow - band.rowStart) * membershipColumns +
                      record.columnStart - membershipColumnStart
                    for localColumn = 0 to localColumns - 1
                        owner = owners.size() == 1 ? 0 :
                          owners.get(localRow * localColumns + localColumn)
                        if owner >= 0 and rootComponents.get(
                          record.boundaryMask.binary_search(owner)) == component
                            band.values.set(base + localColumn, 0)
                            membershipCount += 1
    // Reuse the consumed parent plane for fragment rasters.
    scratch.largeFragmentBins := originalParents
 
    pending.push(_Fragment.new(
      component,
      membershipRowStart, membershipRowEnd,
      membershipColumnStart, membershipColumnEnd,
      -1))
    cuts = 0
    guard = math.max(1,
      (maxTileRow - minTileRow + 1) *
      (maxTileColumn - minTileColumn + 1) * 4)
    while pending.size() > 0
        _Fragment fragment = pending.pop()
        [points, members, vertexBase, loopBase, loopCount] =
          _countLargeFragment(
            scratch, membership,
            membershipRowStart, membershipColumnStart,
            membershipCount, fragment)
        if members == 0
            _rollbackFragmentTrace(scratch, vertexBase, loopBase)
        else if points <= MAX_POINTS
            fragment.exactPoints := points
            scratch.largeFragments.push(fragment)
            _pagesPush(scratch.largeFragmentFirstLoop, loopBase)
            _pagesPush(scratch.largeFragmentLoopCount, loopCount)
        else
            _rollbackFragmentTrace(scratch, vertexBase, loopBase)
            fragment.exactPoints := points
            [axis, position] = _chooseLargeCut(
              scratch, membership,
              membershipRowStart, membershipColumnStart,
              firstWorldTileColumn, fragment)
            cuts += 1
            if cuts > guard
                runtime.error("partition failed: >10000 points")
            // Push the second fragment first so the stack processes the first next.
            pending.push(_Fragment.new(component,
              axis == 0 ? fragment.rowStart : position, fragment.rowEnd,
              axis == 0 ? position : fragment.columnStart, fragment.columnEnd, -1))
            pending.push(_Fragment.new(component,
              fragment.rowStart, axis == 0 ? fragment.rowEnd : position,
              fragment.columnStart, axis == 0 ? position : fragment.columnEnd, -1))
    // Rotate the work planes while keeping membership, full-field parents,
    // and fragment parents in separate storage.
    scratch.largeFragmentBins := membership
    scratch.largeParents := originalParents
    0
 
_preflightLargePartitions(
  _CanvasScratch scratch,
  int componentCount,
  int rows,
  int columns,
  int colorLevels
  ) =>
    resultComponentCount = componentCount
    if na(scratch.largeFragments)
        scratch.largeFragments := array.new<_Fragment>()
        scratch.largePartitionComponents := array.new_int()
        scratch.largePartitionFirst := array.new_int()
    candidates = scratch.largePartitionComponents
    scratch.largeFragments.clear()
    candidates.clear()
    scratch.largePartitionFirst.clear()
    _pagesClear(scratch.largeFragmentVertices)
    _pagesClear(scratch.largeFragmentLoopStart)
    _pagesClear(scratch.largeFragmentLoopEnd)
    _pagesClear(scratch.largeFragmentFirstLoop)
    _pagesClear(scratch.largeFragmentLoopCount)
    if componentCount > 0
        for component = 0 to componentCount - 1
            if _pagesGet(scratch.largeComponentPointBound, component) > MAX_POINTS
                root = _pagesGet(scratch.largeComponentRoot, component)
                level = _parentGet(scratch.largeBins, root)
                exact = _traceLargeComponent(
                  scratch, component, level, rows, columns)
                _pagesSet(scratch.largeComponentExactPoints, component, exact)
                if exact > MAX_POINTS
                    candidates.push(component)
    if candidates.size() > 0
        _IntPlane originalBins = scratch.largeBins
        _IntPlane originalParents = scratch.largeParents
        worldOrigin = scratch.worldOrigin
        for [candidateIndex, component] in candidates
            if candidateIndex > 0
                resultComponentCount := _rebuildLargeTopology(
                  scratch, rows, columns, worldOrigin, colorLevels)
                originalParents := scratch.largeParents
            scratch.largePartitionFirst.push(scratch.largeFragments.size())
            _partitionLargeComponent(
              scratch, originalParents,
              component, rows, columns, worldOrigin)
        scratch.largeBins := originalBins
        resultComponentCount := _rebuildLargeTopology(
          scratch, rows, columns, worldOrigin, colorLevels)
    resultComponentCount
 
_componentFragmentRange(_CanvasScratch scratch, int component) =>
    candidate = scratch.largePartitionComponents.binary_search(component)
    first = candidate < 0 ? -1 : scratch.largePartitionFirst.get(candidate)
    finish = candidate < 0 ? -1 :
      candidate + 1 < scratch.largePartitionFirst.size() ?
      scratch.largePartitionFirst.get(candidate + 1) : scratch.largeFragments.size()
    [first, finish - first]
 
_largeLevelVisible(Style style, int level) =>
    style.lowOpacity + (style.highOpacity - style.lowOpacity) *
      (level / (style.colorLevels - 1.0)) > 0
 
// Estimate per-level drawing counts to divide emission into ten batches.
// Actual drawing requirements are counted during packing.
_largeDrawingCount(_CanvasScratch scratch, int colorLevels, Style style) =>
    scratch.largeLevelRenderUnits.fill(0)
    scratch.largeLevelMandatoryDrawings.fill(0)
    for level = 0 to colorLevels - 1
        activePoints = 0
        levelDrawings = 0
        levelUnits = 0
        component = scratch.largeLevelFirst.get(level)
        while _largeLevelVisible(style, level) and component >= 0
            [firstFragment, fragmentCount] = _componentFragmentRange(
              scratch, component)
            unitCount = fragmentCount > 0 ? fragmentCount : 1
            for unit = 0 to unitCount - 1
                points = 0
                if fragmentCount > 0
                    points := scratch.largeFragments.get(
                      firstFragment + unit).exactPoints
                else
                    exact = _pagesGet(
                      scratch.largeComponentExactPoints, component)
                    points := exact >= 0 ? exact : _pagesGet(
                      scratch.largeComponentPointBound, component)
                levelUnits += 1
                addition = activePoints == 0 ? points : points + 1
                if activePoints > 0 and activePoints + addition > MAX_POINTS
                    levelDrawings += 1
                    activePoints := points
                else
                    activePoints += addition
            component := _pagesGet(scratch.largeComponentNext, component)
        if activePoints > 0
            levelDrawings += 1
        scratch.largeLevelRenderUnits.set(level, levelUnits)
        scratch.largeLevelMandatoryDrawings.set(level, levelDrawings)
    0
 
// Stage a complete component or partition fragment. Reserve closed loops
// and at most four connector points per starting row. Flush before adding
// a unit that would exceed the point budget.
_packLargeUnit(
  Canvas canvas,
  _CanvasScratch scratch,
  _IntPages vertices,
  _IntPages loopStarts,
  _IntPages loopEnds,
  int firstLoop,
  int loopCount,
  int unitPoints,
  int level,
  _Frame frame,
  bool roomForAll
  ) =>
    staged = scratch.chunkVertices
    stamps = scratch.railStamps
    if unitPoints < 1 or unitPoints > MAX_POINTS
        runtime.error("E13")
    if staged.size() > 0
        room = MAX_POINTS + 2 - staged.size() - unitPoints + loopCount
        fits = not roomForAll and
          4 * (scratch.railCount + math.min(loopCount, frame.rows + 1)) <= room
        if not fits and not roomForAll and loopCount > 0 and
          4 * (scratch.railCount + 1) <= room
            // Retain row stamps for the staging pass.
            added = 0
            for loopOffset = 0 to loopCount - 1
                row = int(_pagesGet(vertices,
                  _pagesGet(loopStarts, firstLoop + loopOffset)) / WORLD_STRIDE)
                if stamps.get(row) != scratch.railSerial
                    stamps.set(row, scratch.railSerial)
                    added += 1
            scratch.railCount += added
            fits := 4 * scratch.railCount <= room
        if not fits
            _emitWorldChain(canvas, level, frame)
    if loopCount > 0
        keys = scratch.railKeys
        starts = scratch.railStarts
        serial = scratch.railSerial
        rails = scratch.railCount
        for loopOffset = 0 to loopCount - 1
            loop = firstLoop + loopOffset
            loopStart = _pagesGet(loopStarts, loop)
            cornerCount = _pagesGet(loopEnds, loop) - loopStart
            // A loop spans at most two pages. Append it in trace order and repeat its
            // first corner to close it.
            pageIndex = int(loopStart / PAGE_ELEMENTS)
            pageOffset = loopStart - pageIndex * PAGE_ELEMENTS
            headCount = math.min(cornerCount, PAGE_ELEMENTS - pageOffset)
            page = vertices.pages.get(pageIndex).values
            firstVertex = page.get(pageOffset)
            keys.push(firstVertex * RAIL_SPAN + starts.size())
            starts.push(staged.size())
            row = int(firstVertex / WORLD_STRIDE)
            if stamps.get(row) != serial
                stamps.set(row, serial)
                rails += 1
            staged.concat(page.slice(pageOffset, pageOffset + headCount))
            if headCount < cornerCount
                staged.concat(vertices.pages.get(pageIndex + 1).values.slice(
                  0, cornerCount - headCount))
            staged.push(firstVertex)
        scratch.railCount := rails
    0
 
// Return the first level of an emission batch, dividing estimated drawing
// counts into tenths. Consecutive batch boundaries cover all levels.
_levelPart(array<int> mandatory, int total, int part) =>
    boundary = 0
    reached = 0
    while reached * 10 < total * part
        reached += mandatory.get(boundary)
        boundary += 1
    boundary
 
// Emit one level range and flush each level. The first batch initializes
// chain storage; the last validates the drawing count.
_emitLargePrograms(Canvas canvas, _Frame frame, int part) =>
    _CanvasScratch scratch = canvas._scratch
    Style style = frame.style
    rows = frame.rows
    columns = frame.columns
    if part == 0
        _beginChains(scratch, rows)
    mandatory = scratch.largeLevelMandatoryDrawings
    total = mandatory.sum()
    levelFrom = _levelPart(mandatory, total, part)
    levelTo = _levelPart(mandatory, total, part + 1)
    // Give each unit its own drawing when the budget permits.
    roomForAll = scratch.largeLevelRenderUnits.sum() <= style.drawingLimit
    // Guard empty ranges because Pine otherwise iterates in descending order.
    for level = levelFrom to levelTo - 1
        if levelTo > levelFrom and _largeLevelVisible(style, level)
            component = scratch.largeLevelFirst.get(level)
            while component >= 0
                [firstFragment, fragmentCount] =
                  _componentFragmentRange(scratch, component)
                if fragmentCount > 0
                    for unit = 0 to fragmentCount - 1
                        fragmentIndex = firstFragment + unit
                        _Fragment fragment =
                          scratch.largeFragments.get(fragmentIndex)
                        _packLargeUnit(
                          canvas, scratch,
                          scratch.largeFragmentVertices,
                          scratch.largeFragmentLoopStart,
                          scratch.largeFragmentLoopEnd,
                          _pagesGet(
                            scratch.largeFragmentFirstLoop, fragmentIndex),
                          _pagesGet(
                            scratch.largeFragmentLoopCount, fragmentIndex),
                          fragment.exactPoints, level, frame, roomForAll)
                else
                    unitPoints = _traceLargeComponent(
                      scratch, component, level, rows, columns)
                    _packLargeUnit(
                      canvas, scratch,
                      scratch.largeTraceVertices,
                      scratch.largeTraceLoopStart,
                      scratch.largeTraceLoopEnd,
                      0, scratch.largeTraceLoopStart.size, unitPoints,
                      level, frame, roomForAll)
                component := _pagesGet(
                  scratch.largeComponentNext, component)
            _emitWorldChain(canvas, level, frame)
    if part == 9
        _requireDrawingRoom(scratch, style)
    canvas.drawings.size()
 
_prepareLargeFrame(
  Canvas canvas,
  _Frame frame,
  bool generatedCoordinates,
  bool scalar
  ) =>
    xEdges = frame.xEdges
    yEdges = frame.yEdges
    rows = frame.rows
    columns = frame.columns
    _validatePalette(frame.gradient)
    _validateStyle(frame.style)
    _validateCoordinateMode(
      xEdges, yEdges, frame.timeCoordinates, generatedCoordinates)
    if xEdges.size() != columns + 1 or yEdges.size() != rows + 1
        runtime.error(
          "field/edge dimensions differ")
    if scalar and frame.style.colorLevels > rows * columns
        runtime.error("colorLevels exceeds cell count")
    _CanvasScratch scratch = _ensureScratch(canvas)
    if na(canvas.drawings)
        canvas.drawings := array.new<polyline>()
    comparable = scratch.lastLargeField and
      rows == scratch.lastRows and columns == scratch.lastColumns and
      not na(scratch.largeBins)
    detectedShift = comparable ?
      _horizontalEdgeShift(xEdges, scratch.lastXEdges, columns) : 0
    tentativeOrigin = comparable ?
      scratch.worldOrigin + detectedShift : GENERIC_WORLD_ORIGIN
    [scratch, comparable, detectedShift, tentativeOrigin]
 
_prepareLargeBins(_CanvasScratch scratch, int rows, int columns) =>
    tileCount = int((rows + TILE_SIZE - 1) / TILE_SIZE) *
      int((columns + TILE_SIZE - 1) / TILE_SIZE)
    _prepareLargeCandidates(scratch, tileCount)
    _swapLargeBins(scratch, rows, columns)
 
// Compile independent tiles in twelve interleaved batches to distribute
// work across separate outer loops.
_compileLargeTiles(_CanvasScratch scratch, int part) =>
    dirty = scratch.dirtyTileSlots
    count = dirty.size()
    _IntPlane bins = scratch.largeBins
    if count > part
        for index = part to count - 1 by 12
            _compileTileLarge(
              scratch, scratch.tilePrograms.get(dirty.get(index)),
              bins, bins.rows, bins.columns)
    0
 
_finishLargeRender(
  Canvas canvas,
  _Frame frame,
  bool foundValues,
  float scaleMin,
  float scaleMax,
  bool comparable,
  int tentativeOrigin,
  int originShift,
  int sameChanges,
  int shiftedChanges,
  bool keepLogical
  ) =>
    _CanvasScratch scratch = canvas._scratch
    Style style = frame.style
    rows = frame.rows
    columns = frame.columns
    currentWorldOrigin = originShift != 0 and keepLogical ?
      scratch.worldOrigin : tentativeOrigin
    _prepareTileDirectory(
      scratch, rows, columns, currentWorldOrigin)
    if not comparable
        for slot in scratch.activeTileSlots
            _markTileSlotDirty(scratch, slot)
        scratch.dirtyCellCount := rows * columns
    else
        _applyLargeCandidates(scratch, keepLogical, columns)
        scratch.dirtyCellCount := keepLogical ? sameChanges : shiftedChanges
 
    styleKey = _renderStyleKey(frame)
    binsEqual = comparable and scratch.dirtyCellCount == 0
    cacheHit = scratch.lastLargeField and scratch.lastDrawCount >= 0 and binsEqual
    if cacheHit
        cacheHit := _sameFrameIdentity(canvas, scratch, frame, styleKey)
    geometryReusable = scratch.lastLargeField and binsEqual and
      scratch.lastStyleKey % 128 == style.colorLevels and
      not na(scratch.largeComponentRoot)
    scratch.lastLargeField := true
    if cacheHit
        0
    else
        componentCount = scratch.lastComponentCount
        if not geometryReusable
            _compileLargeTiles(scratch, 0)
            _compileLargeTiles(scratch, 1)
            _compileLargeTiles(scratch, 2)
            _compileLargeTiles(scratch, 3)
            _compileLargeTiles(scratch, 4)
            _compileLargeTiles(scratch, 5)
            _compileLargeTiles(scratch, 6)
            _compileLargeTiles(scratch, 7)
            _compileLargeTiles(scratch, 8)
            _compileLargeTiles(scratch, 9)
            _compileLargeTiles(scratch, 10)
            _compileLargeTiles(scratch, 11)
            _buildLargeOwnership(scratch, rows, columns)
            componentCount := _buildLargeComponentDirectory(
              scratch, rows, columns, style.colorLevels)
            _buildLargeChainCsr(
              scratch, componentCount, columns)
            componentCount := _preflightLargePartitions(
              scratch, componentCount, rows, columns, style.colorLevels)
            scratch.lastComponentCount := componentCount
        _largeDrawingCount(scratch, style.colorLevels, style)
        // Preflight failures preserve the previous drawings. Emission validates
        // the final packed drawing count.
        _clearDrawings(canvas)
        if componentCount > 0
            // Emit ten level ranges in separate outer loops.
            _emitLargePrograms(canvas, frame, 0)
            _emitLargePrograms(canvas, frame, 1)
            _emitLargePrograms(canvas, frame, 2)
            _emitLargePrograms(canvas, frame, 3)
            _emitLargePrograms(canvas, frame, 4)
            _emitLargePrograms(canvas, frame, 5)
            _emitLargePrograms(canvas, frame, 6)
            _emitLargePrograms(canvas, frame, 7)
            _emitLargePrograms(canvas, frame, 8)
            _emitLargePrograms(canvas, frame, 9)
        _storeFrameIdentity(scratch, frame, styleKey, canvas.drawings.size())
    _commitFrame(
      canvas, scratch, frame, foundValues, scaleMin, scaleMax,
      currentWorldOrigin, false)
 
// ============================================================================
// SOURCE RENDERING
// ============================================================================
//
// Source adapters provide bands, row stride, band height, and chronological
// runs. Flat layouts use the flat renderer; other layouts use the large
// renderer. Reuse direct storage when it already matches logical order.
 
_renderLargeValueRuns(
  Canvas canvas,
  array<ValueBand> bands,
  int bandHeight,
  int stride,
  int rows,
  int columns,
  int firstStart,
  int firstCount,
  int secondCount,
  array<int> xEdges,
  array<float> yEdges,
  array<color> gradient,
  Style requestedStyle,
  bool timeCoordinates,
  bool generatedCoordinates
  ) =>
    Style style = _styleOrDefault(requestedStyle)
    _Frame frame = _Frame.new(
      xEdges, yEdges, gradient, style, false, timeCoordinates, rows, columns)
    [scratch, comparable, detectedShift, tentativeOrigin] =
      _prepareLargeFrame(canvas, frame, generatedCoordinates, true)
    _prepareLargeBins(scratch, rows, columns)
    autoScale = style.autoScale
    scaleMin = autoScale ? na : style.valueMin
    scaleMax = autoScale ? na : style.valueMax
    foundValues = not autoScale
    if autoScale
        // Native extrema ignore the na cells in unwritten ring columns.
        for band in bands
            localMin = band.values.min()
            localMax = band.values.max()
            if not na(localMax)
                scaleMin := na(scaleMin) ?
                  localMin : math.min(scaleMin, localMin)
                scaleMax := na(scaleMax) ?
                  localMax : math.max(scaleMax, localMax)
        foundValues := not na(scaleMax)
    [sameChanges, shiftedChanges, keepLogical] = _quantizeLargeValueRuns(
      scratch, bands, bandHeight, stride, columns,
      firstStart, firstCount, secondCount, style,
      autoScale and style.scaleMode != ScaleMode.wholeGrid,
      autoScale and style.scaleMode == ScaleMode.eachColumn,
      scaleMin, scaleMax, comparable, detectedShift)
    _finishLargeRender(
      canvas, frame, foundValues, scaleMin, scaleMax, comparable,
      tentativeOrigin, detectedShift,
      sameChanges, shiftedChanges, keepLogical)
 
_renderLargePaletteRuns(
  Canvas canvas,
  array<PaletteBand> bands,
  int bandHeight,
  int stride,
  int rows,
  int columns,
  int firstStart,
  int firstCount,
  int secondCount,
  array<int> xEdges,
  array<float> yEdges,
  array<color> gradient,
  Style style,
  bool timeCoordinates,
  bool generatedCoordinates
  ) =>
    _Frame frame = _Frame.new(
      xEdges, yEdges, gradient, style, true, timeCoordinates, rows, columns)
    [scratch, comparable, detectedShift, tentativeOrigin] =
      _prepareLargeFrame(canvas, frame, generatedCoordinates, false)
    _prepareLargeBins(scratch, rows, columns)
    [foundValues, sameChanges, shiftedChanges, keepLogical] =
      _quantizeLargePaletteRuns(
        scratch, bands, bandHeight, stride, columns,
        firstStart, firstCount, secondCount,
        style.colorLevels, comparable, detectedShift)
    _finishLargeRender(
      canvas, frame, foundValues, 0.0, style.colorLevels - 1.0, comparable,
      tentativeOrigin, detectedShift,
      sameChanges, shiftedChanges, keepLogical)
 
_renderValueSource(
  Canvas canvas,
  array<ValueBand> bands,
  int bandHeight,
  int stride,
  int rows,
  int columns,
  int origin,
  int firstStart,
  int firstCount,
  int secondCount,
  bool rolling,
  array<int> xEdges,
  array<float> yEdges,
  array<color> gradient,
  Style style,
  bool timeCoordinates,
  bool generatedCoordinates
  ) =>
    _validateFieldEdgeCapacity(rows, columns)
    // Use direct storage for matching flat layouts. Flat rolling sources may
    // be materialized; multi-band fixed fields use the large renderer.
    direct = bands.size() == 1 and
      _contiguousRuns(stride, columns, firstStart, secondCount)
    if rows * columns <= FLAT_CELL_LIMIT and (direct or rolling)
        // Materialize only sources that require chronological reconstruction.
        array<float> cells = na
        if direct
            cells := bands.get(0).values
        else
            cells := _materializeValueRuns(
              _ensureScratch(canvas), bands, stride,
              firstStart, firstCount, secondCount)
        _renderFlat(
          canvas, cells, xEdges, yEdges, gradient, style,
          timeCoordinates, generatedCoordinates,
          producerOrigin = origin)
    else
        _renderLargeValueRuns(
          canvas, bands, bandHeight, stride, rows, columns,
          firstStart, firstCount, secondCount,
          xEdges, yEdges, gradient, style,
          timeCoordinates, generatedCoordinates)
 
_renderPaletteSource(
  Canvas canvas,
  array<PaletteBand> bands,
  int bandHeight,
  int stride,
  int rows,
  int columns,
  int origin,
  int firstStart,
  int firstCount,
  int secondCount,
  bool rolling,
  array<int> xEdges,
  array<float> yEdges,
  array<color> gradient,
  Style style,
  bool timeCoordinates,
  bool generatedCoordinates
  ) =>
    _validateFieldEdgeCapacity(rows, columns)
    direct = bands.size() == 1 and
      _contiguousRuns(stride, columns, firstStart, secondCount)
    if rows * columns <= FLAT_CELL_LIMIT and (direct or rolling)
        array<float> noValues = na
        array<int> cells = na
        if direct
            cells := bands.get(0).values
        else
            cells := _materializePaletteRuns(
              _ensureScratch(canvas), bands, stride,
              firstStart, firstCount, secondCount)
        _renderFlat(
          canvas, noValues, xEdges, yEdges, gradient, style,
          timeCoordinates, generatedCoordinates, cells,
          producerOrigin = origin)
    else
        _renderLargePaletteRuns(
          canvas, bands, bandHeight, stride, rows, columns,
          firstStart, firstCount, secondCount,
          xEdges, yEdges, gradient, style,
          timeCoordinates, generatedCoordinates)
 
// ----------------------------------------------------------------------------
// Source adapters
// ----------------------------------------------------------------------------
//
// Validate source band layout once per draw. E15/E17 indicate invalid band
// metadata; E16/E18 indicate incorrect band bounds or storage sizes for
// value and palette fields, respectively.
 
_validateValueLayout(ValueField source) =>
    bandRows = _calcBandRows(source.columns)
    expected = int((source.rows + bandRows - 1) / bandRows)
    if na(source.bands) or source.bandHeight != bandRows or
      source.bands.size() != expected
        runtime.error("E15")
    for bandIndex = 0 to expected - 1
        ValueBand band = source.bands.get(bandIndex)
        rowStart = bandIndex * bandRows
        rowCount = math.min(bandRows, source.rows - rowStart)
        if band.rowStart != rowStart or band.rowCount != rowCount or
          na(band.values) or band.values.size() != rowCount * source.columns
            runtime.error("E16")
    0
 
_validatePaletteLayout(PaletteField source) =>
    bandRows = _calcBandRows(source.columns)
    expected = int((source.rows + bandRows - 1) / bandRows)
    if na(source.bands) or source.bandHeight != bandRows or
      source.bands.size() != expected
        runtime.error("E17")
    for bandIndex = 0 to expected - 1
        PaletteBand band = source.bands.get(bandIndex)
        rowStart = bandIndex * bandRows
        rowCount = math.min(bandRows, source.rows - rowStart)
        if band.rowStart != rowStart or band.rowCount != rowCount or
          na(band.values) or band.values.size() != rowCount * source.columns
            runtime.error("E18")
    0
 
_renderValueField(
  Canvas canvas,
  ValueField source,
  array<int> xEdges,
  array<float> yEdges,
  array<color> gradient,
  Style style,
  bool timeCoordinates,
  bool generatedCoordinates = false
  ) =>
    _validateFieldDimensions(source.rows, source.columns)
    _validateValueLayout(source)
    _renderValueSource(
      canvas, source.bands, source.bandHeight, source.columns,
      source.rows, source.columns, int(na),
      0, source.columns, 0, false,
      xEdges, yEdges, gradient, style,
      timeCoordinates, generatedCoordinates)
 
_renderPaletteField(
  Canvas canvas,
  PaletteField source,
  array<int> xEdges,
  array<float> yEdges,
  array<color> gradient,
  Style style,
  bool timeCoordinates,
  bool generatedCoordinates = false
  ) =>
    _validateFieldDimensions(source.rows, source.columns)
    _validatePaletteLayout(source)
    _renderPaletteSource(
      canvas, source.bands, source.bandHeight, source.columns,
      source.rows, source.columns, int(na),
      0, source.columns, 0, false,
      xEdges, yEdges, gradient, style,
      timeCoordinates, generatedCoordinates)
 
_renderValueScroll(
  Canvas canvas,
  ValueScroll source,
  array<int> xEdges,
  array<float> yEdges,
  array<color> gradient,
  Style style,
  bool timeCoordinates,
  bool generatedCoordinates = false
  ) =>
    [firstStart, firstCount, secondCount] =
      _scrollRuns(source.written, source.capacity, source.head)
    _renderValueSource(
      canvas, source.bands, source.bandHeight, source.capacity,
      source.rows, source.written, source.origin,
      firstStart, firstCount, secondCount, true,
      xEdges, yEdges, gradient, style,
      timeCoordinates, generatedCoordinates)
 
_renderPaletteScroll(
  Canvas canvas,
  PaletteScroll source,
  array<int> xEdges,
  array<float> yEdges,
  array<color> gradient,
  Style style,
  bool timeCoordinates,
  bool generatedCoordinates = false
  ) =>
    [firstStart, firstCount, secondCount] =
      _scrollRuns(source.written, source.capacity, source.head)
    _renderPaletteSource(
      canvas, source.bands, source.bandHeight, source.capacity,
      source.rows, source.written, source.origin,
      firstStart, firstCount, secondCount, true,
      xEdges, yEdges, gradient, style,
      timeCoordinates, generatedCoordinates)
 
// ============================================================================
// CONSTRUCTORS AND LIFECYCLE
// ============================================================================
 
//@function Creates a rendering Style.
//@param colorLevels Number of sampled gradient colors, from 2 to 100.
//@param lowOpacity Visible opacity at the lowest color, from 0 to 100.
//@param highOpacity Visible opacity at the highest color, from 0 to 100.
//@param autoScale Automatically derive valueMin/valueMax from finite cell values.
//@param valueMin Manual value mapped to 0 when autoScale is false.
//@param valueMax Manual value mapped to 1. Must exceed valueMin when autoScale is false.
//@param gamma Positive exponent applied to normalized values. Below 1 emphasizes lower values.
//@param logarithmicY Use logarithmic spacing for regular Y edges. Requires positive Y bounds.
//@param invertRows Map row 0 to the top of the rendered field.
//@param forceOverlay Draw in the main chart pane.
//@param scaleMode Normalize the whole grid, each column, or each row when autoScale is true.
//@param drawingLimit Maximum polylines this Canvas may own, from 1 to 100.
//@returns A configured Style.
export newStyle(
  int colorLevels = 64,
  float lowOpacity = 15.0,
  float highOpacity = 90.0,
  bool autoScale = false,
  float valueMin = 0.0,
  float valueMax = 1.0,
  float gamma = 1.0,
  bool logarithmicY = false,
  bool invertRows = false,
  bool forceOverlay = false,
  ScaleMode scaleMode = ScaleMode.wholeGrid,
  int drawingLimit = 100
  ) =>
    Style result = Style.new(
      colorLevels,
      lowOpacity,
      highOpacity,
      autoScale,
      valueMin,
      valueMax,
      gamma,
      logarithmicY,
      invertRows,
      forceOverlay,
      scaleMode,
      drawingLimit)
    _validateStyle(result)
    result
 
_newCanvas(array<color> colors, bool scalarDefaults) =>
    Canvas result = Canvas.new()
    result.drawings := array.new<polyline>()
    if na(colors)
        if scalarDefaults
            result.colors := _defaultGradient()
        else
            result.colors := array.from(color.black, color.white)
    else
        _validatePalette(colors)
        result.colors := colors.copy()
    if scalarDefaults
        result.style := _canvasStyle(true)
    else
        result.style := _canvasStyle()
        result.style.colorLevels := result.colors.size()
    result
 
//@function Creates a Canvas with full opacity and a fixed value range of 0 to 1.
//@param colors Gradient stops or exact palette colors. na selects black and white.
//@returns A configured Canvas.
export newCanvas(array<color> colors = na) =>
    _newCanvas(colors, false)
 
//@function Creates a Canvas with automatic scaling, 64 color levels, and 15% to 90% opacity.
//@param colors Gradient stops for value sources. na selects the built-in thermal gradient.
//@returns A heatmap-configured Canvas.
export heatmap(array<color> colors = na) =>
    _newCanvas(colors, true)
 
// ============================================================================
// FIXED SOURCES
// ============================================================================
//
// Use set() for individual cells, row() for a writable row view, and band()
// for direct access to complete rows in a storage band. All three update
// the same field storage.
 
//@function Creates a fixed field of continuous values.
//@param rows Number of rows, at least 1.
//@param columns Number of columns, from 1 to 100,000.
//@param initial Value written into every cell. na is transparent.
//@returns A new ValueField.
export valueField(int rows, int columns, float initial = na) =>
    bandRows = _validateFieldDimensions(rows, columns)
    ValueField result = ValueField.new(rows, columns, bandRows,
      array.new<ValueBand>())
    bandCount = int((rows + bandRows - 1) / bandRows)
    for bandIndex = 0 to bandCount - 1
        rowStart = bandIndex * bandRows
        rowCount = math.min(bandRows, rows - rowStart)
        result.bands.push(ValueBand.new(
          rowStart, rowCount,
          array.new_float(rowCount * columns, initial)))
    result
 
//@function Creates a fixed field of exact palette indices.
//@param rows Number of rows, at least 1.
//@param columns Number of columns, from 1 to 100,000.
//@param initial Palette index written into every cell. -1 is transparent.
//@returns A new PaletteField.
export paletteField(int rows, int columns, int initial = -1) =>
    bandRows = _validateFieldDimensions(rows, columns)
    PaletteField result = PaletteField.new(rows, columns, bandRows,
      array.new<PaletteBand>())
    bandCount = int((rows + bandRows - 1) / bandRows)
    for bandIndex = 0 to bandCount - 1
        rowStart = bandIndex * bandRows
        rowCount = math.min(bandRows, rows - rowStart)
        result.bands.push(PaletteBand.new(
          rowStart, rowCount,
          array.new_int(rowCount * columns, initial)))
    result
 
_validateFieldCell(int rows, int columns, int row, int column) =>
    if row < 0 or row >= rows or column < 0 or column >= columns
        runtime.error("field cell out of bounds")
    0
 
_validateFieldRow(int rows, int row) =>
    if row < 0 or row >= rows
        runtime.error("field row out of bounds")
    0
 
//@function Returns the value stored at a row and column.
//@param self Field to read.
//@param row Zero-based row index. Row 0 is the bottom row unless invertRows is set.
//@param column Zero-based column index.
//@returns The stored value, or na when the cell is transparent.
export method get(ValueField self, int row, int column) =>
    _validateFieldCell(self.rows, self.columns, row, column)
    ValueBand band = self.bands.get(int(row / self.bandHeight))
    band.values.get((row - band.rowStart) * self.columns + column)
 
//@function Sets the value at a row and column.
//@param self Field to write.
//@param row Zero-based row index.
//@param column Zero-based column index.
//@param value Cell value, or na for transparent.
//@returns Self for chaining.
export method set(ValueField self, int row, int column, float value) =>
    _validateFieldCell(self.rows, self.columns, row, column)
    ValueBand band = self.bands.get(int(row / self.bandHeight))
    band.values.set((row - band.rowStart) * self.columns + column, value)
    self
 
//@function Returns the value stored at a row and column.
//@param self Field to read.
//@param row Zero-based row index.
//@param column Zero-based column index.
//@returns The stored palette index. -1 and na are transparent.
export method get(PaletteField self, int row, int column) =>
    _validateFieldCell(self.rows, self.columns, row, column)
    PaletteBand band = self.bands.get(int(row / self.bandHeight))
    band.values.get((row - band.rowStart) * self.columns + column)
 
//@function Sets the value at a row and column.
//@param self Field to write.
//@param row Zero-based row index.
//@param column Zero-based column index.
//@param value Palette index, or -1 for transparent.
//@returns Self for chaining.
export method set(PaletteField self, int row, int column, int value) =>
    _validateFieldCell(self.rows, self.columns, row, column)
    PaletteBand band = self.bands.get(int(row / self.bandHeight))
    band.values.set((row - band.rowStart) * self.columns + column, value)
    self
 
 
//@function Writes one value into every cell.
//@param self Field to fill.
//@param value Cell value, or na for transparent.
//@returns Self for chaining.
export method fill(ValueField self, float value) =>
    count = self.bands.size()
    if count > 0
        last = count - 1
        for bandIndex = 0 to last
            ValueBand band = self.bands.get(bandIndex)
            array<float> cells = band.values
            cells.fill(value)
    self
 
//@function Writes one palette index into every cell.
//@param self Field to fill.
//@param value Palette index, or -1 for transparent.
//@returns Self for chaining.
export method fill(PaletteField self, int value) =>
    count = self.bands.size()
    if count > 0
        last = count - 1
        for bandIndex = 0 to last
            PaletteBand band = self.bands.get(bandIndex)
            array<int> cells = band.values
            cells.fill(value)
    self
 
// Rows are writable slices of their backing bands. Do not resize, clear,
// or append to the returned arrays.
 
//@function Returns one complete row as a writable view of the field's storage.
//@param self Field to address.
//@param row Zero-based row index.
//@returns A writable array<float> view of self.columns cells. Do not resize it.
export method row(ValueField self, int row) =>
    _validateFieldRow(self.rows, row)
    ValueBand band = self.bands.get(int(row / self.bandHeight))
    base = (row - band.rowStart) * self.columns
    band.values.slice(base, base + self.columns)
 
//@function Returns one complete row as a writable view of the field's storage.
//@param self Field to address.
//@param row Zero-based row index.
//@returns A writable array<int> view of self.columns cells. Do not resize it.
export method row(PaletteField self, int row) =>
    _validateFieldRow(self.rows, row)
    PaletteBand band = self.bands.get(int(row / self.bandHeight))
    base = (row - band.rowStart) * self.columns
    band.values.slice(base, base + self.columns)
 
// Band arrays store complete rows in row-major order. For a field cell,
// the band offset is (row - bandStart(index)) * self.columns + column.
 
//@function Returns how many physical storage bands this field holds.
//@param self Field to inspect.
//@returns Band count, at least 1.
export method bandCount(ValueField self) => self.bands.size()
 
//@function Returns a storage band's writable backing array.
//@param self Field to address.
//@param index Zero-based storage band index.
//@returns The band's row-major array<float>. Writes update the field; do not resize it.
export method band(ValueField self, int index) =>
    self.bands.get(index).values
 
//@function Returns a band's first logical row.
//@param self Field to address.
//@param index Zero-based storage band index.
//@returns The global row index of the band's first row.
export method bandStart(ValueField self, int index) =>
    self.bands.get(index).rowStart
 
//@function Returns how many complete rows a band stores.
//@param self Field to address.
//@param index Zero-based storage band index.
//@returns The band's row count.
export method bandRows(ValueField self, int index) =>
    self.bands.get(index).rowCount
 
//@function Returns how many physical storage bands this field holds.
//@param self Field to inspect.
//@returns Band count, at least 1.
export method bandCount(PaletteField self) => self.bands.size()
 
//@function Returns a storage band's writable backing array.
//@param self Field to address.
//@param index Zero-based storage band index.
//@returns The band's row-major array<int>. Writes update the field; do not resize it.
export method band(PaletteField self, int index) =>
    self.bands.get(index).values
 
//@function Returns a band's first logical row.
//@param self Field to address.
//@param index Zero-based storage band index.
//@returns The global row index of the band's first row.
export method bandStart(PaletteField self, int index) =>
    self.bands.get(index).rowStart
 
//@function Returns how many complete rows a band stores.
//@param self Field to address.
//@param index Zero-based storage band index.
//@returns The band's row count.
export method bandRows(PaletteField self, int index) =>
    self.bands.get(index).rowCount
 
// ============================================================================
// FIELD STAMPING
// ============================================================================
//
// Field stamps modify cells directly and clip to the field bounds.
// Coordinates are row and column indices; na and -1 remain the transparent
// values for value and palette fields, respectively.
 
_lineStampPlan(int row0, int column0, int row1, int column1) =>
    flip = row1 < row0 or (row1 == row0 and column1 < column0)
    startRow = flip ? row1 : row0
    startColumn = flip ? column1 : column0
    endRow = flip ? row0 : row1
    endColumn = flip ? column0 : column1
    rowSpan = math.abs(endRow - startRow)
    columnSpan = math.abs(endColumn - startColumn)
    [startRow, startColumn,
     endRow >= startRow ? 1 : -1,
     endColumn >= startColumn ? 1 : -1,
     rowSpan, columnSpan, columnSpan - rowSpan,
     math.max(rowSpan, columnSpan)]
 
//@function Stamps a rectangle, clipped to the field's bounds.
// Corner order is unrestricted. Outlines retain only the original perimeter
// within the field bounds; clipping does not add a border.
//@param self Field to write into.
//@param row0 First corner row.
//@param column0 First corner column.
//@param row1 Opposite corner row.
//@param column1 Opposite corner column.
//@param value Cell value, or na for transparent.
//@param filled True fills the rectangle; false draws only its outline.
//@returns Self for chaining.
export method rect(
  ValueField self,
  int row0,
  int column0,
  int row1,
  int column1,
  float value,
  bool filled = true
  ) =>
    columns = self.columns
    bandHeight = self.bandHeight
    firstRow = math.min(row0, row1)
    lastRow = math.max(row0, row1)
    firstColumn = math.min(column0, column1)
    lastColumn = math.max(column0, column1)
    lowRow = math.max(0, firstRow)
    highRow = math.min(self.rows - 1, lastRow)
    lowColumn = math.max(0, firstColumn)
    highColumn = math.min(columns - 1, lastColumn)
    if lowRow <= highRow and lowColumn <= highColumn
        for row = lowRow to highRow
            ValueBand band = self.bands.get(int(row / bandHeight))
            array<float> cells = band.values
            base = (row - band.rowStart) * columns
            if filled or row == firstRow or row == lastRow
                cells.fill(value, base + lowColumn, base + highColumn + 1)
            else
                if firstColumn >= 0 and firstColumn < columns
                    cells.set(base + firstColumn, value)
                if lastColumn != firstColumn and lastColumn >= 0 and lastColumn < columns
                    cells.set(base + lastColumn, value)
    self
 
//@function Stamps a rectangle, clipped to the field's bounds.
//@param self Field to write into.
//@param row0 First corner row.
//@param column0 First corner column.
//@param row1 Opposite corner row.
//@param column1 Opposite corner column.
//@param value Palette index, or -1 for transparent.
//@param filled True fills the rectangle; false draws only its outline.
//@returns Self for chaining.
export method rect(
  PaletteField self,
  int row0,
  int column0,
  int row1,
  int column1,
  int value,
  bool filled = true
  ) =>
    columns = self.columns
    bandHeight = self.bandHeight
    firstRow = math.min(row0, row1)
    lastRow = math.max(row0, row1)
    firstColumn = math.min(column0, column1)
    lastColumn = math.max(column0, column1)
    lowRow = math.max(0, firstRow)
    highRow = math.min(self.rows - 1, lastRow)
    lowColumn = math.max(0, firstColumn)
    highColumn = math.min(columns - 1, lastColumn)
    if lowRow <= highRow and lowColumn <= highColumn
        for row = lowRow to highRow
            PaletteBand band = self.bands.get(int(row / bandHeight))
            array<int> cells = band.values
            base = (row - band.rowStart) * columns
            if filled or row == firstRow or row == lastRow
                cells.fill(value, base + lowColumn, base + highColumn + 1)
            else
                if firstColumn >= 0 and firstColumn < columns
                    cells.set(base + firstColumn, value)
                if lastColumn != firstColumn and lastColumn >= 0 and lastColumn < columns
                    cells.set(base + lastColumn, value)
    self
 
//@function Stamps a straight line segment, clipped to the field's bounds.
// Canonical endpoint order makes Bresenham ties independent of call direction.
//@param self Field to write into.
//@param row0 Start row.
//@param column0 Start column.
//@param row1 End row.
//@param column1 End column.
//@param value Cell value, or na for transparent.
//@returns Self for chaining.
export method segment(
  ValueField self,
  int row0,
  int column0,
  int row1,
  int column1,
  float value
  ) =>
    rows = self.rows
    columns = self.columns
    if math.max(row0, row1) >= 0 and math.min(row0, row1) < rows and
      math.max(column0, column1) >= 0 and math.min(column0, column1) < columns
        bandHeight = self.bandHeight
        [row, column, rowStep, columnStep,
         rowSpan, columnSpan, drift, steps] =
          _lineStampPlan(row0, column0, row1, column1)
        array<float> cells = na
        cachedRow = -1
        base = 0
        for step = 0 to steps
            if row >= 0 and row < rows and column >= 0 and column < columns
                if row != cachedRow
                    ValueBand band = self.bands.get(int(row / bandHeight))
                    cells := band.values
                    base := (row - band.rowStart) * columns
                    cachedRow := row
                cells.set(base + column, value)
            doubled = drift * 2
            if doubled > -rowSpan
                drift -= rowSpan
                column += columnStep
            if doubled < columnSpan
                drift += columnSpan
                row += rowStep
    self
 
//@function Stamps a straight line segment, clipped to the field's bounds.
// Canonical endpoint order preserves the same cells when the ends are swapped.
//@param self Field to write into.
//@param row0 Start row.
//@param column0 Start column.
//@param row1 End row.
//@param column1 End column.
//@param value Palette index, or -1 for transparent.
//@returns Self for chaining.
export method segment(
  PaletteField self,
  int row0,
  int column0,
  int row1,
  int column1,
  int value
  ) =>
    rows = self.rows
    columns = self.columns
    if math.max(row0, row1) >= 0 and math.min(row0, row1) < rows and
      math.max(column0, column1) >= 0 and math.min(column0, column1) < columns
        bandHeight = self.bandHeight
        [row, column, rowStep, columnStep,
         rowSpan, columnSpan, drift, steps] =
          _lineStampPlan(row0, column0, row1, column1)
        array<int> cells = na
        cachedRow = -1
        base = 0
        for step = 0 to steps
            if row >= 0 and row < rows and column >= 0 and column < columns
                if row != cachedRow
                    PaletteBand band = self.bands.get(int(row / bandHeight))
                    cells := band.values
                    base := (row - band.rowStart) * columns
                    cachedRow := row
                cells.set(base + column, value)
            doubled = drift * 2
            if doubled > -rowSpan
                drift -= rowSpan
                column += columnStep
            if doubled < columnSpan
                drift += columnSpan
                row += rowStep
    self
 
//@function Stamps a circle, clipped to the field's bounds.
// Squared distance selects the disc or one-cell ring. A circle in cell
// coordinates appears round only when the displayed cells are square.
//@param self Field to write into.
//@param centerRow Center row.
//@param centerColumn Center column.
//@param radius Radius in cells. Negative radii do nothing; 0 writes only when filled is true.
//@param value Cell value, or na for transparent.
//@param filled True fills the disc; false draws only the ring.
//@returns Self for chaining.
export method circle(
  ValueField self,
  int centerRow,
  int centerColumn,
  int radius,
  float value,
  bool filled = false
  ) =>
    if radius >= 0
        columns = self.columns
        bandHeight = self.bandHeight
        lowRow = math.max(0, centerRow - radius)
        highRow = math.min(self.rows - 1, centerRow + radius)
        lowColumn = math.max(0, centerColumn - radius)
        highColumn = math.min(columns - 1, centerColumn + radius)
        if lowRow <= highRow and lowColumn <= highColumn
            limit = radius * radius
            inner = (radius - 1) * (radius - 1)
            for row = lowRow to highRow
                ValueBand band = self.bands.get(int(row / bandHeight))
                array<float> cells = band.values
                base = (row - band.rowStart) * columns
                rowGap = row - centerRow
                rowDistance = rowGap * rowGap
                for column = lowColumn to highColumn
                    columnGap = column - centerColumn
                    distance = rowDistance + columnGap * columnGap
                    if distance <= limit and (filled or distance > inner)
                        cells.set(base + column, value)
    self
 
//@function Stamps a circle, clipped to the field's bounds.
//@param self Field to write into.
//@param centerRow Center row.
//@param centerColumn Center column.
//@param radius Radius in cells. Negative radii do nothing; 0 writes only when filled is true.
//@param value Palette index, or -1 for transparent.
//@param filled True fills the disc; false draws only the ring.
//@returns Self for chaining.
export method circle(
  PaletteField self,
  int centerRow,
  int centerColumn,
  int radius,
  int value,
  bool filled = false
  ) =>
    if radius >= 0
        columns = self.columns
        bandHeight = self.bandHeight
        lowRow = math.max(0, centerRow - radius)
        highRow = math.min(self.rows - 1, centerRow + radius)
        lowColumn = math.max(0, centerColumn - radius)
        highColumn = math.min(columns - 1, centerColumn + radius)
        if lowRow <= highRow and lowColumn <= highColumn
            limit = radius * radius
            inner = (radius - 1) * (radius - 1)
            for row = lowRow to highRow
                PaletteBand band = self.bands.get(int(row / bandHeight))
                array<int> cells = band.values
                base = (row - band.rowStart) * columns
                rowGap = row - centerRow
                rowDistance = rowGap * rowGap
                for column = lowColumn to highColumn
                    columnGap = column - centerColumn
                    distance = rowDistance + columnGap * columnGap
                    if distance <= limit and (filled or distance > inner)
                        cells.set(base + column, value)
    self
 
// ============================================================================
// ROLLING SOURCES
// ============================================================================
//
// Rolling sources append columns to a banded ring buffer. Once full, push()
// overwrites the oldest column. Push on barstate.isconfirmed to retain one
// column per completed bar.
 
//@function Creates a rolling field of continuous value columns.
//@param rows Number of rows per column, from 2 to 99,999.
//@param capacity Maximum columns retained, from 2 to 99,999.
//@returns An empty ValueScroll.
export valueScroll(int rows, int capacity) =>
    _validateScrollDimensions(rows, capacity)
    bandRows = _calcBandRows(capacity)
    ValueScroll result = ValueScroll.new(rows, capacity, 0, 0, 0, 0,
      bandRows, array.new<ValueBand>())
    bandCount = int((rows + bandRows - 1) / bandRows)
    for bandIndex = 0 to bandCount - 1
        rowStart = bandIndex * bandRows
        rowCount = math.min(bandRows, rows - rowStart)
        result.bands.push(ValueBand.new(
          rowStart, rowCount,
          array.new_float(rowCount * capacity, na)))
    result
 
//@function Creates a rolling field of exact palette-index columns.
//@param rows Number of rows per column, from 2 to 99,999.
//@param capacity Maximum columns retained, from 2 to 99,999.
//@returns An empty PaletteScroll.
export paletteScroll(int rows, int capacity) =>
    _validateScrollDimensions(rows, capacity)
    bandRows = _calcBandRows(capacity)
    PaletteScroll result = PaletteScroll.new(rows, capacity, 0, 0, 0, 0,
      bandRows, array.new<PaletteBand>())
    bandCount = int((rows + bandRows - 1) / bandRows)
    for bandIndex = 0 to bandCount - 1
        rowStart = bandIndex * bandRows
        rowCount = math.min(bandRows, rows - rowStart)
        result.bands.push(PaletteBand.new(
          rowStart, rowCount,
          array.new_int(rowCount * capacity, -1)))
    result
 
// Only columns supplied to push() are visible. Unwritten cells are transparent.
 
_validatePushColumn(int size, int rows) =>
    if size != rows
        runtime.error("push size must equal scroll rows")
    0
 
//@function Appends one column, overwriting the oldest once capacity is reached.
//@param self Scroll to append to.
//@param column Exactly self.rows values, in row order. na cells are transparent.
//@returns Self for chaining.
export method push(ValueScroll self, array<float> column) =>
    if na(self)
        runtime.error("ValueScroll is na")
    if na(column)
        runtime.error("pushed column is na")
    _validatePushColumn(column.size(), self.rows)
    capacity = self.capacity
    writeColumn = self.head
    bandCount = self.bands.size()
    if bandCount > 0
        lastBand = bandCount - 1
        for bandIndex = 0 to lastBand
            ValueBand band = self.bands.get(bandIndex)
            array<float> cells = band.values
            rowsHere = band.rowCount
            sourceRow = band.rowStart
            if rowsHere > 0
                lastRow = rowsHere - 1
                for localRow = 0 to lastRow
                    cells.set(localRow * capacity + writeColumn,
                      column.get(sourceRow + localRow))
    wasFull = self.written == capacity
    self.head := writeColumn + 1 == capacity ? 0 : writeColumn + 1
    self.written := math.min(capacity, self.written + 1)
    self.origin += wasFull ? 1 : 0
    self.revision += 1
    self
 
//@function Appends one column, overwriting the oldest once capacity is reached.
//@param self Scroll to append to.
//@param column Exactly self.rows palette indices, in row order. -1 is transparent.
//@returns Self for chaining.
export method push(PaletteScroll self, array<int> column) =>
    if na(self)
        runtime.error("PaletteScroll is na")
    if na(column)
        runtime.error("pushed column is na")
    _validatePushColumn(column.size(), self.rows)
    capacity = self.capacity
    writeColumn = self.head
    bandCount = self.bands.size()
    if bandCount > 0
        lastBand = bandCount - 1
        for bandIndex = 0 to lastBand
            PaletteBand band = self.bands.get(bandIndex)
            array<int> cells = band.values
            rowsHere = band.rowCount
            sourceRow = band.rowStart
            if rowsHere > 0
                lastRow = rowsHere - 1
                for localRow = 0 to lastRow
                    cells.set(localRow * capacity + writeColumn,
                      column.get(sourceRow + localRow))
    wasFull = self.written == capacity
    self.head := writeColumn + 1 == capacity ? 0 : writeColumn + 1
    self.written := math.min(capacity, self.written + 1)
    self.origin += wasFull ? 1 : 0
    self.revision += 1
    self
 
// ============================================================================
// PALETTE HELPER
// ============================================================================
 
//@function Creates a two-stop gradient.
//@param lowColor Color at the start of the gradient.
//@param highColor Color at the end of the gradient.
//@returns A new color array.
export gradient(color lowColor, color highColor) =>
    array.from(lowColor, highColor)
 
//@function Creates a five-stop gradient.
//@param color0 Color at 0% of the gradient.
//@param color25 Color at 25% of the gradient.
//@param color50 Color at 50% of the gradient.
//@param color75 Color at 75% of the gradient.
//@param color100 Color at 100% of the gradient.
//@returns A new color array.
export gradient(
  color color0,
  color color25,
  color color50,
  color color75,
  color color100
  ) =>
    array.from(color0, color25, color50, color75, color100)
 
// ============================================================================
// CANVAS API
// ============================================================================
 
//@function Copies a new gradient or palette into the Canvas.
//@param self Canvas to configure.
//@param colors Gradient stops for value sources, or exact colors for palette sources.
//@returns Self for chaining.
export method palette(Canvas self, array<color> colors) =>
    _ensureConfigured(self)
    _validatePalette(colors)
    self.colors := colors.copy()
    self
 
//@function Sets the number of gradient levels used for value sources.
//@param self Canvas to configure.
//@param count Number of sampled gradient colors, from 2 to 100. Does not affect palette sources.
//@returns Self for chaining.
export method colorLevels(Canvas self, int count) =>
    _ensureConfigured(self)
    if na(count) or count < 2 or count > MAX_POLYLINES
        runtime.error("colorLevels must be 2..100")
    self.style.colorLevels := count
    self
 
//@function Limits how many polyline objects this Canvas may own.
//@param self Canvas to configure.
//@param count Canvas budget from 1 to 100. All canvases still share the script limit.
//@returns Self for chaining.
export method drawingLimit(Canvas self, int count) =>
    _ensureConfigured(self)
    if na(count) or count < 1 or count > MAX_POLYLINES
        runtime.error("drawingLimit must be 1..100")
    self.style.drawingLimit := count
    self
 
//@function Sets field opacity as a percentage of each color's existing opacity.
//@param self Canvas to configure.
//@param lowOpacity Opacity percentage at the lowest level, from 0 to 100.
//@param highOpacity Opacity percentage at the highest level, from 0 to 100, or na to use lowOpacity.
//@returns Self for chaining.
export method opacity(
  Canvas self,
  float lowOpacity,
  float highOpacity = na
  ) =>
    _ensureConfigured(self)
    upperOpacity = na(highOpacity) ? lowOpacity : highOpacity
    if na(lowOpacity) or lowOpacity < 0 or lowOpacity > 100 or upperOpacity < 0 or upperOpacity > 100
        runtime.error("opacity must be 0..100")
    self.style.lowOpacity := lowOpacity
    self.style.highOpacity := upperOpacity
    self
 
//@function Enables automatic scalar normalization and selects its scope.
//@param self Canvas to configure.
//@param mode Normalize the whole grid, each column, or each row.
//@returns Self for chaining.
export method autoScale(
  Canvas self,
  ScaleMode mode = ScaleMode.wholeGrid
  ) =>
    _ensureConfigured(self)
    self.style.autoScale := true
    self.style.scaleMode := mode
    self
 
//@function Uses a fixed scalar input range instead of automatic normalization.
//@param self Canvas to configure.
//@param minimum Input value mapped to the lowest color.
//@param maximum Input value mapped to the highest color. Must exceed minimum.
//@returns Self for chaining.
export method valueRange(Canvas self, float minimum, float maximum) =>
    _ensureConfigured(self)
    if na(minimum) or na(maximum) or maximum <= minimum
        runtime.error("valueRange requires max>min")
    self.style.autoScale := false
    self.style.valueMin := minimum
    self.style.valueMax := maximum
    self
 
//@function Sets the scalar response curve.
//@param self Canvas to configure.
//@param value Positive exponent. Below 1 emphasizes lower values; above 1 suppresses them.
//@returns Self for chaining.
export method gamma(Canvas self, float value) =>
    _ensureConfigured(self)
    if na(value) or value <= 0
        runtime.error("gamma must be >0")
    self.style.gamma := value
    self
 
//@function Enables or disables logarithmic spacing for regular Y grids.
//@param self Canvas to configure.
//@param enabled True uses logarithmic spacing and requires positive Y bounds.
//@returns Self for chaining.
export method logarithmicY(Canvas self, bool enabled = true) =>
    _ensureConfigured(self)
    self.style.logarithmicY := enabled
    self
 
//@function Maps row 0 to the top when enabled.
//@param self Canvas to configure.
//@param enabled True puts row 0 at the top.
//@returns Self for chaining.
export method invertRows(Canvas self, bool enabled = true) =>
    _ensureConfigured(self)
    self.style.invertRows := enabled
    self
 
//@function Forces Canvas drawings into the main chart pane when enabled.
//@param self Canvas to configure.
//@param enabled True displays generated drawings on the main chart.
//@returns Self for chaining.
export method forceOverlay(Canvas self, bool enabled = true) =>
    _ensureConfigured(self)
    self.style.forceOverlay := enabled
    self
 
//@function Copies and applies a complete Style to the Canvas.
//@param self Canvas to configure.
//@param style Rendering style.
//@returns Self for chaining.
export method configure(Canvas self, Style style) =>
    _ensureConfigured(self)
    _validateStyle(style)
    self.style := style.copy()
    self
 
//@function Deletes every polyline owned by this Canvas.
//@param self Canvas to clear.
//@returns Self for chaining.
export method clear(Canvas self) =>
    _clearDrawings(self)
    self.rows := 0
    self.columns := 0
    self.scaledMin := na
    self.scaledMax := na
    self
 
//@function Returns how many connected same-color regions the last render found.
// Counts 8-connected regions of equal palette index. Holes, contour loops,
// and partition fragments do not count as separate regions.
//@param self Canvas to inspect.
//@returns Region count from the most recent field render, or 0 before rendering.
export method componentCount(Canvas self) =>
    count = 0
    if not na(self)
        if not na(self._scratch)
            count := self._scratch.lastComponentCount
    count
 
//@function Returns the number of polylines currently owned by the Canvas.
//@param self Canvas to inspect.
//@returns Current drawing count.
export method drawingCount(Canvas self) =>
    count = 0
    if not na(self)
        if not na(self.drawings)
            count := self.drawings.size()
    count
 
//@function Returns the row and column counts from the most recent field render.
//@param self Canvas to inspect.
//@returns A [rows, columns] tuple, or [0, 0] before rendering and after clear().
export method dimensions(Canvas self) =>
    _ensureConfigured(self)
    [self.rows, self.columns]
 
//@function Returns the value range from the most recent field render.
//@param self Canvas to inspect.
//@returns A [minimum, maximum] tuple; both are na for an empty field or after clear(). Palette sources report 0 to palette size minus 1.
export method scaledRange(Canvas self) =>
    _ensureConfigured(self)
    [self.scaledMin, self.scaledMax]
 
// ============================================================================
// DRAWING API
// ============================================================================
//
// Value sources are normalized through the Canvas style. Palette sources
// use exact palette indices. Renderer selection is automatic.
// Each completed draw replaces the polylines owned by the receiving Canvas.
// Rendered fields require 2 to 99,999 rows and columns.
 
// Reuse a Style that preserves opacity and placement while disabling
// value normalization for palette indices.
_paletteStyle(Canvas canvas) =>
    _ensureConfigured(canvas)
    levelCount = canvas.colors.size()
    if levelCount > MAX_POLYLINES
        runtime.error("palettes colors exceed 100")
    _CanvasScratch scratch = canvas._scratch
    Style source = canvas.style
    Style config = scratch.paletteStyle
    if na(config)
        config := Style.new()
        scratch.paletteStyle := config
    config.colorLevels := levelCount
    config.lowOpacity := source.lowOpacity
    config.highOpacity := source.highOpacity
    config.autoScale := false
    config.valueMin := 0.0
    config.valueMax := levelCount - 1.0
    config.gamma := 1.0
    config.logarithmicY := source.logarithmicY
    config.invertRows := source.invertRows
    config.forceOverlay := source.forceOverlay
    config.scaleMode := source.scaleMode
    config.drawingLimit := source.drawingLimit
    config
 
_drawValueBounds(
  Canvas canvas, ValueField source,
  int left, int right, float bottom, float top,
  bool timeCoordinates
  ) =>
    _CanvasScratch scratch = _ensureScratch(canvas)
    Style style = canvas.style
    scratch.xEdges := _regularXEdges(
      left, right, source.columns, timeCoordinates, scratch.xEdges)
    scratch.yEdges := _cachedRegularYEdges(
      scratch, bottom, top, source.rows, style.logarithmicY)
    _renderValueField(
      canvas, source, scratch.xEdges, scratch.yEdges,
      canvas.colors, style, timeCoordinates, true)
 
_drawPaletteBounds(
  Canvas canvas, PaletteField source,
  int left, int right, float bottom, float top,
  bool timeCoordinates
  ) =>
    _CanvasScratch scratch = _ensureScratch(canvas)
    Style style = _paletteStyle(canvas)
    scratch.xEdges := _regularXEdges(
      left, right, source.columns, timeCoordinates, scratch.xEdges)
    scratch.yEdges := _cachedRegularYEdges(
      scratch, bottom, top, source.rows, style.logarithmicY)
    _renderPaletteField(
      canvas, source, scratch.xEdges, scratch.yEdges,
      canvas.colors, style, timeCoordinates, true)
 
// ----------------------------------------------------------------------------
// Fixed sources
// ----------------------------------------------------------------------------
 
//@function Draws a fixed value field on regular bar-index bounds.
//@param self Configured Canvas.
//@param source Field to draw. na cells are transparent.
//@param leftIndex Left grid boundary in bar-index coordinates.
//@param rightIndex Right grid boundary in bar-index coordinates.
//@param bottom Lower Y boundary. Use actual prices for chart overlays.
//@param top Upper Y boundary.
//@returns Self for chaining.
export method draw(
  Canvas self, ValueField source,
  int leftIndex, int rightIndex, float bottom, float top
  ) =>
    _ensureConfigured(self)
    _drawValueBounds(
      self, source, leftIndex, rightIndex, bottom, top, false)
    self
 
//@function Draws a fixed palette field on regular bar-index bounds.
//@param self Configured Canvas.
//@param source Field to draw. -1 cells are transparent.
//@param leftIndex Left grid boundary in bar-index coordinates.
//@param rightIndex Right grid boundary in bar-index coordinates.
//@param bottom Lower Y boundary.
//@param top Upper Y boundary.
//@returns Self for chaining.
export method draw(
  Canvas self, PaletteField source,
  int leftIndex, int rightIndex, float bottom, float top
  ) =>
    _drawPaletteBounds(
      self, source, leftIndex, rightIndex, bottom, top, false)
    self
 
//@function Draws a fixed value field ending near the current bar.
//@param self Configured Canvas.
//@param source Field to draw.
//@param lookback Width in bars. 0 uses source.columns; otherwise at least source.columns.
//@param bottom Lower Y boundary.
//@param top Upper Y boundary.
//@param rightOffset Right boundary offset from bar_index, in bars.
//@returns Self for chaining.
export method drawLookback(
  Canvas self, ValueField source,
  int lookback, float bottom, float top, int rightOffset = 0
  ) =>
    _ensureConfigured(self)
    [leftIndex, rightIndex] = _lookbackBounds(
      source.columns, lookback, rightOffset)
    _drawValueBounds(
      self, source, leftIndex, rightIndex, bottom, top, false)
    self
 
//@function Draws a fixed palette field ending near the current bar.
//@param self Configured Canvas.
//@param source Field to draw.
//@param lookback Width in bars. 0 uses source.columns; otherwise at least source.columns.
//@param bottom Lower Y boundary.
//@param top Upper Y boundary.
//@param rightOffset Right boundary offset from bar_index, in bars.
//@returns Self for chaining.
export method drawLookback(
  Canvas self, PaletteField source,
  int lookback, float bottom, float top, int rightOffset = 0
  ) =>
    [leftIndex, rightIndex] = _lookbackBounds(
      source.columns, lookback, rightOffset)
    _drawPaletteBounds(
      self, source, leftIndex, rightIndex, bottom, top, false)
    self
 
//@function Draws a fixed value field on regular bar-time bounds.
//@param self Configured Canvas.
//@param source Field to draw.
//@param leftTime Left boundary as a UNIX timestamp in milliseconds.
//@param rightTime Right boundary as a UNIX timestamp in milliseconds.
//@param bottom Lower Y boundary.
//@param top Upper Y boundary.
//@returns Self for chaining.
export method drawTime(
  Canvas self, ValueField source,
  int leftTime, int rightTime, float bottom, float top
  ) =>
    _ensureConfigured(self)
    _drawValueBounds(
      self, source, leftTime, rightTime, bottom, top, true)
    self
 
//@function Draws a fixed palette field on regular bar-time bounds.
//@param self Configured Canvas.
//@param source Field to draw.
//@param leftTime Left boundary as a UNIX timestamp in milliseconds.
//@param rightTime Right boundary as a UNIX timestamp in milliseconds.
//@param bottom Lower Y boundary.
//@param top Upper Y boundary.
//@returns Self for chaining.
export method drawTime(
  Canvas self, PaletteField source,
  int leftTime, int rightTime, float bottom, float top
  ) =>
    _drawPaletteBounds(
      self, source, leftTime, rightTime, bottom, top, true)
    self
 
//@function Draws a fixed value field on explicit bar-index edges.
//@param self Configured Canvas.
//@param source Field to draw. Rows and columns must match the edge arrays.
//@param columnEdges Strictly increasing bar indices; source.columns + 1 entries.
//@param rowEdges Strictly increasing Y boundaries; source.rows + 1 entries.
//@returns Self for chaining.
export method drawGrid(
  Canvas self, ValueField source,
  array<int> columnEdges, array<float> rowEdges
  ) =>
    _ensureConfigured(self)
    _renderValueField(
      self, source, columnEdges, rowEdges,
      self.colors, self.style, false)
    self
 
//@function Draws a fixed palette field on explicit bar-index edges.
//@param self Configured Canvas.
//@param source Field to draw. Rows and columns must match the edge arrays.
//@param columnEdges Strictly increasing bar indices; source.columns + 1 entries.
//@param rowEdges Strictly increasing Y boundaries; source.rows + 1 entries.
//@returns Self for chaining.
export method drawGrid(
  Canvas self, PaletteField source,
  array<int> columnEdges, array<float> rowEdges
  ) =>
    Style style = _paletteStyle(self)
    _renderPaletteField(
      self, source, columnEdges, rowEdges,
      self.colors, style, false)
    self
 
//@function Draws a fixed value field on explicit bar-time edges.
//@param self Configured Canvas.
//@param source Field to draw. Rows and columns must match the edge arrays.
//@param timeEdges Strictly increasing UNIX timestamps in milliseconds; source.columns + 1 entries.
//@param rowEdges Strictly increasing Y boundaries; source.rows + 1 entries.
//@returns Self for chaining.
export method drawTimeGrid(
  Canvas self, ValueField source,
  array<int> timeEdges, array<float> rowEdges
  ) =>
    _ensureConfigured(self)
    _renderValueField(
      self, source, timeEdges, rowEdges,
      self.colors, self.style, true)
    self
 
//@function Draws a fixed palette field on explicit bar-time edges.
//@param self Configured Canvas.
//@param source Field to draw. Rows and columns must match the edge arrays.
//@param timeEdges Strictly increasing UNIX timestamps in milliseconds; source.columns + 1 entries.
//@param rowEdges Strictly increasing Y boundaries; source.rows + 1 entries.
//@returns Self for chaining.
export method drawTimeGrid(
  Canvas self, PaletteField source,
  array<int> timeEdges, array<float> rowEdges
  ) =>
    Style style = _paletteStyle(self)
    _renderPaletteField(
      self, source, timeEdges, rowEdges,
      self.colors, style, true)
    self
 
// ----------------------------------------------------------------------------
// Rolling sources
// ----------------------------------------------------------------------------
//
// Rolling sources draw only the columns already pushed. At least two
// columns are required; otherwise the call leaves existing drawings unchanged.
// The newest column is on the right.
 
//@function Draws retained value columns relative to the current bar when at least two are available.
//@param self Configured Canvas.
//@param source Rolling field to draw. na cells are transparent.
//@param bottom Lower Y boundary.
//@param top Upper Y boundary.
//@param rightOffset Right boundary offset from bar_index, in bars.
//@returns Self for chaining.
export method drawLookback(
  Canvas self, ValueScroll source,
  float bottom, float top, int rightOffset = 0
  ) =>
    if na(source)
        runtime.error("ValueScroll is na")
    if source.written >= 2
        _ensureConfigured(self)
        _CanvasScratch scratch = _ensureScratch(self)
        columns = source.written
        [leftIndex, rightIndex] = _lookbackBounds(columns, 0, rightOffset)
        Style style = self.style
        scratch.xEdges := _regularXEdges(
          leftIndex, rightIndex, columns, false, scratch.xEdges)
        scratch.yEdges := _cachedRegularYEdges(
          scratch, bottom, top, source.rows, style.logarithmicY)
        _renderValueScroll(
          self, source, scratch.xEdges, scratch.yEdges,
          self.colors, style, false, true)
    self
 
//@function Draws retained palette columns relative to the current bar when at least two are available.
//@param self Configured Canvas.
//@param source Rolling field to draw. -1 cells are transparent.
//@param bottom Lower Y boundary.
//@param top Upper Y boundary.
//@param rightOffset Right boundary offset from bar_index, in bars.
//@returns Self for chaining.
export method drawLookback(
  Canvas self, PaletteScroll source,
  float bottom, float top, int rightOffset = 0
  ) =>
    if na(source)
        runtime.error("PaletteScroll is na")
    if source.written >= 2
        _CanvasScratch scratch = _ensureScratch(self)
        Style style = _paletteStyle(self)
        columns = source.written
        [leftIndex, rightIndex] = _lookbackBounds(columns, 0, rightOffset)
        scratch.xEdges := _regularXEdges(
          leftIndex, rightIndex, columns, false, scratch.xEdges)
        scratch.yEdges := _cachedRegularYEdges(
          scratch, bottom, top, source.rows, style.logarithmicY)
        _renderPaletteScroll(
          self, source, scratch.xEdges, scratch.yEdges,
          self.colors, style, false, true)
    self
 
// ============================================================================
// SHAPE API
// ============================================================================
//
// Shapes are queued in time and price coordinates, grouped by fill color,
// and packed into polylines. Each batch accepts up to 100,000 input vertices.
// Each polyline holds up to 10,000 points, including closure and connectors.
//
// Winding is normalized so same-color overlaps remain filled. Borders and
// per-shape layering are not supported. Colors render in insertion order.
// Use separate canvases for shapes and fields that must remain visible
// together; either draw call replaces the receiving Canvas's drawings.
 
_ensureShapeStorage(_CanvasScratch scratch) =>
    if na(scratch.shapeTime)
        scratch.shapeTime := array.new_int()
        scratch.shapeY := array.new_float()
        scratch.shapeEnd := array.new_int()
        scratch.shapeNext := array.new_int()
        scratch.shapePalette := array.new<color>()
        scratch.shapeLevelFirst := array.new_int()
        scratch.shapeLevelLast := array.new_int()
        scratch.shapeInputPoints := array.new<chart.point>()
        scratch.shapeInputTime := array.new_int()
        scratch.shapeInputY := array.new_float()
        if na(scratch.anchors)
            scratch.anchors := array.new_int()
        if na(scratch.points)
            scratch.points := array.new<chart.point>()
    0
 
// Returns whether the polygon is clockwise. Translate coordinates before
// the shoelace sum to avoid cancellation with large timestamp values.
_shapeIsClockwise(array<int> times, array<float> ys) =>
    count = times.size()
    originTime = times.get(0)
    originY = ys.get(0)
    twiceArea = 0.0
    for i = 0 to count - 1
        j = i + 1 == count ? 0 : i + 1
        currentX = times.get(i) - originTime
        currentY = ys.get(i) - originY
        nextX = times.get(j) - originTime
        nextY = ys.get(j) - originY
        twiceArea += currentX * nextY - nextX * currentY
    twiceArea < 0
 
_pushShapeReady(
  _CanvasScratch scratch,
  array<int> times,
  array<float> ys,
  color fillColor
  ) =>
    count = times.size()
    if count < 3
        runtime.error("shape needs >=3 corners")
    if count + 1 > MAX_POINTS
        runtime.error("shape exceeds 10000 points")
    if na(fillColor)
        runtime.error("shape fill colour is na")
    if scratch.shapeTime.size() + count > MAX_CELLS
        runtime.error("shape queue >100000 vertices")
 
    // Assign each distinct fill color a queue level.
    level = -1
    for [i, existing] in scratch.shapePalette
        if existing == fillColor
            level := i
            break
    if level < 0
        if scratch.shapePalette.size() >= MAX_POLYLINES
            runtime.error("shape colors exceed 100")
        scratch.shapePalette.push(fillColor)
        scratch.shapeLevelFirst.push(-1)
        scratch.shapeLevelLast.push(-1)
        level := scratch.shapePalette.size() - 1
 
    // Store every polygon counter-clockwise so overlapping fills form a union.
    shapeTime = scratch.shapeTime
    shapeY = scratch.shapeY
    if _shapeIsClockwise(times, ys)
        // count >= 3 guarantees a descending, nonempty range.
        for source = count - 1 to 0
            shapeTime.push(times.get(source))
            shapeY.push(ys.get(source))
    else
        shapeTime.concat(times)
        shapeY.concat(ys)
    scratch.shapeEnd.push(shapeTime.size())
 
    shape = scratch.shapeEnd.size() - 1
    scratch.shapeNext.push(-1)
    tail = scratch.shapeLevelLast.get(level)
    if tail < 0
        scratch.shapeLevelFirst.set(level, shape)
    else
        scratch.shapeNext.set(tail, shape)
    scratch.shapeLevelLast.set(level, shape)
    0
 
// Copies time-based chart points into the reusable input arrays. Shape
// storage must be initialized and points must not be na.
_pushShapePointsReady(
  _CanvasScratch scratch,
  array<chart.point> points,
  color fillColor
  ) =>
    times = scratch.shapeInputTime
    ys = scratch.shapeInputY
    times.clear()
    ys.clear()
    for corner in points
        if na(corner)
            runtime.error("shape corner is na")
        if na(corner.time)
            runtime.error("shape corners need from_time()")
        if na(corner.price)
            runtime.error("shape price is na")
        times.push(corner.time)
        ys.push(corner.price)
    _pushShapeReady(scratch, times, ys, fillColor)
    0
 
// Closes and draws the chunk. Retracing connectors in reverse keeps their
// signed area and winding contribution at zero.
_emitShapeChunk(
  Canvas canvas,
  _CanvasScratch scratch,
  color fillColor,
  Style style
  ) =>
    shapeTime = scratch.shapeTime
    shapeY = scratch.shapeY
    points = scratch.points
    anchors = scratch.anchors
    drawings = canvas.drawings
    anchorCount = anchors.size()
    if anchorCount > 1
        for offset = 2 to anchorCount
            source = anchors.get(anchorCount - offset)
            points.push(chart.point.from_time(
              shapeTime.get(source), shapeY.get(source)))
    if drawings.size() >= style.drawingLimit
        runtime.error("shapes exceed drawingLimit")
    drawings.push(_newFilledPolyline(points, fillColor, true, style.forceOverlay))
    0
 
_clearShapeQueue(_CanvasScratch scratch) =>
    scratch.shapeTime.clear()
    scratch.shapeY.clear()
    scratch.shapeEnd.clear()
    scratch.shapeNext.clear()
    scratch.shapePalette.clear()
    scratch.shapeLevelFirst.clear()
    scratch.shapeLevelLast.clear()
    0
 
_drawShapes(Canvas canvas) =>
    _ensureConfigured(canvas)
    _CanvasScratch scratch = canvas._scratch
    _ensureShapeStorage(scratch)
    _clearDrawings(canvas)
 
    shapeTime = scratch.shapeTime
    shapeY = scratch.shapeY
    shapeEnd = scratch.shapeEnd
    shapeNext = scratch.shapeNext
    shapeLevelFirst = scratch.shapeLevelFirst
    points = scratch.points
    anchors = scratch.anchors
 
    levelCount = scratch.shapePalette.size()
    if levelCount > 0
        Style style = _styleOrDefault(canvas.style)
        for level = 0 to levelCount - 1
            fillColor = scratch.shapePalette.get(level)
            shape = shapeLevelFirst.get(level)
            points.clear()
            anchors.clear()
            while shape >= 0
                runStart = 0
                if shape > 0
                    runStart := shapeEnd.get(shape - 1)
                runEnd = shapeEnd.get(shape)
                // Reserve the return connector for each staged shape.
                projected = points.size() +
                  (runEnd - runStart) + 1 + anchors.size()
                if anchors.size() > 0 and projected > MAX_POINTS
                    _emitShapeChunk(canvas, scratch, fillColor, style)
                    points.clear()
                    anchors.clear()
                anchors.push(runStart)
                for index = runStart to runEnd - 1
                    points.push(chart.point.from_time(
                      shapeTime.get(index), shapeY.get(index)))
                points.push(chart.point.from_time(
                  shapeTime.get(runStart), shapeY.get(runStart)))
                shape := shapeNext.get(shape)
            if anchors.size() > 0
                _emitShapeChunk(canvas, scratch, fillColor, style)
 
    _clearShapeQueue(scratch)
    // Shared with flat contour emission; shape offsets are not world vertices.
    anchors.clear()
    canvas.usesTime := true
    canvas.drawings.size()
 
//@function Estimates a timestamp from a bar offset and the current timeframe.
// Uses fixed timeframe intervals and does not account for session gaps.
// Use a candle's time when exact bar alignment is required.
//@param offsetBars Bars forward (positive) or back (negative) from this bar.
//@returns A UNIX timestamp in milliseconds.
export barsToTime(int offsetBars) =>
    time + offsetBars * timeframe.in_seconds() * 1000
 
//@function Queues an axis-aligned rectangle from two opposite corners.
//@param self Canvas that will own the drawing.
//@param topLeft Upper-left corner, from chart.point.from_time().
//@param bottomRight Lower-right corner, from chart.point.from_time().
//@param fillColor Fill colour. Shapes sharing a colour share polylines.
//@returns Self for chaining.
export method rect(
  Canvas self,
  chart.point topLeft,
  chart.point bottomRight,
  color fillColor
  ) =>
    if na(topLeft) or na(bottomRight)
        runtime.error("rectangle corners is na")
    _ensureConfigured(self)
    _CanvasScratch scratch = self._scratch
    _ensureShapeStorage(scratch)
    points = scratch.shapeInputPoints
    points.clear()
    points.push(topLeft)
    points.push(chart.point.from_time(bottomRight.time, topLeft.price))
    points.push(bottomRight)
    points.push(chart.point.from_time(topLeft.time, bottomRight.price))
    _pushShapePointsReady(scratch, points, fillColor)
    self
 
//@function Queues a triangle from three explicit corners, in any orientation.
//@param self Canvas that will own the drawing.
//@param cornerA First corner, from chart.point.from_time().
//@param cornerB Second corner, from chart.point.from_time().
//@param cornerC Third corner, from chart.point.from_time().
//@param fillColor Fill colour.
//@returns Self for chaining.
export method triangle(
  Canvas self,
  chart.point cornerA,
  chart.point cornerB,
  chart.point cornerC,
  color fillColor
  ) =>
    _ensureConfigured(self)
    _CanvasScratch scratch = self._scratch
    _ensureShapeStorage(scratch)
    points = scratch.shapeInputPoints
    points.clear()
    points.push(cornerA)
    points.push(cornerB)
    points.push(cornerC)
    _pushShapePointsReady(scratch, points, fillColor)
    self
 
//@function Queues an ellipse approximated by a regular polygon.
// Radii use time and price units. The apparent aspect ratio depends on
// the chart scale. More segments produce a smoother perimeter.
//@param self Canvas that will own the drawing.
//@param centre Centre point, from chart.point.from_time().
//@param radiusTime Horizontal radius in milliseconds.
//@param radiusPrice Vertical radius in price units.
//@param segments Number of perimeter vertices, from 3 to 9,999.
//@param fillColor Fill colour.
//@returns Self for chaining.
export method circle(
  Canvas self,
  chart.point centre,
  int radiusTime,
  float radiusPrice,
  int segments,
  color fillColor
  ) =>
    if na(centre)
        runtime.error("circle centre is na")
    if na(centre.price)
        runtime.error("circle centre price is na")
    if na(centre.time)
        runtime.error("circle centre needs from_time()")
    if na(segments) or segments < 3
        runtime.error("circle needs >=3 segments")
    if segments + 1 > MAX_POINTS
        runtime.error("circle exceeds 10000 points")
    if na(radiusTime) or na(radiusPrice)
        runtime.error("circle radii is na")
    _ensureConfigured(self)
    _CanvasScratch scratch = self._scratch
    _ensureShapeStorage(scratch)
    times = scratch.shapeInputTime
    ys = scratch.shapeInputY
    times.clear()
    ys.clear()
    // Normalize winding after generation; negative radii can reverse it.
    for segment = 0 to segments - 1
        angle = 2.0 * math.pi * segment / segments
        times.push(centre.time + int(math.round(radiusTime * math.cos(angle))))
        ys.push(centre.price + radiusPrice * math.sin(angle))
    _pushShapeReady(scratch, times, ys, fillColor)
    self
 
//@function Queues an arbitrary closed shape from its corner points.
// Accepts convex or concave polygons in either winding direction.
// Same-color shapes use a common winding so their overlapping fills form a union.
//@param self Canvas that will own the drawing.
//@param points From 3 to 9,999 chart.point.from_time() vertices in perimeter order.
//@param fillColor Fill colour.
//@returns Self for chaining.
export method poly(
  Canvas self,
  array<chart.point> points,
  color fillColor
  ) =>
    if na(points)
        runtime.error("shape point array is na")
    _ensureConfigured(self)
    _CanvasScratch scratch = self._scratch
    _ensureShapeStorage(scratch)
    _pushShapePointsReady(scratch, points, fillColor)
    self
 
//@function Replaces the Canvas drawings with the queued shapes, then empties the queue.
//@param self Canvas holding the queued shapes.
//@returns Number of polylines created.
export method drawShapes(Canvas self) =>
    _drawShapes(self)
 
//@function Discards queued shapes without drawing them.
//@param self Canvas holding the queued shapes.
//@returns Self for chaining.
export method clearShapes(Canvas self) =>
    _CanvasScratch scratch = _ensureScratch(self)
    _ensureShapeStorage(scratch)
    _clearShapeQueue(scratch)
    self
 
//@function Returns how many shapes are queued but not yet drawn.
//@param self Canvas to inspect.
//@returns Queued shape count.
export method shapeCount(Canvas self) =>
    count = 0
    if not na(self)
        if not na(self._scratch)
            if not na(self._scratch.shapeEnd)
                count := self._scratch.shapeEnd.size()
    count

← 返回列表