Polar data and geometry C reference
These helpers are private to their implementation modules. See Polar data and grid geometry for source ownership and the distinction between data and grid coordinates.
Element data adapters (rbcGrLine.c)
- group Polar element data internals
Private adapters from retained source data to Cartesian graph coordinates.
Functions
-
static int GetComplexLineDataPoint(Line *linePtr, Tcl_Size index, double *xPtr, double *yPtr)
Convert one borrowed complex sample to graph-plane coordinates.
Gamma input is copied directly, including nonfinite values; callers must validate coordinates before mapping. Impedance and admittance are normalized using z0, then converted to Gamma. A FALSE return does not promise unchanged output values. No source storage is copied, retained or modified.
- Parameters:
linePtr – Borrowed line with validated data format and reference impedance.
index – Source index in the retained complex vector.
xPtr – Receives the real graph coordinate.
yPtr – Receives the imaginary graph coordinate.
- Returns:
FALSE for an unavailable sample or failed impedance/admittance division.
-
static int ParseComplexVectorObj(Tcl_Interp *interp, Element *elemPtr, Tcl_Obj *objPtr, ElemComplexVector *candidatePtr)
Acquire a staged client of a named complex vector.
The candidate owns its client ID and borrows the vector record and numeric storage. No update callback is installed until commit moves it into the stable line record. Release an abandoned candidate with FreeComplexVector. This parser does not accept a list of complex values as a fallback.
- Parameters:
interp – Interpreter used for lookup and error reporting.
elemPtr – Borrowed owner recorded in the candidate.
objPtr – Borrowed vector name; NULL or empty means no vector.
candidatePtr – Fresh output slot, initialized here rather than released.
- Returns:
TCL_OK for an empty slot or a retained complex-vector client; TCL_ERROR after releasing a failed lookup/type-check client.
-
static int GetComplexLineDataPoint(Line *linePtr, Tcl_Size index, double *xPtr, double *yPtr)
Grid geometry (rbcGrPolar.c)
- group Polar grid geometry internals
Private data-plane helpers; axes and grid records are borrowed.
Mapping requires cleared destination caches and does not draw labels.
Functions
-
static int GetPolarRadiusRange(Grid *gridPtr, PolarRadiusRange *rangePtr)
Bound radii intersecting the grid’s Cartesian viewport rectangle.
A viewport spanning the origin has minimum radius zero. The maximum is the farthest corner distance, not a fully contained circle radius. Outputs are unspecified on failure. No mapping or allocation is performed.
- Parameters:
gridPtr – Borrowed grid with mapped X/Y axes.
rangePtr – Receives nearest and farthest distances from the origin.
- Returns:
TRUE for a finite nonempty radial range; FALSE for missing axes, logarithmic axes, invalid axis bounds or nonfinite distances.
-
static double PolarCompleteCircleRadius(Grid *gridPtr)
Find the largest origin-centered circle contained in the axis rectangle.
Returns zero for missing/logarithmic axes or an origin not strictly inside both ranges. Borrows prepared axes; unlike GetPolarRadiusRange, this helper does not independently validate finite bounds.
- Parameters:
gridPtr – [in] Borrowed grid with prepared finite linear axis bounds and mappings.
-
static int ClipPolarRay(Grid *gridPtr, double degrees, Point2D *pPtr, Point2D *qPtr)
Intersect a forward ray at a degree angle with the data viewport.
Requires prepared finite linear axis bounds and a finite angle. Uses slab parameters starting at zero; directions within DBL_EPSILON of zero are parallel. Returns FALSE for missing axes or no forward intersection. On success writes data-space endpoints in increasing ray distance, not pixels.
- Parameters:
gridPtr – [in] Borrowed grid with prepared finite linear axis bounds and mappings.
degrees – [in] Finite forward-ray angle in degrees.
pPtr – [out] Required output for the nearer visible data-space endpoint, valid on TRUE.
qPtr – [out] Required output for the farther visible data-space endpoint, valid on TRUE.
-
static void MapCircle(Graph *graphPtr, Grid *gridPtr, double radius, Segment2D *segments)
Write one sampled polar circle into caller-owned segment storage.
Requires room for POLAR_CIRCLE_SEGMENTS entries and current mapped axes. Maps consecutive angular samples through Rbc_Map2D; neither allocates nor clips complete strokes. The caller owns the buffer and its eventual clipping.
- Parameters:
graphPtr – [in] Borrowed graph with current axis mapping and inversion state.
gridPtr – [in] Borrowed grid with prepared finite linear axis bounds and mappings.
radius – [in] Finite positive circle radius in Cartesian data units.
segments – [out] Caller-owned buffer of at least POLAR_CIRCLE_SEGMENTS records; receives mapped pixel segments.
-
static int MapPolarSpoke(Graph *graphPtr, Grid *gridPtr, double degrees, Segment2D *segmentPtr)
Clip a degree-angle ray and map its endpoints to screen coordinates.
Returns FALSE if the ray misses the viewport; output is valid only on success. Borrows graph/grid state, allocates nothing and does not separately check mapped endpoints for finiteness.
- Parameters:
graphPtr – [in] Borrowed graph with current axis mapping and inversion state.
gridPtr – [in] Borrowed grid with prepared finite linear axis bounds and mappings.
degrees – [in] Finite ray angle in degrees.
segmentPtr – [out] Required mapped pixel segment output; valid only on TRUE.
-
static double PolarGridSegmentValue(Graph *graphPtr, Grid *gridPtr, const Segment2D *segmentPtr)
Recover the data-X tick represented by an axis grid segment.
Uses the mapped origin for the other coordinate and selects screen X or Y according to graph inversion. Requires a segment from the selected X axis; it is not a general segment-to-radius conversion.
- Parameters:
graphPtr – [in] Borrowed graph with current axis mapping and inversion state.
gridPtr – [in] Borrowed grid with prepared finite linear axis bounds and mappings.
segmentPtr – [in] Borrowed mapped segment produced for this grid X axis; inversion selects the coordinate to invert.
-
static void MapPolarCircles(Graph *graphPtr, Grid *gridPtr, const PolarRadiusRange *rangePtr)
Build the radial segment cache from positive visible X-axis ticks.
Borrows a validated radial range. Frees temporary axis segments on every allocation/count exit. Transfers the new array to gridPtr->x only on success; callers must already have released old caches. Count overflow or attempted allocation failure silently leaves the destination unchanged.
- Parameters:
graphPtr – [in] Borrowed graph with current axis mapping and inversion state.
gridPtr – [inout] Grid supplying axes/minor policy and receiving owned x-segment storage; old x cache must be cleared.
rangePtr – [in] Borrowed validated minimum/maximum radii intersecting the viewport.
-
static void MapPolarSpokes(Graph *graphPtr, Grid *gridPtr)
Build the angular segment cache from global major and optional minor ticks.
Uses gridPtr axes/minor policy and graphPtr->gridPtr angular arrays. Transfers visible segments to gridPtr->y; frees an allocation with no visible rays. Old caches must be cleared by the caller. Overflow/allocation failure returns without a diagnostic or a destination update.
- Parameters:
graphPtr – [in] Borrowed mapped graph whose global grid supplies angular tick arrays.
gridPtr – [inout] Grid supplying axes/minor policy and receiving owned y-segment storage; old y cache must be cleared.
-
void Rbc_MapPolarGrid(Graph *graphPtr, Grid *gridPtr)
Populate polar circle and spoke caches using prepared linear axes.
Requires empty destination caches and a live global grid for angular ticks. An invalid radial viewport returns without mapping. The two allocations are independent, so partial geometry is possible on allocation failure. Does not draw, notify, schedule layout or free old caches.
- Parameters:
graphPtr – [in] Borrowed graph with prepared mappings and a live global grid for angular settings.
gridPtr – [inout] Grid with empty x/y caches; receives owned mapped segments independently for circles and spokes.
-
static void SmithImpedanceToGamma(double resistance, double reactance, double *realPtr, double *imagPtr)
Convert normalized grid impedance to Cartesian reflection coordinates.
Writes both output scalars using direct squared terms. Intended for validated grid values, not arbitrary external complex data: no denominator, overflow or finite-result check is provided. Owns no storage.
- Parameters:
resistance – [in] Normalized nonnegative finite grid resistance; arithmetic must remain within the unchecked formula domain.
reactance – [in] Normalized finite grid reactance; this is not a physical impedance input.
realPtr – [out] Required output for the Cartesian real Gamma component; no finite-result validation.
imagPtr – [out] Required output for the Cartesian imaginary Gamma component; no finite-result validation.
-
static void SmithGridValueToGamma(int admittance, double realValue, double imagValue, double *realPtr, double *imagPtr)
Convert normalized impedance or admittance grid coordinates.
Delegates to SmithImpedanceToGamma, then negates both outputs for admittance. No reference-impedance scaling is applied; inputs are already normalized. Inherits the unchecked arithmetic domain of the underlying grid helper.
- Parameters:
admittance – [in] Nonzero selects admittance orientation; zero selects impedance.
realValue – [in] Normalized nonnegative resistance or conductance for the chosen domain.
imagValue – [in] Normalized signed reactance or susceptance for the chosen domain.
realPtr – [out] Required real Gamma output; no reference-impedance scaling or finite-result validation.
imagPtr – [out] Required imaginary Gamma output; no reference-impedance scaling or finite-result validation.
-
static int SmithUnitCircleVisible(Grid *gridPtr)
Test whether linear axis bounds contain the entire Smith unit circle.
Returns FALSE for missing/logarithmic axes; otherwise requires both ranges to contain [-1,1], inclusively. Does not test graph visibility or text bounds.
- Parameters:
gridPtr – [in] Borrowed grid with prepared bounds; missing or logarithmic axes return FALSE.
-
static void MapSmithResistanceCircle(Graph *graphPtr, Grid *gridPtr, double resistance, int admittance, Segment2D *segments)
Write a sampled normalized resistance or conductance circle.
Requires SMITH_CIRCLE_SEGMENTS writable entries and validated nonnegative resistance. Center is r/(r+1), radius 1/(r+1); admittance negates both coordinates before mapping. Allocates nothing and leaves clipping to drawing.
- Parameters:
graphPtr – [in] Borrowed graph with current axis mapping and inversion state.
gridPtr – [in] Borrowed grid with prepared finite linear axis bounds and mappings.
resistance – [in] Validated normalized nonnegative resistance or conductance.
admittance – [in] Nonzero selects admittance orientation; zero selects impedance.
segments – [out] Caller-owned buffer of at least SMITH_CIRCLE_SEGMENTS records; receives mapped pixel segments.
-
static Point2D SmithReactanceGamma(double reactance, double t, int admittance)
Parameterize a constant-reactance or constant-susceptance grid arc.
For t below one, the real component of normalized impedance or admittance is t/(1-t). At t >= 1 the infinite-real endpoint is supplied explicitly: (+1,0) for impedance, (-1,0) for admittance. The helper does not validate arbitrary external inputs and owns no resources.
- Parameters:
reactance – Normalized finite reactive value chosen by grid mapping.
t – Arc parameter from zero through one.
admittance – Nonzero selects the admittance orientation.
- Returns:
A point in the Cartesian Gamma plane, before screen mapping.
-
static Point2D SmithReactancePoint(Graph *graphPtr, Grid *gridPtr, double reactance, double t, int admittance)
Screen-map one point of a normalized reactive contour.
Borrows prepared axes and delegates parameter handling to SmithReactanceGamma. Returns mapped coordinates without an additional finite-result check.
- Parameters:
graphPtr – [in] Borrowed graph with current axis mapping and inversion state.
gridPtr – [in] Borrowed grid with prepared finite linear axis bounds and mappings.
reactance – [in] Normalized finite signed reactance or susceptance.
t – [in] Contour parameter in [0,1]; one selects the explicit infinite-real endpoint.
admittance – [in] Nonzero selects admittance orientation; zero selects impedance.
-
static int ClipSegmentParameter(double p, double q, double *enterPtr, double *exitPtr)
Tighten a segment parameter interval against one half-plane.
Updates caller-owned enter/exit bounds, conventionally initialized to [0,1]. A parallel segment is accepted iff q is nonnegative. Returns FALSE on rejection; callers must discard the accumulated interval on failure.
- Parameters:
p – [in] Signed half-plane denominator: negative tightens entry, positive tightens exit, zero is parallel.
q – [in] Signed half-plane numerator; a parallel segment is accepted when q is nonnegative.
enterPtr – [inout] Required lower parameter bound, initially zero for a fresh segment clip.
exitPtr – [inout] Required upper parameter bound, initially one; discard the interval after rejection.
-
static int ClipSegmentToGridViewport(Grid *gridPtr, Point2D p, Point2D q, Point2D *enterPointPtr, Point2D *exitPointPtr)
Clip data-space segment endpoints against the selected axis rectangle.
Requires prepared bounds and finite input points. Preserves segment order and writes entry/exit points on success. Missing axes, rejection or nonfinite computed outputs return FALSE; output values are only valid on TRUE. Does not map to screen coordinates or clip stroke thickness.
- Parameters:
gridPtr – [in] Borrowed grid with prepared finite linear axis bounds and mappings.
p – [in] Finite data-space segment start.
q – [in] Finite data-space segment end.
enterPointPtr – [out] Required clipped data-space entry output; valid only on TRUE.
exitPointPtr – [out] Required clipped data-space exit output; valid only on TRUE.
-
static void MapSmithReactanceArc(Graph *graphPtr, Grid *gridPtr, double reactance, int admittance, Segment2D *segments)
Write a sampled constant-reactance or constant-susceptance contour.
Requires SMITH_ARC_SEGMENTS writable entries and prepared axes. Samples t from zero to one, including the explicit infinite-real endpoint. Allocates nothing; mapping and clipping responsibilities remain separate.
- Parameters:
graphPtr – [in] Borrowed graph with current axis mapping and inversion state.
gridPtr – [in] Borrowed grid with prepared finite linear axis bounds and mappings.
reactance – [in] Validated normalized signed reactance or susceptance.
admittance – [in] Nonzero selects admittance orientation; zero selects impedance.
segments – [out] Caller-owned buffer of at least SMITH_ARC_SEGMENTS records; receives mapped pixel chords.
-
static void MapSmithResistanceGrid(Graph *graphPtr, Grid *gridPtr)
Allocate and publish Smith real-component circle segments.
Uses global major/minor lists and domain selection with the supplied grid axes/minor policy. In both-domain mode omits admittance zero circles already represented by impedance. Requires cleared destination caches. Checked count overflow or attempted-allocation failure returns silently; successful storage is owned by gridPtr->x.
- Parameters:
graphPtr – [in] Borrowed mapped graph whose global grid supplies Smith tick lists and domain selection.
gridPtr – [inout] Grid supplying axes/minor policy; empty x cache receives owned circle segments on success.
-
static void MapSmithReactanceGrid(Graph *graphPtr, Grid *gridPtr)
Allocate Smith reactive arcs and the shared real diameter.
Each configured magnitude supplies positive and negative arcs in each selected domain. The zero-reactive diameter is emitted once, even when no nonzero magnitudes exist. Requires cleared caches; overflow/allocation failure leaves them unchanged. Successful storage transfers to gridPtr->y.
- Parameters:
graphPtr – [in] Borrowed mapped graph whose global grid supplies Smith tick lists and domain selection.
gridPtr – [inout] Grid supplying axes/minor policy; empty y cache receives owned arcs and the shared real diameter.
-
void Rbc_MapSmithGrid(Graph *graphPtr, Grid *gridPtr)
Populate Smith grid caches for the selected global domain.
Returns for missing/logarithmic axes. Requires prepared bounds, validated tick arrays and empty caches. Circle and reactive allocations are independent and can produce partial geometry on failure. Does not draw or free old data.
- Parameters:
graphPtr – [in] Borrowed mapped graph with validated global Smith tick lists and domain settings.
gridPtr – [inout] Grid with empty x/y caches; receives independently allocated circle and reactive geometry.
-
static int GetPolarRadiusRange(Grid *gridPtr, PolarRadiusRange *rangePtr)
Line and polar data transactions (rbcGrLine.c)
These helpers also cover the real parallel parameter input shared by graph line and polar elements. The documentation-only scope keeps private names distinct from similarly named helpers in other modules.
- group Line and polar data transactions
Source ownership, parallel parameters, notification policy and staged commit.
Functions
-
static void FreeLinePenColor(XColor *colorPtr)
Release an owned line-pen color unless it is NULL or COLOR_DEFAULT.
The sentinel represents inheritance rather than a Tk color allocation. Does not clear the caller’s pointer; callers must not release it twice.
- Parameters:
colorPtr – [in] Owned Tk color reference to release, or NULL/COLOR_DEFAULT for no action; caller clears its own field.
-
static int GetLineArrayByteCount(Tcl_Size count, size_t elementSize, size_t *bytesPtr)
Validate a count-to-byte multiplication without allocating storage.
Rejects negative counts, zero element size and SIZE_MAX overflow. Assigns bytesPtr only on success. Zero count is valid with a positive element size. Returns TCL_OK or TCL_ERROR without setting an interpreter diagnostic.
- Parameters:
count – [in] Requested element count; zero is valid and negative counts are rejected.
elementSize – [in] Positive size of one element in bytes; zero is rejected.
bytesPtr – [out] Required byte-count output, assigned only on TCL_OK.
-
static Tcl_Size LinePointCount(Element *elemPtr)
Return the current source point count for a line representation.
Complex mode uses Z length; X/Y mode uses the smaller length. Named sources are queried directly so pending notifications do not hide a resize. Literal slots use cached counts. Does not refresh cached pointers or deliver callbacks; a current count alone does not make cached sample storage current.
- Parameters:
elemPtr – [in] Borrowed line-family core with valid live vector records for any retained client IDs; cached arrays need not be synchronized.
-
static int GetLineDataPoint(Line *linePtr, Tcl_Size index, double *xPtr, double *yPtr)
Read a cached source sample and convert it to graph-plane coordinates.
Complex input delegates to GetComplexLineDataPoint. X/Y input checks cached paired length and non-NULL arrays. Polar X/Y requires finite theta/radius and converts radians to Cartesian coordinates; Cartesian X/Y copies directly, without rejecting nonfinite values. Returns a boolean; callers must reject unusable outputs and ensure borrowed arrays are synchronized before reading.
- Parameters:
linePtr – [in] Borrowed line with synchronized cached source arrays and coordinate-mode options.
index – [in] Original zero-based source index; out-of-range indices return FALSE.
xPtr – [out] Required Cartesian X output, separate from yPtr; use only on TRUE and check finiteness.
yPtr – [out] Required Cartesian Y output, separate from xPtr; use only on TRUE and check finiteness.
-
static void SyncComplexVector(ElemComplexVector *vPtr)
Refresh a complex slot’s borrowed length, capacity and array pointer.
Requires a live vecPtr of complex type. Does not own the array, install a callback, compute extrema, invalidate mapping or schedule redraw.
- Parameters:
vPtr – [inout] Complex source slot with a live complex vecPtr; refreshed array storage remains borrowed from that vector.
-
static void FreeComplexVector(ElemComplexVector *vPtr)
Detach a complex-vector client and zero the whole slot.
Accepts an empty slot. Does not destroy the source vector or free its borrowed numeric storage. The previous elemPtr owner association is also cleared.
- Parameters:
vPtr – [inout] Required initialized slot, possibly empty; its retained client is released and every field is zeroed.
-
static void ComplexVectorChangedProc(Tcl_Interp *interp, ClientData clientData, Rbc_VectorNotify notify)
Refresh or clear a stable complex-data slot on vector notification.
Client data must identify the committed line member. Destruction clears the client ID, vector, array, length and capacity. Update reacquires the vector and refreshes cached storage on success. Always marks axes and element mapping dirty, scheduling backing-store redraw only when not hidden or plotHidden. No partial changed-range accumulation is performed by this callback.
- Parameters:
interp – [inout] Borrowed interpreter for lookup and diagnostics; see Interpreter arguments.
clientData – [inout] Stable committed ElemComplexVector member with a live elemPtr owner; never temporary transaction storage.
notify – [in] Vector notification kind; DESTROY clears the source and other values take the update path.
-
static void ReplaceLineOptionObject(Tcl_Obj **objPtrPtr, Tcl_Obj *newObjPtr)
Replace one retained Tcl option object with balanced references.
An identical pointer is a no-op. Retains the replacement before releasing the old object; NULL clears the slot. Does not parse, configure or evaluate it.
- Parameters:
objPtrPtr – [inout] Required retained-object field; its old reference is released after retaining the replacement.
newObjPtr – [in] Borrowed replacement object, or NULL to clear the field; one reference is acquired unless already installed.
-
static int StageComplexData(Tcl_Interp *interp, Element *elemPtr, Tcl_Obj *objPtr, LineComplexDataTransaction *transactionPtr)
Replace a staged complex source only after candidate parsing succeeds.
Uses ParseComplexVectorObj, then releases an earlier staged client and transfers the new candidate. Failure leaves the earlier candidate untouched. The caller owns transaction cleanup; no callback is registered in temporary storage.
- Parameters:
interp – [inout] Borrowed interpreter for lookup and diagnostics; see Interpreter arguments.
elemPtr – [in] Borrowed live owner recorded in the candidate; must survive parsing and subsequent commit or cleanup.
objPtr – [in] Borrowed source specification; NULL or empty clears the source. Nonempty input must name a complex vector.
transactionPtr – [inout] Initialized transaction owning any earlier candidates; successful staging replaces only the selected candidate, preserving live line state.
-
static int PrepareLineComplexDataTransaction(Graph *graphPtr, Element *elemPtr, Line *linePtr, LineComplexDataTransaction *transactionPtr)
Prepare complex-source replacement and data-mode selection in option order.
Initializes a fresh transaction from the current mode. First configuration considers the retained default unless explicit -cdata was supplied. Processes canonical explicit options in caller order: nonempty -cdata selects complex, empty -cdata or ordinary data options select X/Y. Later mode selection does not excuse an invalid earlier complex source. Failure frees staged clients and zeros the transaction, leaving live line storage unchanged.
- Parameters:
graphPtr – [in] Borrowed owning graph supplying the live window, display and interpreter for resource operations.
elemPtr – [in] Borrowed core of linePtr supplying validated ordered option/value pairs and initial-configuration state.
linePtr – [in] Borrowed line corresponding to elemPtr, with candidate Tk option values installed and current derived resources still retained.
transactionPtr – [out] Fresh transaction storage with no owned candidates; initialized here. Commit only after TCL_OK; failure state is described above.
-
static void CommitLineComplexDataTransaction(Line *linePtr, LineComplexDataTransaction *transactionPtr)
Commit a prepared complex-source transaction into stable line storage.
In complex mode, transfers a staged slot and then registers its notification callback against linePtr->z; an unstaged complex slot remains unchanged. In X/Y mode, frees live and staged complex clients and clears retained -cdata. Stores the selected mode and clears staged ownership. Does not free external vectors or itself schedule graph redraw; preparation must already have passed.
- Parameters:
linePtr – [inout] Live destination line; prepared candidate fields replace the corresponding committed fields, releasing displaced resources.
transactionPtr – [inout] Successfully prepared transaction; moved ownership or staged bits are cleared for subsequent cleanup.
-
static void FreeLineComplexDataTransaction(LineComplexDataTransaction *transactionPtr)
Release an abandoned staged complex source and zero its transaction.
Safe after commit because staged ownership has been cleared. Does not release the live line source or change data mode.
- Parameters:
transactionPtr – [inout] Initialized, possibly empty or committed transaction; remaining owned candidates are released and the record is zeroed.
-
static void SyncLineParamVector(ElemVector *vPtr)
Refresh a live real parameter slot’s borrowed storage and extrema.
Requires a valid vecPtr. Copies length, capacity, array and vector range without geometry invalidation, notification delivery or ownership transfer.
- Parameters:
vPtr – [inout] Real parameter slot with a live vecPtr; cached borrowed storage and extrema are refreshed.
-
static void LineParamVectorChangedProc(Tcl_Interp *interp, ClientData clientData, Rbc_VectorNotify notify)
Refresh parallel parameter data without invalidating plotted geometry.
Destruction clears client identity and borrowed storage. Update reacquires the source and synchronizes it; failed lookup clears vector/array/count/capacity while retaining the client ID for later cleanup. Cached extrema are not reset on those clear paths. Does not reset axes, map geometry or request redraw.
- Parameters:
interp – [inout] Borrowed interpreter for lookup and diagnostics; see Interpreter arguments.
clientData – [inout] Stable committed ElemVector parameter member; teardown must detach its client before freeing the member.
notify – [in] Vector notification kind; DESTROY clears the source and other values take the update path.
-
static int StageLineParam(Tcl_Interp *interp, Element *elemPtr, Tcl_Obj *objPtr, LineParamTransaction *transactionPtr)
Parse and retain a replacement parameter candidate transactionally.
Accepts the common real-vector or numeric-expression-list input. On failure releases the local candidate and retains any earlier staged value. On success frees the earlier staged slot and transfers the candidate. Does not install parameter notifications until commit moves it to stable line storage.
- Parameters:
interp – [inout] Borrowed interpreter for lookup and diagnostics; see Interpreter arguments.
elemPtr – [in] Borrowed live owner recorded in the candidate; must survive parsing and subsequent commit or cleanup.
objPtr – [in] Borrowed source specification; NULL or empty clears the source. Nonempty input names a real vector or supplies a numeric-expression list.
transactionPtr – [inout] Initialized transaction owning any earlier candidates; successful staging replaces only the selected candidate, preserving live line state.
-
static int PrepareLineParamTransaction(Graph *graphPtr, Element *elemPtr, Line *linePtr, LineParamTransaction *transactionPtr)
Prepare parameter input from defaults and ordered explicit options.
Initializes a fresh transaction. On first configuration uses the retained default only when no explicit canonical -param occurs. Validates every explicit occurrence in order, including values superseded later. Failure frees staged storage and zeros the transaction. Length compatibility is a separate check.
- Parameters:
graphPtr – [in] Borrowed owning graph supplying the live window, display and interpreter for resource operations.
elemPtr – [in] Borrowed core of linePtr supplying validated ordered option/value pairs and initial-configuration state.
linePtr – [in] Borrowed line corresponding to elemPtr, with candidate Tk option values installed and current derived resources still retained.
transactionPtr – [out] Fresh transaction storage with no owned candidates; initialized here. Commit only after TCL_OK; failure state is described above.
-
static void CommitLineParamTransaction(Line *linePtr, LineParamTransaction *transactionPtr)
Transfer staged parameter ownership to the line and install its callback.
No-op without a staged candidate. Releases the old live slot, moves the new one, restores its owner pointer and registers LineParamVectorChangedProc for a named source. Clears candidate ownership for subsequent transaction cleanup.
- Parameters:
linePtr – [inout] Live destination line; prepared candidate fields replace the corresponding committed fields, releasing displaced resources.
transactionPtr – [inout] Successfully prepared transaction; moved ownership or staged bits are cleared for subsequent cleanup.
-
static void FreeLineParamTransaction(LineParamTransaction *transactionPtr)
Release a staged parameter candidate and zero its transaction.
Safe on an empty or committed transaction. Uses common slot cleanup for owned list arrays and retained vector clients, without destroying source vectors.
- Parameters:
transactionPtr – [inout] Initialized, possibly empty or committed transaction; remaining owned candidates are released and the record is zeroed.
-
static int LineParamConfigured(Line *linePtr)
Test whether the retained parameter option is nonempty.
Examines paramObjPtr text only, not current numeric length or client validity. A nonempty option whose external source became empty is still configured.
- Parameters:
linePtr – [in] Borrowed line-family record; source slots and option representations remain owned by the element.
-
static int LineParamLengthValidationNeeded(Element *elemPtr)
Decide whether configuration must validate parallel parameter length.
Returns true on initial configuration or an explicit canonical -param, -data, -x, -y or -cdata option. Other changes may proceed during a temporary mismatch caused by independently resized external vectors. Does not compare lengths.
- Parameters:
elemPtr – [in] Borrowed element with initial-configuration state and the ordered explicit option/value vector.
-
static Tcl_Size ProspectiveLinePointCount(Line *linePtr, const ElemDataTransaction *dataTransactionPtr, const LineComplexDataTransaction *complexDataTransactionPtr)
Count prospective data points using current named-vector lengths.
Uses the staged mode when a complex transaction is supplied. Complex mode selects staged or live Z storage; X/Y delegates to the common transaction count. Named sources are queried directly, while literals use their stored counts. Does not refresh arrays, deliver notifications or commit candidates.
- Parameters:
linePtr – [in] Borrowed line-family record; source slots and option representations remain owned by the element.
dataTransactionPtr – [in] Borrowed prepared ordinary-data transaction, or NULL to use committed X/Y slots.
complexDataTransactionPtr – [in] Borrowed prepared complex-data transaction, or NULL to use the committed mode and Z slot.
-
static int ValidateLineParamLength(Graph *graphPtr, Line *linePtr, const ElemDataTransaction *dataTransactionPtr, const LineComplexDataTransaction *complexDataTransactionPtr, const LineParamTransaction *paramTransactionPtr)
Require configured parameter length to match prospective data length.
Empty retained -param disables the check. Selects staged parameter storage when available, otherwise the live slot, querying current named-vector length. Obtains data length through ProspectiveLinePointCount. Returns TCL_ERROR with both counts on mismatch, TCL_OK otherwise. Does not refresh arrays, deliver notifications, commit candidates or free them.
- Parameters:
graphPtr – [in] Borrowed owning graph supplying the interpreter for a length-mismatch diagnostic.
linePtr – [in] Borrowed line with candidate retained -param text already installed and valid live source slots.
dataTransactionPtr – [in] Borrowed prepared ordinary-data transaction, or NULL to use committed X/Y slots.
complexDataTransactionPtr – [in] Borrowed prepared complex-data transaction, or NULL to use the committed mode and Z slot.
paramTransactionPtr – [in] Borrowed prepared parameter transaction, or NULL to use the committed parameter slot.
-
static void FreeLinePenColor(XColor *colorPtr)
Label placement and presentation (rbcGrPolar.c)
The formatting helpers may execute Tcl. Their contracts describe cancellation of the current drawing pass when callbacks mutate or destroy its graph.
- group Polar and Smith label internals
Positioning, formatting and screen/export presentation.
Geometry helpers borrow prepared graph state; formatting paths may evaluate Tcl callbacks.
Functions
-
static Tk_Anchor GetPolarRadialLabelAnchor(Graph *graphPtr)
Resolve the radial anchor from the global grid.
Automatic selection is TK_ANCHOR_SE; otherwise returns the configured anchor. Requires a live global grid and does not modify it.
- Parameters:
graphPtr – [in] Borrowed graph with live global grid anchor settings.
-
static Tk_Anchor GetInwardLabelAnchor(double degrees)
Choose one of eight inward text anchors from a degree direction.
Callers provide a normalized angle in [0,360). Sector boundaries lie at 22.5 degrees plus multiples of 45. This is a direction lookup only; it does not inspect text extents or guarantee the label fits inside a viewport.
- Parameters:
degrees – [in] Finite data angle in degrees, normalized to [0,360) for automatic anchor selection.
-
static Tk_Anchor GetPolarAngleLabelAnchor(Graph *graphPtr, double degrees)
Resolve a circular angular label anchor.
An explicit global-grid anchor wins; automatic mode uses the supplied data angle directly. No screen-axis inversion or descending-axis adjustment is performed by this helper.
- Parameters:
graphPtr – [in] Borrowed graph with live global grid angular-anchor settings.
degrees – [in] Finite data angle in degrees, normalized to [0,360) for automatic anchor selection.
-
static Tk_Anchor GetPolarSpokeLabelAnchor(Graph *graphPtr, const Segment2D *segmentPtr)
Anchor a label inward from the far end of a mapped spoke.
An explicit anchor wins. Otherwise derives direction from screen endpoints, negating screen Y; a degenerate segment selects CENTER. Borrows the segment and does not alter its geometry.
- Parameters:
graphPtr – [in] Borrowed graph with live global grid angular-anchor settings.
segmentPtr – [in] Borrowed mapped pixel spoke ordered from near to far; label belongs at its q endpoint.
-
static int GetPolarAngularLabelPosition(Graph *graphPtr, Grid *gridPtr, double completeRadius, double degrees, Point2D *pointPtr, Tk_Anchor *anchorPtr)
Choose a circular or clipped-spoke angular label position.
A positive completeRadius selects 90 percent of that radius and the data-angle anchor. Otherwise selects the far visible mapped ray endpoint and a screen-direction anchor. Returns FALSE for a missing ray or nonfinite position; outputs must only be consumed on success.
- Parameters:
graphPtr – [in] Borrowed graph with current axis mapping and inversion state.
gridPtr – [in] Borrowed grid with prepared finite linear axis bounds and mappings.
completeRadius – [in] Radius of a fully contained origin-centered circle; nonpositive selects clipped-spoke placement.
degrees – [in] Finite data angle in degrees, normalized to [0,360) for automatic anchor selection.
pointPtr – [out] Required output for mapped pixel position; consume only when TRUE is returned.
anchorPtr – [out] Required output for the text anchor; consume only when TRUE is returned.
-
static int GetPolarRadialLabelPosition(Graph *graphPtr, Grid *gridPtr, double radius, Point2D *pointPtr)
Map a positive radial tick on the zero-degree ray when visible.
Requires linear axes and a finite positive radius whose point (radius,0) lies inside both data ranges. The origin itself need not be visible. Returns TRUE only for finite mapped coordinates; output is success-only.
- Parameters:
graphPtr – [in] Borrowed graph with current axis mapping and inversion state.
gridPtr – [in] Borrowed grid with prepared finite linear axis bounds and mappings.
radius – [in] Finite positive data radius; label point is (radius,0).
pointPtr – [out] Required output for mapped pixel position; consume only when TRUE is returned.
-
static void DrawPolarRadialLabels(Graph *graphPtr, Drawable drawable, Grid *gridPtr)
Draw radial labels through a temporary screen text renderer.
Allocates an X-axis major-tick snapshot and formatted tick labels, freeing each after use. A NULL formatted label terminates the loop. Borrows graph/grid/drawable and copies the relevant axis text style with rotation zero. Requires showTicks on that axis. Screen positions are rounded; the renderer is ended before returning. Formatting can evaluate Tcl; callers must retain graph lifetime. A cancelled formatter stops the loop before copied style or component resources are used again.
- Parameters:
graphPtr – [inout] Caller-protected graph with prepared label geometry; formatter callbacks can invalidate the pass.
drawable – [in] Borrowed compatible screen destination; no ownership is acquired.
gridPtr – [in] Borrowed prepared grid/axis resources; no cached resource may be reused after formatter cancellation.
-
static char *FormatGridLabel(Graph *graphPtr, Tcl_Obj *prefixObjPtr, const char *domain, const char *value, Tcl_DString *dsPtr)
Evaluate a grid label prefix while guarding the current drawing pass.
Borrows an initialized default-label DString, prefix and numeric text. Appends widget path, optional domain and value to an owned prefix copy. Preserves interpreter state; errors report a background exception and keep default text. Uses the existing axis-format guard to reject recursive rendering and detect mutation. Returns NULL on invalidation, scheduling a fresh redraw; callers must free the DString and stop before accessing cached grid/style resources. The enclosing widget command or display wrapper must preserve graph lifetime.
- Parameters:
graphPtr – [inout] Caller-protected graph with live interpreter/window; formatting may invalidate its drawing state.
prefixObjPtr – [in] Borrowed command-prefix object, or NULL for default text; duplicated before arguments are appended.
domain – [in] Borrowed NUL-terminated domain argument, or NULL to omit that argument.
value – [in] Borrowed NUL-terminated numeric spelling copied into the callback command.
dsPtr – [inout] Initialized caller-owned DString containing default text; caller frees it even when return is NULL.
-
static char *FormatPolarAngleLabel(Graph *graphPtr, double degrees, Tcl_DString *dsPtr)
Format a degree label into a caller-released DString.
Initializes dsPtr and returns its borrowed buffer. Default text is g plus a degree sign. A nonempty command prefix receives widget path and numeric degrees in the current evaluation context. Success replaces all text, including an empty result; failure reports a background exception and retains default text. Preserves interpreter state and returns NULL if formatting invalidates the graph. Caller must still free dsPtr on NULL and abandon cached drawing state.
- Parameters:
graphPtr – [inout] Caller-protected graph whose global grid supplies the angular command prefix.
degrees – [in] Finite data angle in degrees, normalized to [0,360) for automatic anchor selection.
dsPtr – [out] Unowned DString storage initialized here; caller must free it on every return path.
-
static void DrawPolarAngularLabels(Graph *graphPtr, Drawable drawable, Grid *gridPtr, double completeRadius)
Draw angular labels through a temporary screen text renderer.
Reads global major angle ticks and invokes FormatPolarAngleLabel. Empty formatted strings suppress drawing. Borrows graph/grid/drawable and copies the relevant axis text style with rotation zero. Requires showTicks on that axis. Screen positions are rounded; the renderer is ended before returning. Formatting can evaluate Tcl; callers must retain graph lifetime. A cancelled formatter stops the loop before copied style or component resources are used again.
- Parameters:
graphPtr – [inout] Caller-protected graph with prepared label geometry; formatter callbacks can invalidate the pass.
drawable – [in] Borrowed compatible screen destination; no ownership is acquired.
gridPtr – [in] Borrowed prepared grid/axis resources; no cached resource may be reused after formatter cancellation.
completeRadius – [in] Radius of a fully contained origin-centered circle; nonpositive selects clipped-spoke placement.
-
void Rbc_DrawPolarLabels(Graph *graphPtr, Drawable drawable)
Draw the visible global polar grid labels.
Returns when the global grid is missing or hidden. Borrows current mapped graph resources and the destination drawable. Does not map segments. Runs radial labels, checks Rbc_GraphCallbackValid, then chooses the circular or clipped-spoke angular layout. Inner loops stop immediately when their formatter reports invalidation; the caller retains graph record lifetime.
- Parameters:
graphPtr – [inout] Caller-protected graph with prepared label geometry; formatter callbacks can invalidate the pass.
drawable – [in] Borrowed compatible screen destination; no ownership is acquired.
-
static char *FormatSmithLabel(Graph *graphPtr, Tcl_Obj *commandObjPtr, int admittance, int imaginary, double value, Tcl_DString *dsPtr)
Format a normalized Smith value into a caller-released DString.
Initializes dsPtr and returns its borrowed buffer. Real defaults use g; reactive defaults add signed j notation. A nonempty prefix receives widget path, impedance/admittance domain and original signed numeric value. Empty success suppresses text; errors report a background exception and keep the default. Preserves interpreter state; returns NULL on graph invalidation. The caller frees dsPtr even on NULL and stops using cached drawing state.
- Parameters:
graphPtr – [inout] Caller-protected graph with live interpreter/window; formatting may cancel its drawing pass.
commandObjPtr – [in] Borrowed command prefix, or NULL for default formatting.
admittance – [in] Nonzero selects admittance orientation; zero selects impedance.
imaginary – [in] Nonzero requests signed j notation in default text; zero requests real-value notation.
value – [in] Original signed normalized value passed numerically to the callback, without j decoration.
dsPtr – [out] Unowned DString storage initialized here; caller frees it even after a NULL return.
-
static void DrawSmithRealLabels(Graph *graphPtr, Drawable drawable, Grid *gridPtr, int admittance)
Draw Smith real labels through a temporary screen text renderer.
Reads global real major ticks for one normalized domain and invokes FormatSmithLabel; empty strings suppress drawing. Zero values use inward horizontal anchors, other values are above/below the real axis by domain. Borrows graph/grid/drawable and copies the relevant axis text style with rotation zero. Requires showTicks on that axis. Screen positions are rounded; the renderer is ended before returning. Formatting can evaluate Tcl; callers must retain graph lifetime. A cancelled formatter stops the loop before copied style or component resources are used again.
- Parameters:
graphPtr – [inout] Caller-protected graph with prepared label geometry; formatter callbacks can invalidate the pass.
drawable – [in] Borrowed compatible screen destination; no ownership is acquired.
gridPtr – [in] Borrowed prepared grid/axis resources; no cached resource may be reused after formatter cancellation.
admittance – [in] Nonzero selects admittance orientation; zero selects impedance.
-
static void PolarRadialLabelsExport(Graph *graphPtr, Rbc_ExportContext *exportPtr, Grid *gridPtr)
Export radial labels through a temporary output renderer.
Allocates/frees X-axis ticks and each formatted tick label; NULL formatting stops the loop. Applies the same two-pixel offset as screen drawing. Borrows the export context; ends the renderer on every return. Requires showTicks on the relevant axis and copies its style with rotation zero. Retains fractional coordinates rather than rounding as on screen. May evaluate Tcl; formatter invalidation stops traversal before cached resources are reused. Export errors remain owned by the export context.
- Parameters:
graphPtr – [inout] Caller-protected graph with prepared label geometry; formatter callbacks can invalidate the pass.
exportPtr – [inout] Borrowed initialized document context; outer caller owns clipping, error handling and finalization.
gridPtr – [in] Borrowed prepared grid/axis resources; no cached resource may be reused after formatter cancellation.
-
static void PolarAngularLabelsExport(Graph *graphPtr, Rbc_ExportContext *exportPtr, Grid *gridPtr, double completeRadius)
Export angular labels through a temporary output renderer.
Uses global major angle ticks, the shared position/anchor helpers and FormatPolarAngleLabel; empty formatted text is omitted. Borrows the export context; ends the renderer on every return. Requires showTicks on the relevant axis and copies its style with rotation zero. Retains fractional coordinates rather than rounding as on screen. May evaluate Tcl; formatter invalidation stops traversal before cached resources are reused. Export errors remain owned by the export context.
- Parameters:
graphPtr – [inout] Caller-protected graph with prepared label geometry; formatter callbacks can invalidate the pass.
exportPtr – [inout] Borrowed initialized document context; outer caller owns clipping, error handling and finalization.
gridPtr – [in] Borrowed prepared grid/axis resources; no cached resource may be reused after formatter cancellation.
completeRadius – [in] Radius of a fully contained origin-centered circle; nonpositive selects clipped-spoke placement.
-
void Rbc_PolarLabelsExport(Graph *graphPtr, Rbc_ExportContext *exportPtr)
Export the visible global polar grid labels.
Returns when the global grid is missing or hidden. Borrows current mapped graph resources and the export context. Does not map segments. Runs radial labels, checks Rbc_GraphCallbackValid, then chooses the circular or clipped-spoke angular layout. Inner loops stop immediately when their formatter reports invalidation; the caller retains graph record lifetime.
- Parameters:
graphPtr – [inout] Caller-protected graph with prepared label geometry; formatter callbacks can invalidate the pass.
exportPtr – [inout] Borrowed initialized document context; outer caller owns clipping, error handling and finalization.
-
static Tk_Anchor GetSmithReactiveEdgeAnchor(const Point2D *enterPtr, const Point2D *exitPtr)
Choose an inward anchor at a clipped contour entry point.
Uses reversed local screen direction from exit to entry, compensating for downward screen Y. Degenerate segments select CENTER. No text measurement or viewport containment guarantee is made.
- Parameters:
enterPtr – [in] Borrowed finite mapped pixel entry point.
exitPtr – [in] Borrowed finite mapped pixel exit point defining inward direction.
-
static int GetSmithReactiveLabelPosition(Graph *graphPtr, Grid *gridPtr, double reactive, int admittance, Point2D *pointPtr, Tk_Anchor *anchorPtr)
Locate a reactive label at the unit circle or first visible contour entry.
When the complete unit circle is visible, scales its r=0/g=0 point by 0.94 and uses its data-angle anchor. Otherwise scans the same 90-segment contour used for drawing, clips each chord in data space, and takes the first visible entry with a screen-direction anchor. FALSE means no usable finite position; outputs are success-only. No Tcl callback or allocation occurs.
- Parameters:
graphPtr – [in] Borrowed graph with current axis mapping and inversion state.
gridPtr – [in] Borrowed grid with prepared finite linear axis bounds and mappings.
reactive – [in] Validated normalized signed reactance or susceptance.
admittance – [in] Nonzero selects admittance orientation; zero selects impedance.
pointPtr – [out] Required output for mapped pixel position; consume only when TRUE is returned.
anchorPtr – [out] Required output for the text anchor; consume only when TRUE is returned.
-
static void DrawSmithReactiveLabels(Graph *graphPtr, Drawable drawable, Grid *gridPtr, int admittance)
Draw Smith reactive labels through a temporary screen text renderer.
Formats both signs of each global major reactive magnitude for one domain. Uses GetSmithReactiveLabelPosition and skips invisible contours. Borrows graph/grid/drawable and copies the relevant axis text style with rotation zero. Requires showTicks on that axis. Screen positions are rounded; the renderer is ended before returning. Formatting can evaluate Tcl; callers must retain graph lifetime. A cancelled formatter stops the loop before copied style or component resources are used again.
- Parameters:
graphPtr – [inout] Caller-protected graph with prepared label geometry; formatter callbacks can invalidate the pass.
drawable – [in] Borrowed compatible screen destination; no ownership is acquired.
gridPtr – [in] Borrowed prepared grid/axis resources; no cached resource may be reused after formatter cancellation.
admittance – [in] Nonzero selects admittance orientation; zero selects impedance.
-
void Rbc_DrawSmithLabels(Graph *graphPtr, Drawable drawable)
Draw the visible global Smith grid labels.
Returns when the global grid is missing or hidden. Borrows current mapped graph resources and the destination drawable. Does not map segments. Dispatches real then reactive labels for each selected Smith domain. Checks callback validity between phases and domains; inner loops stop on cancellation. The enclosing caller retains graph record lifetime.
- Parameters:
graphPtr – [inout] Caller-protected graph with prepared label geometry; formatter callbacks can invalidate the pass.
drawable – [in] Borrowed compatible screen destination; no ownership is acquired.
-
static void SmithRealLabelsExport(Graph *graphPtr, Rbc_ExportContext *exportPtr, Grid *gridPtr, int admittance)
Export Smith real labels through a temporary output renderer.
Uses the selected domain and global real major ticks. Shares normalized conversion, formatting and domain-dependent offsets with screen drawing. Borrows the export context; ends the renderer on every return. Requires showTicks on the relevant axis and copies its style with rotation zero. Retains fractional coordinates rather than rounding as on screen. May evaluate Tcl; formatter invalidation stops traversal before cached resources are reused. Export errors remain owned by the export context.
- Parameters:
graphPtr – [inout] Caller-protected graph with prepared label geometry; formatter callbacks can invalidate the pass.
exportPtr – [inout] Borrowed initialized document context; outer caller owns clipping, error handling and finalization.
gridPtr – [in] Borrowed prepared grid/axis resources; no cached resource may be reused after formatter cancellation.
admittance – [in] Nonzero selects admittance orientation; zero selects impedance.
-
static void SmithReactiveLabelsExport(Graph *graphPtr, Rbc_ExportContext *exportPtr, Grid *gridPtr, int admittance)
Export Smith reactive labels through a temporary output renderer.
Formats both signs of global major reactive magnitudes and uses the same visible contour placement as screen drawing. Borrows the export context; ends the renderer on every return. Requires showTicks on the relevant axis and copies its style with rotation zero. Retains fractional coordinates rather than rounding as on screen. May evaluate Tcl; formatter invalidation stops traversal before cached resources are reused. Export errors remain owned by the export context.
- Parameters:
graphPtr – [inout] Caller-protected graph with prepared label geometry; formatter callbacks can invalidate the pass.
exportPtr – [inout] Borrowed initialized document context; outer caller owns clipping, error handling and finalization.
gridPtr – [in] Borrowed prepared grid/axis resources; no cached resource may be reused after formatter cancellation.
admittance – [in] Nonzero selects admittance orientation; zero selects impedance.
-
void Rbc_SmithLabelsExport(Graph *graphPtr, Rbc_ExportContext *exportPtr)
Export the visible global Smith grid labels.
Returns when the global grid is missing or hidden. Borrows current mapped graph resources and the export context. Does not map segments. Dispatches real then reactive labels for each selected Smith domain. Checks callback validity between phases and domains; inner loops stop on cancellation. The enclosing caller retains graph record lifetime.
- Parameters:
graphPtr – [inout] Caller-protected graph with prepared label geometry; formatter callbacks can invalidate the pass.
exportPtr – [inout] Borrowed initialized document context; outer caller owns clipping, error handling and finalization.
-
static Tk_Anchor GetPolarRadialLabelAnchor(Graph *graphPtr)
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 PolarRadiusRange
Computed finite radial interval.