Line decimation C reference
These static helpers belong to rbcGrLine.c. They are not cross-module APIs. See Line decimation and source identity for fallback
order and source-index ownership.
- group Line decimation internals
Private screen-density reduction services.
All objects are borrowed from the owning graph; these routines neither mutate source vectors nor invoke Tcl.
Functions
-
static int CanPixelDecimateLine(Line *linePtr)
Test semantic eligibility, independently of source density.
- Parameters:
linePtr – Borrowed live line/strip element.
- Returns:
TRUE for automatic, ordinary XY, unsmoothed, single-pen traces without area fill, outside export. Does not guarantee that reduction will be attempted.
-
static int LineNeedsPixelDecimation(Graph *graphPtr, Line *linePtr)
Test source density against the physical data-X plot span.
- Parameters:
graphPtr – Borrowed graph with current mapping/extents, including track scope.
linePtr – Borrowed element supplying the complete paired source count.
- Returns:
TRUE at the renderer’s density threshold, FALSE for empty data or invalid/subpixel spans. Uses vertical extent when axes are inverted.
-
static int RefreshLineDecimateCache(Line *linePtr)
Maintain a persistent source-domain cache after element invalidation.
Exact Y changes rebuild affected summaries; X changes invalidate ordering. Growth delegates to checked prefix retention. Does not clear source change flags.
- Parameters:
linePtr – Borrowed element with current source pointers and change metadata.
- Returns:
TRUE when no cache exists or the existing cache can be retained or updated; FALSE asks the caller to invalidate it. Not a geometry-generation result.
-
static int BuildPixelDecimatedScreenPoints(Graph *graphPtr, Line *linePtr, MapInfo *mapPtr)
Map representative points from pixel buckets into an owned screen buffer.
Returns TRUE for completed mapping, including empty output. Returns FALSE when capacity, allocation or source-order constraints require the ordinary mapper. Initializes output pointers/count to empty and releases temporary allocations on fallback. Successful arrays transfer to the caller for ckfree cleanup; source vectors are not modified. Buckets preserve first/minimum/maximum/last indices.
- Parameters:
graphPtr – [in] Borrowed graph with current axis mapping and the owning track viewport selected.
linePtr – [in] Borrowed eligible real Cartesian line element; caller checks fast-path applicability before entry.
mapPtr – [out] Required output with no owned screen arrays on entry; receives owned points, original indices and an optional break array.
-
static int BuildCachedPixelDecimatedScreenPoints(Graph *graphPtr, Line *linePtr, MapInfo *mapPtr)
Build reduced mapped geometry from source-domain summaries.
Supports a finite continuous monotonic-X run. Binary searches locate pixel buckets; block extrema supply first/min/max/last representatives in source order. Successful output belongs to the mapping caller. breakBefore is NULL.
- Parameters:
graphPtr – Borrowed graph with current axes and plot scope.
linePtr – Borrowed eligible trace-only element; may build its persistent cache.
mapPtr – Caller-owned mapping record receiving allocated points and source indices.
- Returns:
TRUE if handled, FALSE asks the caller to use the source-scanning fallback.
-
static void DecimatePointsByPixels(Graph *graphPtr, MapInfo *mapPtr)
Reduce eligible mapped geometry without changing source values.
Retains first/min/max/last representatives per pixel bucket and continuous run. Leaves geometry unchanged for short/nonmonotonic inputs, allocation failure or no useful reduction. Preserves source indices and run boundaries.
- Parameters:
graphPtr – Borrowed graph defining the physical data-X direction.
mapPtr – Owned mapped arrays; replacements, when made, remain owned by caller.
-
static int CanPixelDecimateLine(Line *linePtr)
Source summaries and bucket searches
These helpers distinguish owned block storage from borrowed source arrays, cache validity from log-domain eligibility, and partial append results from complete mappings. The namespace is documentation-only.
- group Line cache internals
Private source-summary ownership, append retention and bucket searches.
Functions
-
static void InvalidateLineDecimateCache(Line *linePtr)
Release owned summaries and reset cache identity.
Frees the block array and zeros the complete cache record. Borrowed X/Y source arrays are neither freed nor retained. Does not clear element change metadata, map geometry or deliver vector notifications.
- Parameters:
linePtr – [inout] Live line whose owned summary blocks and cache identity are discarded; source arrays are not freed.
-
static int BuildLineDecimateCache(Line *linePtr)
Build source-domain summaries for one finite monotonic-X run.
Invalidates the previous cache first, records current source identity and marks built even if construction fails. Borrows X/Y arrays and allocates one block summary per LINE_DECIMATE_BLOCK_SIZE samples. Equal X values are allowed; reversals or nonfinite coordinates make the run unsupported.
Stores earliest source indices for tied Y extrema and positivity summaries. Unsupported data releases blocks but retains built/identity state, avoiding repeated attempts until invalidation. Size/allocation failure likewise returns FALSE with an unsupported built cache. TRUE means summaries exist, not that current logarithmic axes accept the source domain.
- Parameters:
linePtr – [inout] Line in Cartesian X/Y mode with synchronized source arrays; old summaries are discarded before building new ones.
-
static int RebuildLineDecimateYBlock(Line *linePtr, Tcl_Size blockIndex)
Recompute one existing block after a precise Y-only update.
Requires a supported cache with current borrowed Y storage and unchanged X. Validates the block, scans finite Y values and computes earliest extrema and nonpositive count before modifying summaries. Returns FALSE without changing the block on invalid input or inconsistent positivity accounting. On success updates block/global counts and allPositiveY. Does not inspect X or allocate.
- Parameters:
linePtr – [inout] Line with supported cache, unchanged X and refreshed Y storage; one block and global positivity counts may change.
blockIndex – [in] Zero-based block index; an invalid index returns FALSE without updating summaries.
-
static int EnsureLineDecimateCache(Line *linePtr)
Ensure Cartesian X/Y summaries exist and fit the current log domains.
Rejects converted polar and complex input before inspecting cache arrays; original-sample picking must scan those representations through their adapter.
Invalidates built state when source pointers or paired count differ, then builds once if necessary. Returns FALSE for unsupported summaries or a log axis whose source contains nonpositive values. Log rejection retains the cache for later linear-axis reuse. Pointer/count checks do not detect in-place writes; notification-driven refresh/invalidation remains required. May allocate summaries but does not synchronize vectors or consume change metadata.
- Parameters:
linePtr – [inout] Line with synchronized source storage and prepared axes; Cartesian X/Y summaries may be rebuilt, other representations return FALSE.
-
static void GetCachedRangeExtrema(Line *linePtr, Tcl_Size first, Tcl_Size last, Tcl_Size *minIndexPtr, Tcl_Size *maxIndexPtr)
Find earliest Y extrema in an inclusive source range.
Requires valid current cache summaries and 0 <= first <= last < nPoints. Uses whole aligned block summaries and scans boundary fragments. Strict comparisons preserve the earliest source index on ties. Writes min/max indices, performs no allocation, and does not validate the caller’s range.
- Parameters:
linePtr – [in] Borrowed line with valid current summaries and their live Y array.
first – [in] Inclusive first source index, at least zero and no greater than last.
last – [in] Inclusive last source index, less than the cached point count.
minIndexPtr – [out] Required earliest-minimum source-index output, distinct from maxIndexPtr.
maxIndexPtr – [out] Required earliest-maximum source-index output, distinct from minIndexPtr.
-
static int GetCachedPixelBucket(Graph *graphPtr, Line *linePtr, Tcl_Size index, double pixelMin, double pixelMax, double *bucketPtr)
Map a cached source index to a bounded physical pixel bucket.
Requires a valid index and current axis/viewport state. Returns FALSE without writing bucketPtr for nonfinite mapped abscissa. Values outside pixelMin/pixelMax use sentinel buckets one unit beyond the respective boundary; inside values use truncation toward zero, not floor. Does not modify the cache.
- Parameters:
graphPtr – [in] Borrowed owning graph with the element or track viewport and axis mappings already installed.
linePtr – [in] Borrowed line with a valid cached X array and prepared X axis.
index – [in] Valid zero-based index into the cached source arrays; bounds are not checked here.
pixelMin – [in] Lower finite physical screen-coordinate bound for buckets, no greater than pixelMax.
pixelMax – [in] Upper finite physical screen-coordinate bound for buckets, no less than pixelMin.
bucketPtr – [out] Required physical pixel-bucket output; unchanged when mapping returns FALSE.
-
static Tcl_Size FindNextCachedPixelBucket(Graph *graphPtr, Line *linePtr, Tcl_Size first, double currentBucket, int direction, double pixelMin, double pixelMax, int *okPtr)
Binary-search the first source index beyond the current bucket.
Requires monotonic mapped buckets, a valid first index and nonzero direction. Searches after first, returning nPoints when no later bucket exists. Sets okPtr TRUE on success. If mapping fails, sets it FALSE and returns an intermediate bound that callers must not use as a valid bucket boundary. No allocation.
- Parameters:
graphPtr – [in] Borrowed owning graph with the element or track viewport and axis mappings already installed.
linePtr – [in] Borrowed line with valid cached X storage and monotonic mapped bucket order.
first – [in] Valid source index in the current bucket; search begins at first plus one.
currentBucket – [in] Physical bucket containing first, obtained with the same viewport bounds.
direction – [in] Positive for increasing mapped buckets, negative for decreasing; zero is not supported.
pixelMin – [in] Lower finite physical screen-coordinate bound for buckets, no greater than pixelMax.
pixelMax – [in] Upper finite physical screen-coordinate bound for buckets, no less than pixelMin.
okPtr – [out] Required status output; use the returned source boundary only when TRUE.
-
static int CanPreMapDecimateLine(Line *linePtr)
Check whether full mapped center arrays may be omitted.
First applies general pixel-decimation eligibility, then rejects normal symbols/value labels and any configured error-bar data. Whole-element active symbols/labels also require full centers; explicit active selections can map independently. This is a semantic gate, not a density or cache-validity test. Borrows line/pen state and makes no changes.
- Parameters:
linePtr – [in] Borrowed configured line with source lengths, palette, normal/active pens and activation state available.
-
static int CanRetainLineDecimatePrefix(const ElemVector *vPtr, const double *cachedValues, Tcl_Size nPoints)
Check metadata proof that a cached source prefix is unchanged.
With no pending change, requires the same source pointer. Full/unknown changes reject retention. An exact pending range beginning at or beyond nPoints permits retention even if vector storage relocated. Does not compare values or validate the full range; relies on truthful producer notifications.
- Parameters:
vPtr – [in] Borrowed synchronized source slot and its accumulated change metadata.
cachedValues – [in] Previous borrowed array identity; compared as a pointer, never dereferenced.
nPoints – [in] Length of the previously cached prefix; exact changes must start at or beyond this index.
-
static int IsMonotonicMappedAbscissa(Graph *graphPtr, MapInfo *mapPtr)
Check mapped data-X ordering independently within each run.
Accepts either direction and repeated coordinates; resets direction at each break-before flag. Fewer than two points succeed. Uses physical screen roles for inversion, without modifying input or allocating. Caller supplies finite mapped points; this helper is not a nonfinite-value validator.
- Parameters:
graphPtr – [in] Borrowed graph supplying the inversion flag.
mapPtr – [in] Borrowed finite mapped points and optional break-before flags; each run is checked independently.
-
static void AppendPixelBucket(Tcl_Size first, Tcl_Size minIndex, Tcl_Size maxIndex, Tcl_Size last, Tcl_Size *selected, Tcl_Size *countPtr)
Append distinct bucket representatives in source order.
Sorts first/min/max/last indices and appends each distinct candidate, advancing countPtr. Caller must provide enough output capacity; no bounds check or allocation occurs. Deduplicates within this bucket only.
- Parameters:
first – [in] First source index of this bucket.
minIndex – [in] Source index of the bucket minimum; may coincide with another representative.
maxIndex – [in] Source index of the bucket maximum; may coincide with another representative.
last – [in] Last source index of this bucket, inclusive.
selected – [inout] Caller-owned index array with space for up to four more entries; capacity is not checked.
countPtr – [inout] Required current output length, advanced for each emitted representative; initially within destination capacity.
-
static int AppendSourcePixelBucket(Tcl_Size first, Tcl_Size minIndex, Tcl_Size maxIndex, Tcl_Size last, int startsRun, Tcl_Size capacity, Tcl_Size *selected, unsigned char *selectedBreakBefore, Tcl_Size *countPtr)
Append bounded source representatives with run-boundary flags.
Sorts and deduplicates first/min/max/last within the bucket. Checks capacity before each append, setting a break flag only on the first emitted candidate of a new run when prior output exists. Returns FALSE on exhaustion, leaving any preceding appends and updated count intact; caller must discard or handle that partial result. Does not allocate or deduplicate against earlier buckets.
- Parameters:
first – [in] First source index of this bucket.
minIndex – [in] Source index of the bucket minimum; may coincide with another representative.
maxIndex – [in] Source index of the bucket maximum; may coincide with another representative.
last – [in] Last source index of this bucket, inclusive.
startsRun – [in] Nonzero marks the first emitted representative as a new run when earlier output exists.
capacity – [in] Nonnegative number of entries allocated in both output arrays.
selected – [inout] Writable index array of capacity entries; partial appends remain on FALSE.
selectedBreakBefore – [inout] Writable parallel array of capacity break flags; each appended index receives a flag.
countPtr – [inout] Required current output length, advanced for each emitted representative; initially within destination capacity.
-
static int GetCachedSourceRangeForAbscissa(Graph *graphPtr, Line *linePtr, double low, double high, Tcl_Size *firstPtr, Tcl_Size *lastPtr)
Find a half-open source range inside inclusive screen bounds.
Requires a valid monotonic-X cache and prepared axes/viewport. Orders low/high, then binary-searches mapped endpoints in either direction. Equal mapped endpoints yield the full range or empty range. Initializes outputs to zero; nonfinite mapping returns FALSE, and outputs must then be ignored. Success may be empty. Does not apply a query distance metric: callers decide whether pruning by mapped data X is valid for their search.
- Parameters:
graphPtr – [in] Borrowed owning graph with the element or track viewport and axis mappings already installed.
linePtr – [in] Borrowed line with supported monotonic-X cache and current source storage.
low – [in] Inclusive screen-abscissa bound; low/high are ordered locally if reversed.
high – [in] Other inclusive screen-abscissa bound; neither argument is a source-data value.
firstPtr – [out] Required first index of the half-open source interval; initialized to zero and usable only on TRUE.
lastPtr – [out] Required separate one-past-last source index; may equal first for an empty result. Use only on TRUE.
-
static int GrowLineDecimateCache(Line *linePtr, Tcl_Size nPoints)
Retain or extend summaries after proven source-tail growth.
Requires built supported state, no shrinkage and metadata proving both cached prefixes unchanged. Pointer relocation is allowed with exact ranges. If paired count is unchanged, rebinds borrowed arrays without extending blocks.
Validates new finite samples and X ordering before mutation. Rebuilds the old partial final block and any new blocks, preserving earliest tied extrema. Allocates replacement block storage only when more blocks are needed, then commits pointers, counts, direction and positivity summaries. FALSE requests caller invalidation; it does not report a Tcl error or clear change metadata.
- Parameters:
linePtr – [inout] Line with supported summaries and synchronized X/Y slots carrying exact prefix-preservation metadata.
nPoints – [in] New paired source count, readable in both current X/Y arrays; shrinkage is rejected.
-
static void InvalidateLineDecimateCache(Line *linePtr)
Data records and member contracts
These records describe stored state and resource ownership. Their presence in the reference does not make private layouts part of the installed C API.
-
struct LineDecimateBlock
Source-index extrema and log-eligibility summary for one decimation block.
-
struct LineDecimateCache
Owned extrema-block cache; source pointers are borrowed identities used to detect replacement, not retained storage.
Public Members
-
LineDecimateBlock *blocks
Owned block-summary array.
-
Tcl_Size nBlocks
Number of block summaries.
-
Tcl_Size nPoints
Source point count represented by the cache.
-
const double *xValues
Borrowed source X-array identity at build time.
-
const double *yValues
Borrowed source Y-array identity at build time.
-
int built
Nonzero after cache construction.
-
int supported
Nonzero when source ordering/data permit cached decimation.
-
int xDirection
X ordering: -1 decreasing, 0 constant, +1 increasing.
-
int allPositiveX
Nonzero when all cached X values are positive.
-
int allPositiveY
Nonzero when all cached Y values are positive.
-
Tcl_Size nonPositiveYCount
Total number of nonpositive source Y values.
-
LineDecimateBlock *blocks