Global

Members

(constant) BACKTICK_HIGHLIGHT_MATCH_CLASS

Class name for v-html mirror spans; style with :deep(.backtick-highlight-match) in the host.

Source:

(constant) DATA_VERSION :number

The version of the JSON data format of the scene, which matches the major version number of the app starting from version 5.0.

Type:
  • number
Source:

(constant) DEFAULT_SIMULATION_ENGINE_CONFIGS

Default global tuning values for each primitive-based simulation engine. Stored user preferences contain only values which override these defaults.

Source:

(constant) FLOAT32_EPSILON

Relative spacing of IEEE 754 binary32 values around 1.

Source:

(constant) FN1

One-argument functions: LaTeX command → math.js name

Source:

(constant) FORMULA_MODULE_TOOLTIP_MAX_LINES

Max tooltip lines when listing distinct expanded values across instances/rows. When exceeded, shows first (this − 2) value rows, an ellipsis line, then the last row.

Source:

(constant) FOR_IF_DEFAULTS

Get a value from an object by a dot-separated key path. Numeric segments are treated as array indices.

Source:

(constant) GREEK_SYMBOL

LaTeX math-mode command (no leading ) → math.js symbol name

Source:

(constant) JSON_INNER_COLLAPSE_THRESHOLD

Inner length (between { and }) above which we collapse the segment in the UI.

Source:

(constant) LITERAL_NUMERIC_TOKEN

Single JS-style numeric token (no thousands separators).

Source:

(constant) MODULE_EDITOR_LIST

One sidebar list may have selection at a time; add keys when adding new lists (see clearOtherModuleSidebarLists).

Source:

(constant) PARAM_CURVE_POINT_TOLERANCE

Position tolerance for parametric curve endpoint checks (closed loop and piece junctions).

Source:

(constant) PAREN_HIGHLIGHT_MATCH_CLASS

Class name for v-html mirror spans; style with :deep(.paren-highlight-match) in the host.

Source:

(constant) PRIMITIVE_CURVE_REFERENCE_PREFIX

Unicode diagnostic delimiters keep references distinct from JSON, i18next interpolation, HTML, and the Markdown-like link syntax used by the app. The short pc type tag keeps raw console/integration warnings readable.

Source:

(constant) usePreferencesStore

Create a Vue store for application preferences that persist to localStorage

Source:

(constant) useSceneStore

Create a Vue store for the scene, which is a wrapper around the Ray Optics Simulation core library Scene class. /** Create a Vue store for the scene, which is a wrapper around the Ray Optics Simulation core library Scene class.

Source:

(constant) useStatusStore

Create a Vue store for application status

Source:

(constant) useThemeStore

Create a Vue store for theme properties, which manages the nested theme structure from Scene.

Source:

(constant) vTooltipPopover

Vue directive for handling Bootstrap tooltips and popovers Usage:

  • For tooltips: v-tooltip-popover="{ title: 'Tooltip text' }"
  • For popovers: v-tooltip-popover:popover="{ title: 'Title', content: 'Content', popoverImage: 'image.svg' }"
Source:

Methods

CircleObjMixin(Base) → {T}

The mixin for the scene objects that are defined by a circle.

Parameters:
Name Type Description
Base T
Source:
Returns:
Type
T

CurveObjMixin(Base) → {T}

The mixin for the scene objects whose boundary is defined by a sequence of cubic Bezier curves, either forming a closed loop or an open polyline.

Subclasses that extend this mixin may override:

  • static allowOpen (default false): whether construction allows the user to finish with an open (non-closed) curve by double-clicking the last committed point. When false, the only way to finish is to click on the first anchor point (closed shape), matching the legacy CurveGlass behavior.
Parameters:
Name Type Description
Base T
Source:
Returns:
Type
T

LineObjMixin(Base) → {T}

The mixin for the scene objects that are defined by a line segment.

Parameters:
Name Type Description
Base T
Source:
Returns:
Type
T

ParamCurveObjMixin(Base) → {T}

The mixin for the scene objects that are defined by a line segment.

Parameters:
Name Type Description
Base T
Source:
Returns:
Type
T

_applyPiecesJoinedWarning()

Set or clear the pieces-not-joined warning after a successful path build. Glass types run additional checks in validateCurve(); this only manages the junction warning.

Source:

_ensureCubicBezierPathReady() → {boolean}

Rebuild path when switching to cubic Bezier if cached samples lack derivatives or Bezier list.

Source:
Returns:

Whether the path is usable (or rebuild succeeded).

Type
boolean

_pathPairToHermiteBezier(p1, p2) → {Bezier}

Cubic Bezier matching position and (dx/dt, dy/dt) at two consecutive samples; u in [0,1] maps linearly to t in [p1.t, p2.t].

Parameters:
Name Type Description
p1 Object
p2 Object
Source:
Returns:
Type
Bezier

allocateInteractionIndexBuffers(buffers) → {number}

Allocate exact-sized source-index buffers and their slot-major destination ranges after the counting pass.

Parameters:
Name Type Description
buffers Array.<Object>
Source:
Returns:

Total number of slots required in the destination buffer.

Type
number

appendPartialDerivatives(dag, options) → {Object}

Append labeled first partial derivative nodes to a formula DAG.

The input DAG is not mutated. Existing node IDs are preserved, and derivative nodes are appended without interning or post-pass deduplication.

Parameters:
Name Type Description
dag Object

DAG containing the labeled source node.

Properties
Name Type Attributes Description
root number <optional>

Root node ID.

nodes Array.<Object>

DAG nodes.

options Object

Derivative request.

Source:
Returns:

New DAG plus successful derivative nodes and skipped derivative errors.

Type
Object

applyTextareaAutoResize()

Sets textarea height from content. Returns false if skipped (hidden / not measurable); does not write a zero height in that case.

Source:

arePiecesJoined() → {boolean}

Check whether the end of each piece meets the start of the next (within floating point error). Lazy-generates the path if needed.

Source:
Returns:

True if all piece junctions coincide, false otherwise

Type
boolean

buildBacktickHighlightHtml(text, matchClassopt)

Safe HTML for a pre-wrapped highlight layer; all backtick math blocks are highlighted.

Parameters:
Name Type Attributes Description
text string | null | undefined
matchClass string <optional>
Source:

buildBvh(curveEntries, optionsopt) → {Object}

Build a BVH for primitive-curve entries.

Small input sets are built directly by recursive longest-axis weighted median splits. Larger input sets are first divided into spatially consecutive groups without regard to their originating scene object. Each group is packed into leaves using the configured leaf size for each curve kind, and the group roots are connected by a Morton hierarchy. A group ends when adjacent curve bounds are no longer local or its bounds exceed the configured maximum extent.

Prepared entries provide geometry and bounds, avoiding duplicate curve preparation. Raw curve entries remain accepted by this standalone builder.

Parameters:
Name Type Attributes Description
curveEntries Array.<BvhCurveEntry>
options Object <optional>
Properties
Name Type Attributes Default Description
lineLeafSize number <optional>
4

Target number of ordinary or smooth line segments in a homogeneous leaf.

arcLeafSize number <optional>
2

Target number of circular arcs or circles in a homogeneous leaf.

cubicBezierLeafSize number <optional>
1

Target number of cubic Bézier curves in a homogeneous leaf.

directPrimitiveThreshold number <optional>
32

Maximum primitive count for building the hierarchy directly.

maxGroupExtent number <optional>
100

Maximum group width or height in scene coordinates.

consecutiveLocalityFactor number <optional>
2

Maximum adjacent AABB gap, relative to the larger curve extent.

numericEpsilon number <optional>

Relative arithmetic epsilon required when an entry contains an unprepared curve.

Source:
Returns:

The BVH.

Type
Object

buildModuleInstanceTooltipHtml(allRows) → {string}

Build Bootstrap tooltip title HTML from rows of cell tuples (same shape as FormulaInput).

Parameters:
Name Type Description
allRows Array.<Array.<*>>
Source:
Returns:
Type
string

buildParenHighlightHtml(text, pair, matchClassopt)

Safe HTML for a pre-wrapped highlight layer under a textarea (escape + optional match spans).

Parameters:
Name Type Attributes Description
text string | null | undefined
pair Array.<number> | null

Two bracket indices [open, close].

matchClass string <optional>
Source:

checkRayIntersectsShape(ray) → {Point}

Check if a ray intersects the circle. In the child class, this can be called from the checkRayIntersects method.

Parameters:
Name Type Description
ray Ray

The ray.

Source:
Returns:

The intersection point, or null if there is no intersection.

Type
Point

checkRayIntersectsShape(ray) → {Point}

Check if a ray intersects the line segment. In the child class, this can be called from the checkRayIntersects method.

Parameters:
Name Type Description
ray Ray

The ray.

Source:
Returns:

The intersection point, or null if there is no intersection.

Type
Point

clampWebGpuParameterToF32()

Convert an ordinary instance parameter to the value that may be packed in an f32 buffer. Finite overflow and signed infinities saturate; NaN and non-numeric values remain scene-contract errors.

Source:

collapseBinaryBvh()

Collapse the temporary binary construction tree into the shared BVH4 representation. Branch nodes are stored before leaves so WebGPU can pack the branch prefix directly while CPU diagnostics can still address leaves.

Source:

collapseRedundantNestedParentheses(node) → {*}

Collapse AST chains ParenthesisNode(ParenthesisNode(x)) to a single ParenthesisNode so e.g. ((a+b)) does not become redundant nesting in output. Does not unwrap a single outer pair around a product like ((a+b)*(c+d)).

Parameters:
Name Type Description
node *

math.js expression AST node

Source:
Returns:

math.js expression AST node

Type
*

collectPointPaths(objData, schema, basePathopt) → {Array.<string>}

Recursively collect all point-type property paths from schema and objData. Handles arrays with itemSchema by expanding to concrete indices from objData.

Parameters:
Name Type Attributes Default Description
objData Object

Template object data.

schema Array

Property schema descriptors.

basePath string <optional>
''

Base path for nested contexts.

Source:
Returns:

List of full dot-separated paths to point values.

Type
Array.<string>

collectRayPowerQueue(rays, targetPower, generation, samplingopt) → {Object}

Apply the selected weak-ray policy while compacting an outgoing queue. Stable sampling matches the WebGPU weight/prefix/fill collector: weak rays contribute fractional weight and retained representatives are amplified. Truncation instead omits every weak ray. Both policies return the original weak power for conservative error accounting.

Parameters:
Name Type Attributes Default Description
rays Array.<Object>
targetPower number
generation number
sampling boolean <optional>
false
Source:
Returns:
Type
Object

collectReferencedParameterNames(dag, labels) → {Set.<string>}

Collect parameters which are dependencies of the selected output labels.

Parameters:
Name Type Description
dag Object
labels Array.<string>
Source:
Returns:
Type
Set.<string>

combineDags(dags) → {Object}

Combine independently built formula DAGs while preserving all labeled outputs. Node IDs are remapped, but nodes are not deduplicated across DAGs. The first DAG's root remains the root of the combined DAG.

Parameters:
Name Type Description
dags Array.<Object>

The formula DAGs to combine.

Source:
Returns:

The combined formula DAG.

Type
Object

compileParametricDerivative(eqnLatex) → {function}

Compile d(eq)/dt from LaTeX eq(t). Uses latexToMathJS → mathjs derivative → toTex replacements → evaluateLatex.

Parameters:
Name Type Description
eqnLatex string
Source:
Returns:
Type
function

controlPointIndexAfterReorder()

Index s after moving one item from from to to.

Source:

countCurveRayCrossings(geometry, ray, optionsopt, outopt) → {Object}

Count forward crossings of one curve for an even-odd region ray cast.

Parameters:
Name Type Attributes Description
geometry Object
ray Object
options Object <optional>
Properties
Name Type Attributes Description
numericEpsilon number
tolerancePolicy Object <optional>
originTolerance number <optional>
out Object <optional>
Source:
Returns:
Type
Object

countIntersections()

Counts intersections between the line segment (or ray) from p3 to p4 and the boundary curves. When p4 is omitted, this is used as a crossing-number test (for closed shapes) and returns the number of intersections from p3 with a pseudo-ray going outside the bounding box. When p4 is provided, it also records per-curve intersections and the nearest one in this.curIntersections.

Source:

countIntersections(point) → {number}

Count intersections between a horizontal ray from the point and the parametric curve. Uses a more robust crossing number algorithm that handles dense/repeated points. Lazy-generates the path if needed.

Parameters:
Name Type Description
point Point

The point from which to cast the horizontal ray

Source:
Returns:

Number of intersections with the curve boundary

Type
number

createArcOrLineCurve()

Convert an endpoint/through-point circular arc to the primitive bulge form. Collinear input falls back to a line segment.

Source:

createCpuDetectorResults(description) → {Array.<Float64Array>}

Allocate one result array for each logical detector result.

Parameters:
Name Type Description
description Object
Source:
Returns:
Type
Array.<Float64Array>

createCustomSurfacePrimitive()

Translate legacy angle/polarization custom-surface formulas to a primitive surface type. The translation is performed independently for s and p polarization. A legacy output occupies two primitive slots whenever those translated angle DAGs differ; later formulas inherit that split through their references to earlier theta/P values.

Source:

createDagClosureEvaluator(dag, optionsopt) → {function}

Build a closure-based DAG evaluator.

Parameters:
Name Type Attributes Default Description
dag Object

DAG to evaluate.

options Object <optional>
{}

Evaluator options.

Properties
Name Type Attributes Description
labels Array.<string> <optional>

Optional ordered output labels.

Source:
Returns:

Function that accepts parameter values and returns labeled node values.

Type
function

createDagEvaluator(dag, optionsopt) → {function}

Compile a DAG to native JavaScript when dynamic function construction is available, falling back once at scene-preparation time when it is blocked (for example by a browser Content Security Policy).

The returned evaluator has no runtime fallback branch or exception wrapper.

Parameters:
Name Type Attributes Default Description
dag Object

DAG to evaluate.

options Object <optional>
{}

Evaluator options.

Properties
Name Type Attributes Description
labels Array.<string> <optional>

Optional ordered output labels.

functionConstructor function <optional>

Test/host override.

Source:
Returns:

Compiled or closure-based evaluator.

Type
function

createDagWgslSpecialization()

Perform the range-dependent portion of WGSL generation once. The returned object can be compared by guardSignature and later supplied to generateDagWgslFunction without estimating the DAG again.

Source:

createInteractionCandidate(regionCount, maximumDistanceopt) → {InteractionCandidate}

Create the reusable state updated once for every curve visited by a linear loop or acceleration-structure traversal.

Parameters:
Name Type Attributes Default Description
regionCount number
maximumDistance number <optional>
Infinity

Initial search limit.

Source:
Returns:
Type
InteractionCandidate

createInteractionCandidateContext(description, numericEpsilon, maximumDistanceopt) → {Object}

Prepare constants shared by every candidate update for one ray.

Parameters:
Name Type Attributes Default Description
description Object
numericEpsilon number
maximumDistance number <optional>
Infinity
Source:
Returns:
Type
Object

createInteractionIndexBuffers(layout) → {Array.<Object>}

Create the mutable per-iteration buffers for a fixed type layout.

Parameters:
Name Type Description
layout Object
Source:
Returns:
Type
Array.<Object>

createInteractionTypeLayout(description) → {Object}

Build the interaction-type metadata once for a prepared scene. The layout remains unchanged between ping-pong iterations.

Parameters:
Name Type Description
description Object
Source:
Returns:
Type
Object

createMegakernelCollectorShader()

Systematically samples and stable-compacts current-generation output slots without copying ray payloads. Physical holes have zero weight, while a ray below the configured target power contributes its power divided by that target. The retained representative is amplified before the next trace.

Source:

createMegakernelInitialShader()

Build the source-emission and initial-membership megakernel.

Source:

createMegakernelQueueLayout()

Queue metadata shared by the two ray-buffer directions.

Source:

createRegionMembershipResult(regionCount) → {Object}

Create reusable output storage for one region-membership ray cast.

Parameters:
Name Type Description
regionCount number
Source:
Returns:
Type
Object

createSampledPrimitiveCurveEntries()

Convert the sampled representation maintained by ParamCurveObjMixin and the custom-equation glass/mirror classes. Each returned entry retains the sampled parameter endpoints used to reconstruct a legacy t from native primitive parameter u.

Source:

createWebGpuDagPrograms()

Materialize output-specific WGSL functions from the specializations made by the range pass. No range estimation occurs here. These program objects are cached with the execution plan and are intended to be embedded directly in the corresponding compute pipeline modules.

Source:

createWebGpuExecutionPlan()

Describe the concrete buffers and ordered passes used by a prepared WebGPU megakernel scene. Keeping this as plain data also provides a cache key independent of runtime instance values and rendering uniforms.

Source:

createWebGpuMegakernelShader()

Build one scene-specialized tracing megakernel. The generated shader keeps the continuation ray in function memory, evaluates all interaction kinds in one invocation, and writes only branches or a suspended continuation.

Source:

createWebGpuRawTraceShader()

Generate native BVH tracing, coincident-hit merging, region-crossing and typed-interaction classification. Geometry functions are specialized to the curve kinds present in the prepared scene.

Source:

createWebGpuTraceSceneData()

Pack the immutable tables needed while tracing into one storage binding. Each table begins at the alignment required by its WGSL element type and has a fixed stride.

Source:

createWebGpuTraceSceneDeclaration()

Build the fixed-size WGSL struct matching createWebGpuTraceSceneData.

Source:

deepEqual(obj1, obj2) → {boolean}

Recursively compare two objects for equality.

Parameters:
Name Type Description
obj1 *

First object

obj2 *

Second object

Source:
Returns:

True if objects are equal

Type
boolean

deriveWebGpuWavelengthRange()

Derive the accepted wavelength range. By default this applies the scene's violet/red affine mapping to the standard 380/420/620/700 anchors. When non-visible light is retained, the closed range-estimation interval covers the positive finite f32 domain and runtime validation excludes zero.

Source:

distancePointToSegment(point, segment) → {number}

Calculate distance from a point to a line segment.

Parameters:
Name Type Description
point Point

The point

segment Line

The line segment

Source:
Returns:

Distance from point to segment

Type
number

draftsToCommittedValue()

Same shape as passed to applyUpdate in commitForDrafts (for equality checks).

Source:

drawConstruction(canvasRenderer)

Draw the (polygonal) construction preview of the curve path while the user is still adding anchor points.

Parameters:
Name Type Description
canvasRenderer CanvasRenderer
Source:

drawControlHandles(canvasRenderer)

Draw the anchor and control points with tangent guide lines.

Parameters:
Name Type Description
canvasRenderer CanvasRenderer
Source:

drawPath(canvasRenderer, offset)

Draw the parametric curve path on the canvas. This method sets up the canvas path but does not stroke or fill it.

Parameters:
Name Type Default Description
canvasRenderer CanvasRenderer

The canvas renderer

offset number 0

Optional offset distance perpendicular to the curve (positive = left side)

Source:

drawPreparedCurve(renderer, geometry, color, lineWidthopt)

Draw a prepared primitive curve for host-side diagnostics or highlighting.

Parameters:
Name Type Attributes Default Description
renderer Object
geometry Object
color Array.<number> | Object
lineWidth number <optional>
1
Source:

drawPreparedRegion(renderer, geometries, fillColor, outlineColor, lineWidthopt)

Fill and outline an ordered set of prepared region-boundary curves.

Parameters:
Name Type Attributes Default Description
renderer Object
geometries Array.<Object>
fillColor Array.<number> | Object
outlineColor Array.<number> | Object
lineWidth number <optional>
1
Source:

ensureCurveIntersectionNormal(geometry, ray, intersection, optionsopt) → {Object|null}

Populate the incident-facing unit normal and geometric orientation of a curve intersection unless they have already been calculated.

Parameters:
Name Type Attributes Description
geometry Object
ray Object
intersection Object
options Object <optional>
Properties
Name Type Attributes Description
numericEpsilon number
tolerancePolicy Object <optional>
Source:
Returns:
Type
Object | null

equationDisplayToValue(text, isTemplate) → {string|undefined}

Convert a display string (user-entered math.js text) back to a stored equation value.

In template mode the value is wrapped in double backticks. In non-template mode the value is converted to LaTeX, then validated by parsing that LaTeX back to math.js so stored values remain editable.

Parameters:
Name Type Description
text string

The user-entered math.js expression.

isTemplate boolean

Whether the current context is a template.

Source:
Throws:

If non-template conversion to LaTeX fails or the LaTeX cannot be read back.

Returns:

The stored value, or undefined for empty input.

Type
string | undefined

equationValueForListDisplay(value) → {string}

Plain-text equation for object list descriptions (matches EquationPropertyControl / equationValueToDisplay): LaTeX → math.js string; expr → inner expr; unsupported → raw stored value.

Parameters:
Name Type Description
value *

The stored equation value.

Source:
Returns:
Type
string

equationValueToDisplay(value) → {Object|Object}

Check whether a stored equation value is supported by the visual editor and extract the math.js display string.

Supported formats:

  • A string without backticks: interpreted as LaTeX, converted to math.js.
  • A string that is a single double-backtick block (expr): the inner part is already math.js.
Parameters:
Name Type Description
value *

The stored equation value.

Source:
Returns:
Type
Object | Object

estimateAmbiguousRayWarningPowerThreshold()

Estimate ambiguous power that can arise naturally from rays landing within floating-point endpoint uncertainty. Sources are assumed to have total power of order one, matching the default source normalization.

Source:

estimateDagRanges()

Estimate finite f32 value ranges for every DAG node.

Parameter ranges are closed interval unions. Callers which know an input can also carry the runtime invalid state may pass { intervals, maybeInvalid: true }:

estimateDagRanges(dag, { x: [[-1, 1]], i: [[0, 10], [20, 30]] })
estimateDagRanges(dag, { x: { intervals: [[-1, 1]], maybeInvalid: true } })

Returned intervals are disjoint, sorted, finite, and clamped to f32 range. maybeInvalid means the node may evaluate to the runtime invalid state for some allowed input.

Source:

estimateWebGpuParameterRanges(description, optionsopt) → {Object}

Estimate the f32 input interval contract for every formula type in a processed scene. Each authored type receives a reusable WGSL specialization containing its DAG range result and range-dependent guard signature. A later WGSL generation step can consume that specialization without running the range estimator again. No WGSL is emitted or compiled here.

Runtime WebGPU tracing must discard wavelengths outside wavelengthRange. The same range is used for every downstream lambda input.

Parameters:
Name Type Attributes Description
description Object

Engine-independent processed scene.

options Object <optional>
Properties
Name Type Attributes Default Description
violetWavelength number <optional>
420
redWavelength number <optional>
620
keepNonVisibleLight boolean <optional>
false
intervalLimit number <optional>
8
Source:
Returns:

A unified types list, category views, and supporting region-index metadata.

Type
Object

evaluatePreparedCurve(geometry, u, outopt) → {Object}

Evaluate a prepared open curve at its native parameter.

Parameters:
Name Type Attributes Description
geometry Object
u number
out Object <optional>
Source:
Returns:
Type
Object

extractNonDefaults(obj, defaults) → {Object|null}

Recursively extract only non-default values from a nested object.

Parameters:
Name Type Description
obj Object

The object to extract from

defaults Object

The default values

Source:
Returns:

Object containing only non-default values, or null if all values are default

Type
Object | null

extractNumbersAsParameters(dag, optionsopt) → {Object}

Replace number literals in a DAG with generated parameters.

Parameters:
Name Type Attributes Default Description
dag Object

DAG to rewrite.

options Object <optional>
{}

Extraction options.

Properties
Name Type Attributes Default Description
prefix string <optional>
"_n"

Prefix for generated parameter names.

Source:
Throws:

If dag is malformed or options.prefix is not a non-empty string.

Type
TypeError
Returns:

Rewritten DAG and extracted literal metadata.

Type
Object
Example
const { dag, extracted } = extractNumbersAsParameters(parsedDag);
// extracted: [{ name: "_n0", value: 2.5, raw: "2.5" }]

finalizeInteractionCandidate(candidate, context, ray) → {InteractionCandidate|null}

Finish lazily populated fields after traversal.

Parameters:
Name Type Description
candidate InteractionCandidate
context Object
ray Object
Source:
Returns:
Type
InteractionCandidate | null

findMatchingBraceEnd(s, openIdx) → {number}

Index of the matching } for { at openIdx, or -1. Ignores { / } inside JSON strings.

Parameters:
Name Type Description
s string
openIdx number
Source:
Returns:
Type
number

findMatchingParenPair(text, caret) → {Array.<number>|null}

Parameters:
Name Type Description
text string
caret number
Source:
Returns:

Two indices [open, close] inclusive, or null if none.

Type
Array.<number> | null

findMathBlockRanges(text) → {Array.<Array.<number>>}

Ranges [start, end] inclusive for each math block delimited by backticks (`` first, then `).

Parameters:
Name Type Description
text string
Source:
Returns:
Type
Array.<Array.<number>>

findPrimitiveCurveReferenceSpans(message) → {Array.<{start: number, end: number, curveId: number, reference: string}>}

Find namespaced primitive-curve references in a diagnostic message.

Parameters:
Name Type Description
message string
Source:
Returns:
Type
Array.<{start: number, end: number, curveId: number, reference: string}>

findUnjoinedPieces() → {Object|null}

Find the first pair of consecutive pieces whose endpoints do not meet. Lazy-generates the path if needed.

Source:
Returns:

1-based piece numbers, or null if all joined

Type
Object | null

findValidJsonObjectSpans(line) → {Array.<{start: number, end: number, json: string}>}

Non-overlapping { ... } spans that parse as JSON.

Parameters:
Name Type Description
line string
Source:
Returns:
Type
Array.<{start: number, end: number, json: string}>

formatKeyPath(path) → {string}

Format a dot-separated key path into a more familiar bracket notation. Numeric segments become array indices: path.1.x → path[1].x Reserved JS keywords (for, if) use bracket notation: obj.if → obj["if"]

Parameters:
Name Type Description
path string

Dot-separated key path.

Source:
Returns:

The formatted path.

Type
string

formatPrimitiveCurveReference(curveId) → {string}

Format a processed primitive curve ID for detection by diagnostic UIs.

Parameters:
Name Type Description
curveId number
Source:
Returns:
Type
string

formatStatusLineHtml(line, options) → {string}

HTML for one status line with long JSON segments collapsed to { [icon] } and primitive-curve references rendered as interactive controls.

Parameters:
Name Type Description
line string
options object
Properties
Name Type Attributes Description
expanded Record.<string, boolean>
keyPrefix string

e.g. 'w' or 'e'

lineIdx number
labels object
Properties
Name Type Attributes Description
expand string
primitiveCurve function <optional>
threshold number <optional>
Source:
Returns:
Type
string

formatTooltipNumber()

If the value shows 4+ digits after the decimal point, round for display to 3 places.

Source:

formulaDisplayToValue(text, typeopt) → {number|boolean|string|undefined}

Convert a display string (user-entered text) back to a stored value. For numbers: numeric text becomes a number; anything else is wrapped in backticks. For booleans: "true"/"false" become boolean literals; anything else is wrapped in backticks. Empty string always returns undefined.

Parameters:
Name Type Attributes Default Description
text string
type 'number' | 'boolean' <optional>
'number'
Source:
Returns:
Type
number | boolean | string | undefined

generateDagJsEvaluator(dag, optionsopt) → {Object}

Generate JavaScript source for evaluating labeled DAG nodes.

The returned source is not evaluated. Callers that trust the DAG may load it with new Function or write it to a file.

Parameters:
Name Type Attributes Default Description
dag Object

DAG to generate source for.

options Object <optional>
{}

Generator options.

Properties
Name Type Attributes Description
labels Array.<string> <optional>

Optional ordered output labels.

functionName string <optional>

Generated evaluator function name.

Source:
Returns:

Generated source code and metadata.

Type
Object

getAllByKeyPath(obj, path) → {Array}

Read values along a dot-separated key path, returning an array of results (one per branch). Like getByKeyPath, but when a numeric segment follows an array that isSourceIndexArray marks as source-indexed, the segment selects every element whose _sourceIndex equals that number (not the array index). Remaining segments are applied to each branch; the final return is the list of leaf values (possibly empty).

Parameters:
Name Type Description
obj Object

Root object.

path string

Dot-separated path (e.g. expanded.2.x). Empty string returns [obj].

Source:
Returns:

All values at the path; [] if no branches match or all branches hit null.

Type
Array

getCurveBounds(curve, options) → {Object}

Calculate the axis-aligned bounding box of a primitive curve.

Parameters:
Name Type Description
curve PrimitiveCurve

The primitive curve.

options Object
Properties
Name Type Description
numericEpsilon number

Relative arithmetic epsilon selected by the engine.

Source:
Returns:

The curve bounds.

Type
Object

getEffectiveRayPowerOptions()

Resolve the scene-facing weak-ray options. The default color renderer has fixed effective values because it cannot faithfully display weaker rays.

Source:

getInteractionTypeIndex(description, layout, hit) → {number}

Return the fixed interaction-type index for one source-ray hit, or -1 when the ray is discarded or escapes to infinity.

Parameters:
Name Type Description
description Object
layout Object
hit Object
Source:
Returns:
Type
number

getIntersectionTolerancePolicy(numericEpsilon) → {Object}

Return the immutable, epsilon-dependent portion of curve-intersection tolerances. Runtime coordinate, curve, and ray scales are deliberately applied by the intersection routines rather than stored here.

Policies are cached by epsilon so direct callers and engine-owned contexts share the same object instead of rebuilding it for every tested curve.

Parameters:
Name Type Description
numericEpsilon number
Source:
Returns:
Type
Object

getNextModuleIdentifierName()

Next unused single-letter az, then n0, n1, … — existingNames should include both module parameters and variables.

Source:

getRayIntersections(ray) → {Array}

Get all ray intersections with the parametric curve. Returns an array of intersection data with normal vectors and incident types consistent with CustomArcSurface conventions for counterclockwise arcs.

Parameters:
Name Type Description
ray Ray

The ray to check intersections with

Source:
Returns:

Array of intersection objects with properties:

  • s_point: intersection point
  • normal: {x, y} normal vector
  • incidentType: 1 (inside to outside), -1 (outside to inside), or NaN
  • incidentPiece: piece index (0-based)
  • incidentPos: parameter t value of the intersection
Type
Array

getRayIntersectionsCubicBezier(ray) → {Array}

Ray–curve intersections when each segment is a cubic Bezier in natural t between consecutive samples.

Parameters:
Name Type Description
ray Ray
Source:
Returns:
Type
Array

getRayIntersectionsLinear(ray) → {Array}

Ray intersections using linear segments between sampled points.

Parameters:
Name Type Description
ray Ray
Source:
Returns:
Type
Array

getRoundingErrorFactor(operationCount, numericEpsilon) → {number}

Return the standard accumulated relative rounding-error bound for a sequence of elementary operations.

Parameters:
Name Type Description
operationCount number

Positive integer upper bound on the number of rounded operations.

numericEpsilon number

Relative arithmetic epsilon selected by the engine.

Source:
Returns:
Type
number

initPath() → {boolean}

Initialize the path points based on the parametric curve pieces. This method generates points for each piece from tMin to tMax with the given step.

Source:
Returns:

Whether the initialization was successful.

Type
boolean

intersectCurve(geometry, ray, optionsopt, outopt) → {Object|null}

Find only the nearest geometric intersection with one prepared curve. Normal data is deliberately calculated separately after the caller has rejected intersections that are farther than its current candidate.

Parameters:
Name Type Attributes Description
geometry Object
ray Object
options Object <optional>
Properties
Name Type Attributes Description
numericEpsilon number
tolerancePolicy Object <optional>
minDistance number <optional>
out Object <optional>
Source:
Returns:
Type
Object | null

isAtomicExpr()

Check whether a math.js expression string produced by the parser is a single "atom" (identifier, number, function call, or already-parenthesized group) vs. a compound expression with top-level operators. Relies on the convention that all binary operators are surrounded by spaces and unary minus is formatted as "- expr".

Source:

isClosed() → {boolean}

Check if the parametric curve is closed (first point matches last point within floating point error). Lazy-generates the path if needed.

Source:
Returns:

True if the curve is closed, false otherwise

Type
boolean

isFormula(text, typeopt) → {boolean}

Check whether a display string represents a formula (not a literal of the given type).

Parameters:
Name Type Attributes Default Description
text string
type 'number' | 'boolean' <optional>
'number'
Source:
Returns:
Type
boolean

isFormulaValueSupported(value, typeopt) → {boolean}

Check whether a stored value can be displayed/edited by the visual formula editor for the given property type. Supported: undefined, null, backtick-wrapped formula strings, and the native JS type matching type (number for 'number', boolean for 'boolean').

Parameters:
Name Type Attributes Default Description
value *
type 'number' | 'boolean' <optional>
'number'
Source:
Returns:
Type
boolean

isInside(point) → {boolean}

Check if a point is inside the parametric curve (using crossing number algorithm). Lazy-generates the path if needed.

Parameters:
Name Type Description
point Point

The point to test

Source:
Returns:

True if the point is inside the curve, false otherwise

Type
boolean

isLiteralBooleanFieldValue()

True when the field is the boolean literals true or false only (after trim).

Source:

isLiteralNumericFieldValue()

True when the field is a plain number or comma-separated list of numbers (literal user input). In that case we skip the expanded-instance tooltip.

Source:

isNonBasicProperty(descriptor) → {boolean}

Check whether a property is "non-basic" (always shown in partial view). Non-basic: points, equations, and arrays of objects (arrays whose itemSchema is not just a single number or string). Styles are basic.

Parameters:
Name Type Description
descriptor Object

PropertyDescriptor.

Source:
Returns:

True if the property is non-basic.

Type
boolean

isNonDefault(objData, descriptor, serializableDefaults, basePathopt) → {boolean}

Check whether the value at the given descriptor key path differs from the default. Non-basic properties (points, equations, arrays of objects) are always treated as non-default. Basic properties use serializableDefaults for comparison.

Parameters:
Name Type Attributes Default Description
objData Object

Raw/serialized object data (plain object with type and properties; never a class instance).

descriptor Object

PropertyDescriptor with a key property (dot-separated path).

serializableDefaults Object

The default values structure (e.g. from constructor.serializableDefaults).

basePath string <optional>
''

Optional base path when used in nested contexts (e.g. array items).

Source:
Returns:

True if the value is different from the default (or if non-basic, always true).

Type
boolean

isOnBoundary(point) → {boolean}

Check if a point is on the boundary of the parametric curve. Uses distance-based approach similar to checkMouseOver for robustness. Lazy-generates the path if needed.

Parameters:
Name Type Description
point Point

The point to test

Source:
Returns:

True if the point is on the boundary, false otherwise

Type
boolean

isOutside(point) → {boolean}

Check if a point is outside the parametric curve (using crossing number algorithm). Lazy-generates the path if needed.

Parameters:
Name Type Description
point Point

The point to test

Source:
Returns:

True if the point is outside the curve, false otherwise

Type
boolean

isPointHardcoded(value) → {boolean}

Check whether a point value has hardcoded coordinates. Hardcoded means both x and y are numbers (not formula strings). The special coordinates (0, 0) are NOT considered hardcoded.

Parameters:
Name Type Description
value Object | undefined

Point value from template (may have x/y as number or string).

Source:
Returns:

True if the point is hardcoded (numeric x, y, and not (0,0)).

Type
boolean

isPositivelyOriented() → {boolean}

Check if the parametric curve is positively oriented (clockwise in the computer graphics coordinate system). Uses the shoelace formula to calculate signed area. Lazy-generates the path if needed.

Source:
Returns:

True if the curve is positively oriented false otherwise

Type
boolean

isSourceIndexArray(arr) → {boolean}

Returns true when arr looks like a module-expanded list: at least one element is a non-null object with a numeric _sourceIndex (see ModuleObj.expandArray).

Parameters:
Name Type Description
arr Array
Source:
Returns:
Type
boolean

isTextareaAutoResizeMeasurable()

Whether the element participates in layout in a way that yields a real scrollHeight (not e.g. display: none under a hidden sidebar tab).

Source:

isValidFormulaParameterName(name) → {boolean}

Return whether a string can be used as a formula parameter or assignment name.

Formula names must be JavaScript-style identifiers and must not collide with constants or supported function names.

Parameters:
Name Type Description
name unknown

Candidate formula name.

Source:
Returns:

True when name is valid in formula syntax.

Type
boolean

latexToMathJS(latex) → {string}

Convert a LaTeX equation string to a math.js expression string.

Parameters:
Name Type Description
latex string

A LaTeX equation string.

Source:
Throws:

If the LaTeX cannot be parsed.

Returns:

The equivalent math.js expression string.

Type
string

mathJSToLatex(mathJSStr) → {string}

Convert a math.js expression string to a LaTeX equation string. Uses the same toTex handler as ModuleObj.expandEquation().

Parameters:
Name Type Description
mathJSStr string

A math.js expression string.

Source:
Throws:

If the expression cannot be parsed or converted.

Returns:

The equivalent LaTeX equation string.

Type
string

mergeWithDefaults(target, source, defaults, path) → {Object}

Recursively merge a nested object with its defaults.

Parameters:
Name Type Description
target Object

The target object to merge into

source Object

The source object to merge from

defaults Object

The default values

path string

The current path for error reporting

Source:
Returns:

The merged object

Type
Object

newlinesToBr(html) → {string}

HTML ignores newline characters in text; convert them to line breaks for status display.

Parameters:
Name Type Description
html string
Source:
Returns:
Type
string

nextDuplicateIdentifier()

Next unused identifier when duplicating a parameter or variable row (the symbol name used in math.js expressions).

  • Increments a trailing integer (a1a2), instead of appending (a1a11).
  • For function-style LHS f(...), only the function symbol before ( changes (f(x)f1(x)).
Source:

normalizeNumericStrings()

Convert numeric strings left by older scene data without mutating primitive objects. Primitive parameter contracts contain only numbers, including the nested point objects used by curve geometry.

Source:

normalizeParsedEquationAST(node) → {*}

Parameters:
Name Type Description
node *

math.js expression AST node

Source:
Returns:

math.js expression AST node

Type
*

observeTextareasResizeWhenVisible(getElements, resizeAll) → {Object}

When a textarea lives under tabs / v-show / sidebar chrome, it can become visible after sidebarWidth updates while hidden. Observe intersection and re-measure when shown.

Parameters:
Name Type Description
getElements function

Returns textareas to observe (may include null/undefined entries).

resizeAll function

Re-measure all linked textareas.

Source:
Returns:

{ disconnect } — call disconnect() to stop observing.

Type
Object

packWebGpuScene()

Convert an engine-independent processed scene to immutable GPU table data. Every offset is expressed in the element unit used by its shader binding: parameter and geometry offsets are f32 indices; descriptor offsets are record indices.

Source:

parseFormula(input, parametersopt, optionsopt) → {Object}

Parse a math expression into a canonical DAG without evaluating it.

The expression may use constants (pi, e), binary operators (+, -, *, /, ^), unary minus, supported unary and binary functions, max/min, guard/fallback functions, parentheses, finite decimal numbers, and the parameter names supplied in parameters.

Parameters:
Name Type Attributes Default Description
input string

Expression to parse.

parameters Array.<string> <optional>
[]

Allowed parameter names in the expression.

options Object <optional>
{}

Parse options.

Properties
Name Type Attributes Description
outputLabel string <optional>

Label to assign to the root node.

Source:
Throws:
  • If input or parameters are invalid.

    Type
    TypeError
  • If the expression is syntactically invalid or references unknown names.

    Type
    FormulaParseError
Returns:

DAG with root pointing to a node id.

Type
Object
Example
const dag = parseFormula("sin(x)^2 + cos(x)^2", ["x"]);
console.log(dag.root, dag.nodes);

populateObjBarShape(objBar)

Populate the object bar with parametric curve controls. This method should be called from populateObjBar in subclasses.

Parameters:
Name Type Description
objBar ObjBar

The object bar instance

Source:

prepareCpuOutgoingRayData(description) → {Object}

Prepare CPU formula evaluators and reusable instance-input objects. This is performed once per prepared scene, outside the ping-pong loop.

Parameters:
Name Type Description
description Object
Source:
Returns:
Type
Object

prepareCurve(curve, optionsopt) → {Object}

Prepare a primitive curve for engine-independent intersection testing.

The returned bounds include the same engine-selected positional tolerance used to extend open curves' accepted parameter intervals at their endpoints. An engine that packs bounds into a lower-precision representation is responsible for outward rounding while packing.

Parameters:
Name Type Attributes Description
curve PrimitiveCurve
options Object <optional>
Properties
Name Type Attributes Default Description
lengthScale number <optional>
1
endpointTolerance number <optional>
0

Minimum world-space endpoint tolerance.

numericEpsilon number

Relative arithmetic epsilon selected by the engine.

Source:
Returns:
Type
Object

preprocessPrimitives(primitives, optionsopt) → {Object}

Convert scene-object primitives into an engine-independent processed scene. Degenerate curves are discarded. A surface or detector owning one is discarded with it, while a region is retained if any boundary remains.

Parameters:
Name Type Attributes Description
primitives Array.<Primitive>

Primitives collected in scene order.

options Object <optional>
Properties
Name Type Attributes Default Description
bvhOptions Object <optional>

Options forwarded to buildBvh.

lengthScale number <optional>
1

Natural scene length used by engine-selected curve tolerances.

numericalTolerances Object <optional>

Simulator-configured tolerance minimums, with distances relative to the scene length scale.

numericEpsilon number

Relative arithmetic epsilon selected by the engine.

Source:
Returns:
Type
Object

promptNewModuleName(moduleNames) → {string|null}

Prompts for a new module name. Shows alerts on invalid input.

Parameters:
Name Type Description
moduleNames Array.<string>

Existing module names.

Source:
Returns:

The chosen name, or null if cancelled / invalid.

Type
string | null

promptNewModuleNameForHandle(scene) → {string|null}

Prompt for a new module name using the same rules as the module editor (for handle → module conversion).

Parameters:
Name Type Description
scene Object
Source:
Returns:
Type
string | null

recordWebGpuRecompilationNeeds(estimated, previousSignatures) → {Map.<string, string>}

Compare only range-dependent guard signatures. Structural DAG changes are intentionally outside this comparison and remain simulator-owned.

Parameters:
Name Type Description
estimated Object
previousSignatures Map.<string, string> | null
Source:
Returns:

Signatures to retain for the next update.

Type
Map.<string, string>

renderCpuRay()

Render one ray from an immutable ray-buffer entry and its completed hit. Inactive rays break nearby-ray adjacency, matching inactive WebGPU source slots. Prefix-sampled outgoing queues are compact and contain no such gaps.

Source:

resetInteractionIndexBuffers(buffers)

Reset mutable counts and arrays without rebuilding the fixed type metadata.

Parameters:
Name Type Description
buffers Array.<Object>
Source:

resolvePrimitiveSimulatorConfig()

Resolve numerical tolerances shared by all primitive engines.

Source:

resolveSimulationEngineConfig(engineKind, storedConfigsopt) → {Object}

Resolve one engine's defaults with its stored global overrides.

Parameters:
Name Type Attributes Default Description
engineKind string

Simulation engine kind.

storedConfigs Object.<string, Object> <optional>
{}

Per-engine overrides.

Source:
Returns:

Resolved configuration for the engine.

Type
Object

sanitizePastedJson(text) → {string}

Prepare clipboard text for the scene JSON editor (fences + comments).

Parameters:
Name Type Description
text string
Source:
Returns:
Type
string

setByKeyPath(obj, path, value, defaultsopt)

Set a value in an object by a dot-separated key path. Creates intermediate objects/arrays as needed. When a parent is undefined (using default), materializes it from defaults before modifying.

Parameters:
Name Type Attributes Description
obj Object

The object to mutate (root).

path string

Dot-separated path (e.g. 'focalLength', 'path.0', 'params.r1'). Empty string is not valid for set (would replace root).

value *

The value to set.

defaults Object <optional>

Optional defaults. When an intermediate is null/undefined, materializes from defaults first. When the value being set matches the default (from defaults or the built-in for/if defaults), the property is deleted instead of set — except for sub-properties inside array elements, which are always kept (arrays are compared as a whole during serialization). The reserved keys for and if are still deleted when default even inside array elements.

Source:

setViewportSize(width, height)

Set the size (in CSS pixels) for the viewport of the scene.

Parameters:
Name Type Description
width number
height number
Source:

solveQuadraticRoots(a, b, c, numericEpsilon, outopt) → {Array.<number>}

Solve a real quadratic with cancellation-resistant roots.

Parameters:
Name Type Attributes Description
a number
b number
c number
numericEpsilon number

Relative arithmetic epsilon selected by the engine.

out Array.<number> <optional>
Source:
Returns:
Type
Array.<number>

splitTexCommaArgs(inner) → {Array.<string>}

Split a TeX fragment on commas that separate arguments at the current fence level: {…} / () / \left…\right nesting increments/decrements; commas only split when all depths are 0.

Parameters:
Name Type Description
inner string
Source:
Returns:
Type
Array.<string>

splitTopLevelCommas(str) → {Array.<string>}

Split a string by commas that are not inside (), [], or {}.

Parameters:
Name Type Description
str string
Source:
Returns:

The parts, each trimmed.

Type
Array.<string>

stableRaySamplingPhase()

Match the deterministic phase used by the WebGPU stable queue collector. All integer operations deliberately wrap to u32.

Source:

stripJsonComments(text) → {string}

Strip // and /* */ comments from pasted text while respecting string literals. :// is not treated as a line comment (e.g. http://).

Parameters:
Name Type Description
text string
Source:
Returns:
Type
string

stripMarkdownCodeFence(text) → {string}

Remove leading markdown fence (e.g. json) and trailing from AI-style pastes.

Parameters:
Name Type Description
text string
Source:
Returns:
Type
string

stripParenChain(node) → {*}

Remove a chain of ParenthesisNode wrappers (used after nested collapse).

Parameters:
Name Type Description
node *

math.js expression AST node

Source:
Returns:

math.js expression AST node

Type
*

stripRedundantParensForLatex(node) → {*}

Strip ParenthesisNode wrappers that are redundant in LaTeX output because the surrounding construct already provides grouping:

  • exponent of ^ (wrapped in ^{…})
  • numerator and denominator of / (wrapped in \frac{…}{…})
Parameters:
Name Type Description
node *

math.js expression AST node

Source:
Returns:

math.js expression AST node

Type
*

substituteDagParameters(dag, substitutions) → {Object}

Replace selected parameter nodes with expression DAGs.

Replacement expressions are copied as-is and are not recursively subjected to the same substitution map. They must not contain labeled outputs. The input DAG is not mutated, and all of its labeled outputs are preserved even when they are not reachable from its root node.

Parameters:
Name Type Description
dag Object

The DAG whose parameters are to be replaced.

substitutions Object.<string, Object>

Parameter names mapped to expression DAGs.

Source:
Returns:

A rewritten DAG.

Type
Object

suggestNewModuleName(names) → {string}

Parameters:
Name Type Description
names Array.<string>

Existing module names in the scene.

Source:
Returns:
Type
string

templatePointLockState(objData, schema, basePathopt) → {Object}

Check whether all point-type properties in a module template have hardcoded coordinates. Used to determine if a template object will be movable in the canvas when placed in a module.

Parameters:
Name Type Attributes Default Description
objData Object

Template object data (raw JSON from module objs).

schema Array

Property schema from getPropertySchema.

basePath string <optional>
''

Base path for nested contexts.

Source:
Returns:
Type
Object

textHasBacktickBlocks(text) → {boolean}

True when the display string contains backtick-delimited math blocks.

Parameters:
Name Type Description
text string
Source:
Returns:
Type
boolean

toJSON() → {string}

Convert the scene to JSON.

Source:
Returns:

The JSON string representing the scene.

Type
string

tooltipAllTupleRowsConstant()

True if every collected tuple row equals row 0 (raw values).

Source:

tooltipMantissaDecimalPlaces()

Mantissa decimal places as shown by Number#toString (handles scientific notation).

Source:

tooltipPointTupleEqual()

One expansion row as a tuple (e.g. point x,y); whole tuple must match to collapse.

Source:

tooltipValueEqualForCollapse()

Equality for tooltip collapse; uses raw values (not rounded / not display-truncated).

Source:

tracePath(canvasRenderer)

Build a sub-path on the current canvas context that traces all Bezier curves from the first anchor to the last anchor. The caller is expected to have already called ctx.beginPath(). When the shape is closed, callers may additionally call ctx.closePath() before filling.

Parameters:
Name Type Description
canvasRenderer CanvasRenderer
Source:

traceSceneCapacityCounts()

Derive the WGSL array lengths from an existing packed buffer layout.

A reusable backend keeps these capacities (and therefore all later field offsets) fixed even when a compatible scene with smaller tables is uploaded. Any shader compiled for that backend must use the same fixed layout rather than recomputing offsets from the replacement scene.

Source:

traverseBvhForInteraction(description, ray, candidate, candidateContext)

Traverse the prepared curve BVH using an explicit stack and update an interaction candidate for every curve in a reached leaf.

Each stack item is stored as two consecutive numbers: node index followed by the ray's entry distance into that node. The farther child is pushed first so the nearer child is popped first. When the farther child is later popped, a candidate found in the nearer subtree can prune it immediately.

Parameters:
Name Type Description
description Object
ray Object
candidate Object
candidateContext Object
Source:

traverseBvhForRegionMembership(description, ray, result, numericEpsilon) → {Object}

Determine region membership by counting every forward region-boundary crossing reached through the BVH. Nodes without region boundaries are ignored using their owner-kind mask.

Parameters:
Name Type Description
description Object
ray Object
result Object
numericEpsilon number
Source:
Returns:
Type
Object

unwrapParenInCallableArgs(node) → {*}

Strip gratuitous ParenthesisNode wrappers from function and unary +/- arguments (e.g. sin(((x))) → sin(x)). Top-level expressions such as ((a+b)*(c+d)) are unchanged.

Parameters:
Name Type Description
node *

math.js expression AST node

Source:
Returns:

math.js expression AST node

Type
*

updateInteractionCandidate(candidate, context, curveId, ray)

Test one curve and update the nearest interaction candidate. This is the traversal-independent update operation used by both a loop and a BVH.

Parameters:
Name Type Description
candidate InteractionCandidate
context Object
curveId number
ray Object
Source:

useBacktickHighlightLayer(getText)

Backtick math-block overlay for a textarea (pair with a highlight layer + shared CSS). All backtick blocks in the text are always highlighted.

Parameters:
Name Type Description
getText function
Source:

useParenHighlightLayer(getTextareaRef, getText, isFieldActive)

Matching-parenthesis overlay for a textarea (pair with a highlight layer + shared CSS).

Parameters:
Name Type Description
getTextareaRef function

Returns the textarea element or null/undefined.

getText function
isFieldActive function

True when the field is focused.

Source:

useStatus() → {Object}

Composable for handling application status including mouse position, simulator metrics, and system status (errors/warnings)

Source:
Returns:

Reactive status state and computed properties

Type
Object

useWebGpuTraceScene()

Redirect the familiar table expressions to fields of TraceScene.

Source:

validateDagNodeLabel(label, fieldNameopt) → {string}

Validate a DAG node label.

Labels are lookup/output keys. They only need to be non-empty strings and unique within the DAG.

Parameters:
Name Type Attributes Default Description
label unknown

Candidate node label.

fieldName string <optional>
"label"

Field name used in error messages.

Source:
Throws:

If the label is invalid.

Type
TypeError
Returns:

The validated label.

Type
string

validateFormulaNodeLabel(label, _parametersopt, fieldNameopt) → {string}

Validate an output DAG node label.

Output labels are DAG lookup keys, not formula names. They may match parameter names or formula function names.

Parameters:
Name Type Attributes Default Description
label unknown

Candidate node label.

_parameters Iterable.<string> <optional>
[]

Ignored compatibility parameter.

fieldName string <optional>
"label"

Field name used in error messages.

Source:
Throws:

If the label is invalid.

Type
TypeError
Returns:

The validated label.

Type
string

validateNestedKeys(obj, defaults, path) → {string|null}

Recursively validate that an object only contains known keys.

Parameters:
Name Type Description
obj Object

The object to validate

defaults Object

The default structure defining known keys

path string

The current path for error reporting

Source:
Returns:

The path of unknown key if found, null otherwise

Type
string | null

validateNumericEpsilon(numericEpsilon, nameopt) → {number}

Require an engine-supplied relative arithmetic epsilon.

Parameters:
Name Type Attributes Default Description
numericEpsilon number
name string <optional>
'numericEpsilon'
Source:
Returns:
Type
number

validateWebGpuSpatialBounds()

Reject processed geometry which cannot use the WebGPU world-coordinate domain. This is intentionally a GPU preparation check, not common CPU preprocessing policy.

Source:

valueToFormulaDisplay(value) → {string}

Convert a stored value (number or backtick-wrapped formula string) to a display string with backticks stripped.

Parameters:
Name Type Description
value *
Source:
Returns:
Type
string

versionUpdate(jsonData) → {Object}

Update the scene JSON data to the latest version.

Parameters:
Name Type Description
jsonData Object
Source:
Returns:

The updated JSON data.

Type
Object

viewportCenterSceneCoords()

Scene-space point at the viewport center (same formula as observer init when switching to observer mode).

Source:
See:
  • app/store/scene.js — mode callback

writeCpuOutgoingRays(options) → {number}

Evaluate one indexed interaction and write every fixed outgoing-ray slot.

Parameters:
Name Type Description
options Object
Source:
Returns:

Number of active outgoing slots written.

Type
number

Type Definitions

BodyMergingObj

Every ray has a temporary bodyMerging object ("bodyMergingObj") as a property (this property exists only while the ray is inside a region of one or several overlapping grin objects - e.g. CircleGrinGlass and GrinGlass), which gets updated as the ray enters/exits into/from grin objects, using the "multRefIndex"/"devRefIndex" function, respectively.

Type:
  • Object
Properties:
Name Type Description
fn_p function

The refractive index function for the equivalent region of the simulation.

fn_p_der_x function

The x derivative of fn_p for the equivalent region of the simulation.

fn_p_der_y function

The y derivative of fn_p for the equivalent region of the simulation.

Source:

BulkType

Defines the relative refractive-index field shared by a set of region primitives. Like surface types, bulk type definitions are immutable plain data and are structurally deduplicated during preprocessing, with object identity as a fast path. The DAG uses the format implemented by the formula utilities in src/core/formula and must contain the labeled scalar outputs n and alpha.

The reserved DAG inputs are x and y, the world-space position at which the field is evaluated, and lambda, the ray wavelength in nm. Direction, polarization, and power are not inputs because bulk media are isotropic. Coordinate origins or other instance-specific transformations are expressed through params.

alpha is the local power-absorption coefficient in inverse scene-length units. It is applied only when the engine performs a GRIN step: a step of length L multiplies both polarized powers by exp(-alpha * L). A segment ending at a boundary, authored surface, or detector does not apply a partial-step absorption update. Thus zero represents no bulk absorption, positive values absorb light, and negative values represent gain.

The formula compiler symbolically derives n_x and n_y, the partial derivatives of n with respect to world-space x and y. They are part of the compiled evaluator used for GRIN propagation, not independently authored DAG outputs. A wavelength-dependent field with no spatial dependence is still homogeneous and has zero spatial derivatives.

Type:
  • Object
Properties:
Name Type Description
name string

A human-readable diagnostic name, not a registry ID.

paramNames Array.<string>

The formula symbols and keys accepted in a region primitive's params object. Their order defines the packed parameter layout and is therefore significant, particularly for WebGPU buffers. Names must not collide with the reserved bulk-DAG symbols.

dag Object

The formula DAG containing the required labeled outputs n and alpha.

Source:

BvhCurveEntry

Type:
  • Object
Properties:
Name Type Attributes Description
geometry Object <optional>

Prepared curve geometry.

bounds Object <optional>

Prepared curve bounds.

curve PrimitiveCurve <optional>

Raw primitive curve.

ownerKind 'surface' | 'region' | 'detector' <optional>

Curve owner kind used to build node masks.

Source:

Circle

Type:
  • Object
Properties:
Name Type Description
c Point
r number | Line
Source:

CircleCurveParams

Type:
  • Object
Properties:
Name Type Description
center Point

The center of the circle.

radius number

The nonzero signed radius. Its absolute value defines the geometry; a positive value gives the circle an outward front normal and a negative value gives it an inward front normal.

Source:

CirclePrimitiveCurve

A complete oriented circle. The sign of its radius determines whether its front normal points away from or toward its center.

Type:
  • Object
Properties:
Name Type Description
kind 'circle'
params CircleCurveParams
Source:

CircularArcCurveParams

Type:
  • Object
Properties:
Name Type Description
start Point

The start endpoint.

end Point

The end endpoint.

bulge number

The tangent of one quarter of the signed sweep angle from start to end. A positive sweep is counter-clockwise. A zero bulge degenerates to a line segment; absolute values below, equal to, and above 1 describe minor arcs, semicircles, and major arcs respectively.

Source:

CircularArcPrimitiveCurve

Type:
  • Object
Properties:
Name Type Description
kind 'circularArc'
params CircularArcCurveParams
Source:

ConstructReturn

Type:
  • Object
Properties:
Name Type Attributes Description
isDone boolean <optional>

Whether the construction is done.

requiresObjBarUpdate boolean <optional>

Whether the object bar should be updated.

isCancelled boolean <optional>

Whether the construction is cancelled.

Source:

ControlPoint

Type:
  • Object
Properties:
Name Type Description
dragContext DragContext

The drag context of the virtual mouse that is dragging the control point.

newPoint Point

The new position of the control point.

Source:

CubicBezierCurveParams

Type:
  • Object
Properties:
Name Type Description
start Point

The start endpoint.

control1 Point

The first control point.

control2 Point

The second control point.

end Point

The end endpoint.

Source:

CubicBezierPrimitiveCurve

Type:
  • Object
Properties:
Name Type Description
kind 'cubicBezier'
params CubicBezierCurveParams
Source:

DetectorPrimitive

A detector represented by one oriented curve. Its type defines how ray incidents are accumulated and exposed as detector results. For a one-sided detector, an intersection from behind the curve's front normal is ignored and produces no detector reading. Detector formulas use the reserved hit-input symbols documented by SurfaceType, except n_0 and n_1, and include u and sigma for distinguishing the two geometric sides; they define detector outputs rather than outgoing-ray slots.

Type:
  • Object
Properties:
Name Type Description
kind 'detector'
curve PrimitiveCurve

The detector geometry.

twoSided boolean

Whether rays approaching from either side can be detected. If false, only rays approaching against the curve's front normal are detected.

detectorType DetectorType

The shared detector behavior definition.

params Object.<string, number>

Numeric instance parameters matching detectorType.paramNames.

resultSize number

The positive integer length of the logical result array. Primitives sharing a result holder must specify the same size.

result DetectorResult

The result holder. Its object identity associates this primitive with other detector surfaces and with the scene-object state used by draw() and result collection.

Source:

DetectorResult

A mutable holder for the completed result of one logical detector output. Object identity defines the output: detector primitives which reference the same holder accumulate into the same result array, while different holders remain separate even when they belong to the same scene object. This lets a scene object expose several detector outputs without assigning IDs, and lets wrappers such as ModuleObj forward child primitives unchanged.

The holder is preprocessing-only metadata and is never sent to a simulation engine or worker. PrimitiveBasedSimulator assigns it a numeric result ID, retains the reverse binding, and updates values only after readback from a successfully completed current run. Cancelled, failed, and superseded runs leave it unchanged.

Type:
  • Object
Properties:
Name Type Description
values ArrayLike.<number> | null

The most recently completed logical result values, or null before a result is available. The simulator may replace this value or update a compatible preallocated typed array.

Source:

DetectorResultBinding

Simulator-side association between a logical detector result range and the mutable holder supplied by one or more detector primitives. These bindings are deliberately returned beside, rather than inside, processedScene.

Type:
  • Object
Properties:
Name Type Description
resultId number

Logical detector result ID used by processed detector instances.

result DetectorResult

Scene-object-owned mutable holder.

resultSize number

Number of scalars in the logical result.

Source:

DetectorType

Defines how one detector hit contributes to a logical result array. Detector types use the same immutable, structurally deduplicated plain-data convention as surface types. Their DAG accepts the reserved hit inputs documented by SurfaceType, except for n_0 and n_1, together with the instance parameters named by paramNames. Detectors observe ray power rather than participating in refraction, so detector types must not declare or reference n_0 or n_1.

writeCount is the fixed positive number of result writes produced by one hit. For every one-based write index j from 1 through writeCount, the DAG must contain the two labeled scalar outputs k_j and v_j. The engine accumulates each pair as:

result[k_j] += v_j

k_j must evaluate to an integer index within the detector primitive's logical resultSize. v_j is a real-valued contribution. This contract does not prescribe an engine's storage representation or accumulation method; a CPU engine may accumulate floating-point values directly, while another engine may use a different internal representation and convert it during readback.

Type:
  • Object
Properties:
Name Type Description
name string

A human-readable diagnostic name, not a registry ID.

paramNames Array.<string>

The formula symbols and keys accepted in a detector primitive's params object. Their order defines the packed parameter layout and is therefore significant.

dag Object

The formula DAG containing the required k_j and v_j labeled outputs.

writeCount number

The constant positive number of result writes produced by each hit.

Source:

DragContext

Type:
  • Object
Properties:
Name Type Attributes Description
part number

The index of the part within the object being dragged. 0 for the whole object.

targetPoint Point <optional>

The target point where the user is dragging. This is recognized by the editor so that it can be used for popping up the coordinate box (when the user double-clicks or right-clicks such a point), or binding to a handle (when the user holds Ctrl and clicks such a point).

targetPoint_ Point <optional>

If this property is set instead of setting targetPoint, then the point will not be used for the coordinate box or handle, but is still recognized by the editor when deciding which part of which object the user want to interact with.

requiresObjBarUpdate boolean <optional>

Whether the object bar should be updated during the dragging.

cursor string <optional>

The cursor to be used during hovering and dragging.

snapContext SnapContext <optional>

The snap context.

hasDuplicated boolean <optional>

Whether the object is duplicated during the dragging. This is true when the user holds the Ctrl key and drags the whole object. Only set by the editor.

originalObj BaseSceneObj <optional>

The original object when the dragging starts. Only set by the editor.

isByHandle boolean <optional>

Whether the dragging is initiated by dragging a handle. Only set by the editor.

Source:

InteractionCandidate

Type:
  • Object
Properties:
Name Type Description
s number
normalX number
normalY number
u number
sigma number
curveId number
positionTolerance number
positiveRegionCrossings Uint8Array
negativeRegionCrossings Uint8Array
regionCrossingMask Uint8Array
conflictType number
conflictCurveId number
conflictToleranceKind number
conflictTolerance number
Source:

LightSourcePrimitive

A ray source. It has no geometry field: its ray distribution is defined entirely by sourceType and params. A source never contains a PrimitiveCurve and is not inserted into the BVH. The scene object calculates rayCount and any derived sampling parameters each time getPrimitives() is called, so changing global sampling settings does not require a separate sizing DAG.

Type:
  • Object
Properties:
Name Type Description
kind 'source'
sourceType SourceType

The shared per-invocation ray definition.

params Object.<string, number>

Numeric instance and derived sampling parameters matching sourceType.paramNames.

rayCount number

The nonnegative integer number of source-formula invocations.

Source:

Line

Type:
  • Object
Properties:
Name Type Description
p1 Point
p2 Point
Source:

LineSegmentCurveParams

Type:
  • Object
Properties:
Name Type Description
start Point

The start endpoint.

end Point

The end endpoint.

Source:

LineSegmentPrimitiveCurve

Type:
  • Object
Properties:
Name Type Description
kind 'lineSegment'
params LineSegmentCurveParams
Source:

ModuleDef

Type:
  • Object
Properties:
Name Type Description
numPoints number

The number of control points of the module.

params Array.<string>

The parameters of the module.

vars Array.<string>

Mathematical variable definitions that can be used in the objects.

objs Array.<Object>

The objects in the module in the form of JSON objects with template syntax.

maxLoopLength number

The maximum length of the list in for loops to prevent infinite loops.

Source:

OutRay

Variables that can be used in the angle and brightness functions:

  • (\theta_0): The angle of the incident ray.
  • (\lambda): The wavelength of the incident ray.
  • (t): The position of the incident ray on the surface.
  • (p): The polarization of the incident ray. 0 for s-polarized, 1 for p-polarized.
  • (n_0): The refractive index of the source medium (glass merged at the same side as the incident ray).
  • (n_1): The refractive index of the destination medium (glass merged at the opposite side as the incident ray).
  • (\theta_1), (\theta_2), ..., (\theta_{j-1}): The angles of the previous outgoing rays. For (P_j), (\theta_j) can also be used.
  • (P_1), (P_2), ..., (P_{j-1}): The brightnesses of the previous outgoing rays.
Type:
  • Object
Properties:
Name Type Description
eqnTheta string

The LaTeX expression of the angle (\theta_j) of the jth outgoing ray.

eqnP string

The LaTeX expression of the brightness (P_j) of the jth outgoing ray.

Source:

Point

Type:
  • Object
Properties:
Name Type Description
x number
y number
Source:

PreparedCircleGeometry

Type:
  • Object
Properties:
Name Type Description
kind 'circle'
centerX number

World-space center x coordinate.

centerY number

World-space center y coordinate.

signedInvRadius number

Signed inverse radius preserving front-normal orientation.

positionTolerance number

Derived world-space positional tolerance.

endpointTolerance number

Always zero because a circle has no endpoints.

Source:

PreparedCircularArcGeometry

Type:
  • Object
Properties:
Name Type Description
kind 'circularArc'
originX number

World-space chord midpoint x coordinate.

originY number

World-space chord midpoint y coordinate.

tangentX number

Unit chord direction x component.

tangentY number

Unit chord direction y component.

invChordLength number

Inverse chord length.

bulge number

Tangent of one quarter of the signed sweep.

positionTolerance number

Derived world-space positional tolerance.

endpointTolerance number

Minimum world-space endpoint tolerance.

Source:

PreparedCubicBezierGeometry

Type:
  • Object
Properties:
Name Type Description
kind 'cubicBezier'
originX number

World-space normalization origin x coordinate.

originY number

World-space normalization origin y coordinate.

invScale number

Inverse uniform normalization scale.

startX number

Normalized start x coordinate.

startY number

Normalized start y coordinate.

control1X number

Normalized first-control x coordinate.

control1Y number

Normalized first-control y coordinate.

control2X number

Normalized second-control x coordinate.

control2Y number

Normalized second-control y coordinate.

endX number

Normalized end x coordinate.

endY number

Normalized end y coordinate.

positionTolerance number

Derived world-space positional tolerance.

endpointTolerance number

Minimum world-space endpoint tolerance.

Source:

PreparedCurveGeometry

Type:
Source:

PreparedLineSegmentGeometry

Type:
  • Object
Properties:
Name Type Description
kind 'lineSegment'
originX number

World-space start endpoint x coordinate.

originY number

World-space start endpoint y coordinate.

tangentX number

Unit tangent x component from start to end.

tangentY number

Unit tangent y component from start to end.

invLength number

Inverse segment length.

positionTolerance number

Derived world-space positional tolerance.

endpointTolerance number

Minimum world-space endpoint tolerance.

Source:

PreparedSmoothLineSegmentGeometry

Type:
  • Object
Properties:
Name Type Description
kind 'smoothLineSegment'
originX number

World-space start endpoint x coordinate.

originY number

World-space start endpoint y coordinate.

tangentX number

Unit geometric tangent x component from start to end.

tangentY number

Unit geometric tangent y component from start to end.

invLength number

Inverse segment length.

startNormalX number

Unit optical front-normal x component at the start endpoint.

startNormalY number

Unit optical front-normal y component at the start endpoint.

endNormalX number

Unit optical front-normal x component at the end endpoint.

endNormalY number

Unit optical front-normal y component at the end endpoint.

positionTolerance number

Derived world-space positional tolerance.

endpointTolerance number

Minimum world-space endpoint tolerance.

Source:

Primitive

A primitive returned by BaseSceneObj#getPrimitives.

Type:
Source:

PrimitiveCurve

A curve which will be extracted as an individual intersection primitive and inserted into the BVH. Open curves are directed from start to end; this direction is significant for surfaces and for resolving coincident region boundary pieces.

The engine-independent curve parameters are converted during preprocessing into whatever intersection representation an engine requires.

Intersection testing assigns every open curve a native parameter u from 0 at start to 1 at end. A line segment uses its affine parameter, a circular arc uses its center-free rational-quadratic parameter, and a cubic Bezier uses its usual Bezier parameter. A circle has no endpoints or useful native parameter and returns the neutral placeholder u = 0.5.

Reversing a line segment means swapping start and end. Reversing a smooth line segment additionally means swapping and negating its endpoint normals. Reversing a circular arc means swapping its endpoints and negating bulge. Reversing a cubic Bezier means swapping its endpoints and also swapping control1 and control2. Reversing a circle means negating its radius.

Type:
Source:

ProcessedBvh

The BVH node array uses up to four child node indices for branches. A leaf has count > 0; its [start, start + count) range indexes curveIds, whose values index the stable curves table. Branches are stored before leaves so GPU packing can omit standalone leaf records. The BVH may therefore reorder curves without changing curve or owner IDs. Every node's ownerKindMask is the bitwise union of the surface, region, and detector kinds in its subtree.

Type:
  • Object
Properties:
Name Type Description
root number

Root node index, or -1 for an empty tree.

nodes Array.<Object>

BVH4 branch and leaf nodes.

curveIds Uint32Array

Curve IDs in BVH leaf order.

Source:

ProcessedCurve

An intersection curve and its owning processed instance. Surface and detector intersection policy is kept here because it is needed while traversing the BVH, before formula evaluation. Region curves do not have sidedness or wavelength filters.

Type:
  • Object
Properties:
Name Type Attributes Description
geometry PreparedCurveGeometry

Prepared engine-independent curve geometry.

bounds Object

Conservative world-space bounds, including the engine-selected positional and endpoint tolerances.

ownerKind 'surface' | 'region' | 'detector'

Owner table kind.

ownerId number

Index into the matching owner table.

mergesWithBoundary boolean

Whether this curve can participate in an interaction with coincident region boundaries.

twoSided boolean <optional>

Whether both oriented sides participate.

filter WavelengthFilter <optional>

Optional pre-intersection wavelength filter.

Source:

ProcessedDetector

A detector instance. resultId identifies primitives contributing to the same logical scene-object result without prescribing an engine memory layout.

Type:
  • Object
Properties:
Name Type Description
detectorTypeId number

Index into types.detectors.

params Object.<string, number>

Detector instance parameters.

resultId number

Index into the simulator-side detector result bindings.

resultSize number

Number of result scalars.

Source:

ProcessedRegion

A bulk-region instance. All of its boundary curves point back to this record through their ownerId.

Type:
  • Object
Properties:
Name Type Description
bulkTypeId number

Index into types.bulks.

params Object.<string, number>

Bulk instance parameters.

stepSize number

Interior propagation step size.

partialReflect boolean

Whether transmissible boundaries also reflect.

Source:

ProcessedScene

A complete engine-independent scene snapshot.

Type IDs are local to their category and deterministic for a given set of structural definitions. Instance parameters remain plain objects in this common representation. Each engine may use those objects directly or pack the values in the corresponding type's significant paramNames order.

The type signature changes when any canonical type definition changes, independent of primitive encounter order. It can be compared with the previous snapshot to decide whether compiled engine code remains reusable. Runtime parameter values, curves, and detector result sizes do not affect this signature.

This object contains only transferable plain data. In particular, it does not contain the mutable detector result holders owned by scene objects.

Type:
  • Object
Properties:
Name Type Description
numericEpsilon number

Relative arithmetic epsilon selected by the engine for geometry preparation and intersection.

numericalTolerances Object

Engine-ready tolerance minimums. Distance values are in world units and interactionNormal is in radians.

typeSignature string

Structural signature of all four type tables.

types Object
sources Array.<ProcessedSource>
surfaces Array.<ProcessedSurface>
regions Array.<ProcessedRegion>
detectors Array.<ProcessedDetector>
curves Array.<ProcessedCurve>
bvh ProcessedBvh
Source:

ProcessedSource

A source instance. The engine decides whether to use the parameter object directly or pack it according to the corresponding type's paramNames.

Type:
  • Object
Properties:
Name Type Description
sourceTypeId number

Index into types.sources.

params Object.<string, number>

Source instance parameters.

rayCount number

Number of source-formula invocations.

Source:

ProcessedSurface

A surface instance. Its geometry is stored separately in curves.

Type:
  • Object
Properties:
Name Type Description
surfaceTypeId number

Index into types.surfaces.

params Object.<string, number>

Surface instance parameters.

Source:

ProcessedType

A canonical, engine-independent type definition.

The definition is a deeply frozen plain-data copy of the type supplied by a scene object. hash is an efficient lookup key, not the definition's identity: preprocessing also compares the complete canonical representation when hashes match.

Type:
  • Object
Properties:
Name Type Description
hash string

A deterministic structural hash.

definition Object

The canonical type definition.

Source:

PropertyDescriptor

Type:
  • Object
Properties:
Name Type Attributes Description
key string

Dot-separated property path (e.g. 'focalLength', 'p1', 'path.0', 'params.r1'). Numeric segments are array indices. Empty string '' means the root object itself (e.g. PointSource x/y).

type 'point' | 'number' | 'boolean' | 'dropdown' | 'equation' | 'text' | 'style' | 'array'

The type of the property.

styleKind 'stroke' | 'fill' <optional>

For 'style' type: 'stroke' = line/stroke style (color, width, dash); 'fill' = fill style (color only). Required when type is 'style'.

label string

Pre-rendered HTML label string (i18n already expanded).

info string | null <optional>

Optional pre-rendered HTML for an info popover (i18n already expanded).

options Object.<string, string> | null <optional>

For 'dropdown' type: value -> display label map (already translated).

variables Array.<(string|RegExp)> | null <optional>

For 'equation' type: valid variable names (literal strings or RegExp patterns).

differentiable boolean <optional>

For 'equation' type: if true, only the differentiable function subset is allowed (for symbolic derivative). Default false.

readOnly boolean <optional>

If true, the property is display-only (e.g. module name in ModuleObj).

updatesSchema boolean <optional>

If true, changing this property invalidates the schema (reserved for future use).

itemSchema Array.<PropertyDescriptor> | null <optional>

For 'array' type: schema for each array item. Keys within itemSchema are relative to each array element.

Source:

Ray

Type:
  • Object
Properties:
Name Type Attributes Description
p1 Point

The starting point of the ray.

p2 Point

Another point on the ray.

brightness_s number

he intensity of the s-polarization component of the ray.

brightness_p number

The intensity of the p-polarization component of the ray. In this simulator the two polarization components are assumed to be of no phase coherence.

wavelength number <optional>

The wavelength of the ray in nanometers. Only has effect when "Simulate Colors" is on.

gap boolean

Whether the ray is the first ray in a bunch of "continuous" rays. This is for the detection of images to work correctly. The intersection of two rays is considered as a candidate of an image only if the second ray has gap === false.

isNew boolean

Whether the ray is just emitted by a source. This is to avoid drawing trivial initial extensions in the "Extended rays" mode.

Source:

RegionPrimitive

A bulk optical region. The curves must collectively form a valid closed boundary whose interior follows the even-odd rule. Curve order is irrelevant, and reversing the direction of every curve does not change the region. Pieces forming one smooth boundary must nevertheless have consistent directions. A geometrically self-overlapping boundary section must be traversed in opposite directions by its coincident pieces.

At a merged incident point, the engine records whether each region has at least one positive crossing and at least one negative crossing. Repeated crossings with the same sign are idempotent; the region changes parity only when exactly one sign is present. Under the direction constraints above, this is equivalent to the even-odd rule while remaining insensitive to duplicate hits at endpoints of consecutive curve pieces.

Each curve belongs only to this region, even when its geometry coincides with another primitive's curve.

Region-boundary refraction and reflection are built into the engine rather than represented by a formula-defined surface type. When partialReflect is true, a transmissible incident ray produces Fresnel-reflected and transmitted rays. When false, it produces only the transmitted ray. Total internal reflection still produces a reflected ray in either case. More advanced boundary behavior, such as coatings, is represented by overlapping surface primitives instead of additional engine-internal boundary modes.

Type:
  • Object
Properties:
Name Type Description
kind 'region'
curves Array.<PrimitiveCurve>

The region boundary curves.

bulkType BulkType

The shared refractive-index field definition.

params Object.<string, number>

Numeric instance parameters matching bulkType.paramNames.

stepSize number

The nonnegative interior propagation step size in scene units. Zero denotes a spatially homogeneous region; a positive value enables GRIN propagation.

partialReflect boolean

Whether transmissible boundary interactions generate the Fresnel-reflected ray in addition to the transmitted ray.

Source:

SelectionSearchResult

Type:
  • Object
Properties:
Name Type Description
dragContext DragContext

The drag context.

targetObjIndex number

The index of the target object.

Source:

SimulationReturn

Type:
  • Object
Properties:
Name Type Attributes Description
isAbsorbed boolean <optional>

Whether the object absorbs the ray.

newRays Array.<Ray> <optional>

The new rays to be added.

truncation number <optional>

The brightness of truncated rays due to numerical cutoff (e.g. after a large number of partial internal reflections within a glass). This is used to estimate the error of the simulation.

brightnessScale number <optional>

The actual brightness of the ray divided by the brightness inferred from the properties of the object. This should be 1 when "ray density" is high enough. When "ray density" is low, the calculated brightness of the individual rays will be too high (alpha value for rendering will be larger than 1). In this case, the object should rescale all the brightness of the rays by a factor to keep the maximum alpha value to be 1. This factor should be returned here and is used to generate warnings.

isUndefinedBehavior boolean <optional>

Whether the behavior of the ray is undefined. For example, when the ray is incident on a corner of a glass.

Source:

SmoothLineSegmentCurveParams

Type:
  • Object
Properties:
Name Type Description
start Point

The start endpoint.

end Point

The end endpoint.

startNormal Point

The optical front normal at start.

endNormal Point

The optical front normal at end.

Source:

SmoothLineSegmentPrimitiveCurve

A line segment whose optical front normal is the normalized linear interpolation of its endpoint normals. Its intersection geometry and native parameter are identical to those of a line segment. Boundary-crossing orientation remains geometric and is derived from start to end, rather than from the interpolated normal.

Type:
  • Object
Properties:
Name Type Description
kind 'smoothLineSegment'
params SmoothLineSegmentCurveParams
Source:

SnapContext

Type:
  • Object
Properties:
Name Type Attributes Description
locked boolean <optional>

Whether the snapping direction is locked.

i0 number <optional>

The index of the locked direction.

Source:

SourceType

Defines how one invocation emits one ray for a set of source primitives. Like surface types, source type definitions are immutable plain data and are structurally deduplicated during preprocessing, with object identity as a fast path. The DAG uses the format implemented by the formula utilities in src/core/formula.

The reserved DAG inputs are i, the zero-based invocation index, and N, the source primitive's total rayCount. Both are integer-valued formula scalars and satisfy 0 <= i < N. An engine only needs to materialize either input when the DAG references it.

The DAG must contain the seven labeled outputs x, y, d_x, d_y, P_s, P_p, and lambda. x and y are the emitted ray's world-space starting position; d_x and d_y are its unit world-space direction; P_s and P_p are its s- and p-polarized powers; and lambda is its wavelength in nm. An invocation whose two powers are both zero is ignored. A source invocation has no incoming ray and emits only one ray, so these output labels do not use ray-index subscripts.

Sampling density, brightness limits, color mode, and source-specific rounding are resolved by the scene object when it creates the primitive. They affect rayCount and may produce derived entries in params, but raw requested or effective ray density is not a reserved DAG input. The source format also has no gap, isNew, or random-number output.

Type:
  • Object
Properties:
Name Type Description
name string

A human-readable diagnostic name, not a registry ID.

paramNames Array.<string>

The formula symbols and keys accepted in a source primitive's params object. Their order defines the packed parameter layout and is therefore significant, particularly for WebGPU buffers. Names must not collide with the reserved inputs i and N.

dag Object

The formula DAG containing the seven required labeled ray outputs.

Source:

SurfacePrimitive

An optical surface represented by one oriented curve. For a one-sided surface, an intersection from behind the curve's front normal is ignored completely: it is not a surface hit and does not participate in surface merging or ray-depth accounting. Sidedness is interaction policy rather than curve geometry and is therefore stored at the primitive's top level.

Type:
  • Object
Properties:
Name Type Attributes Description
kind 'surface'
curve PrimitiveCurve

The surface geometry.

twoSided boolean

Whether rays approaching from either side can interact. If false, only rays approaching against the curve's front normal can interact.

filter WavelengthFilter <optional>

An optional pre-intersection wavelength filter. Omit this property when filtering is disabled.

surfaceType SurfaceType

The shared surface behavior definition.

params Object.<string, number>

Numeric instance parameters matching surfaceType.paramNames.

Source:

SurfaceType

Defines the optical behavior shared by a set of surface primitives. Type definitions must be treated as immutable. Preprocessing uses object identity as a fast path, then structurally deduplicates equivalent plain-data definitions from separately expanded objects. name is diagnostic rather than a registry ID, but it remains part of that structural definition so differently named types are kept distinct. The DAG uses the format implemented by the formula utilities in src/core/formula.

Before evaluating the DAG, the engine converts the hit into a local orthonormal frame. The adjusted, incident-side normal is mapped to (0, 1), and the local x-axis is obtained by rotating that normal clockwise by 90 degrees. The normal is adjusted for the side from which the ray arrived, so the incoming unit direction satisfies d_0y < 0; a ray exactly tangent to the surface is not considered a hit. For f32 range analysis, -d_0y can therefore use the closed range from the smallest positive f32 through 1.

The following formula symbols are reserved inputs:

  • d_0x, d_0y: components of the incoming unit direction in the local surface frame.
  • P_0s, P_0p: incoming s- and p-polarized powers.
  • lambda: incoming wavelength in nm.
  • x, y: world-space coordinates of the hit.
  • u: the native curve parameter at the hit. It is in [0, 1] for line segments, circular arcs, and cubic Bezier curves. A circle supplies the neutral placeholder 0.5; code must use the curve kind, rather than this placeholder, when deciding whether a hit is at an endpoint.
  • sigma: the geometric side of the hit. It is 1 when the ray approaches against the oriented curve's front normal and -1 when it approaches from behind that normal. Its range is the discrete union {-1, 1} for a two-sided primitive and the singleton {1} for a one-sided primitive.
  • n_0, n_1: effective refractive indices on the incident and opposite sides of the surface respectively.

u and sigma are derived hit inputs, not instance parameters, and therefore are not entries in paramNames or the scene parameter buffer. Detector types use the same reserved hit-input symbols and sigma convention, although their outputs describe accumulated detector data rather than outgoing rays.

For every one-based output index j from 1 through outRayCount, the DAG must contain the four labeled outputs d_jx, d_jy, P_js, and P_jp. d_jx and d_jy are the outgoing unit direction in the same local frame; P_js and P_jp are its s- and p-polarized powers. A slot whose two powers are both zero is ignored. The output count and layout never vary at runtime. Outgoing rays inherit the incoming wavelength and non-optical bookkeeping.

Existing angle-based Custom Surface formulas can be translated with theta_0 = atan2(-d_0x, -d_0y), then with d_jx = -sin(theta_j) and d_jy = -cos(theta_j). Polarization is evaluated directly through P_0s and P_0p; there is no polarization-selector input. If the two polarizations leave in different directions, they occupy separate output slots and the unused power component of each slot is zero.

WGSL range specialization uses the actual packed f32 parameter values of all primitives sharing this type, rather than a largest declared parameter range. Changing instance parameters requires recompilation only when the range-dependent WGSL safety decisions change; otherwise the engine only updates its parameter buffer.

Type:
  • Object
Properties:
Name Type Description
name string

A human-readable diagnostic name, not a registry ID.

paramNames Array.<string>

The formula symbols and keys accepted in a surface primitive's params object. Their order defines the packed parameter layout and is therefore significant, particularly for WebGPU buffers. Names must not collide with reserved surface-DAG symbols.

dag Object

The formula DAG containing the required labeled outputs.

outRayCount number

The constant positive number of outgoing-ray slots.

mergesWithBoundary boolean

Whether the surface interaction supports coincident region boundaries.

Source:

WavelengthFilter

Controls whether a surface participates in intersection testing for a ray. When invert is false, the surface is intersectable for wavelengths in the inclusive interval wavelength ± bandwidth. When invert is true, the surface is intersectable for wavelengths outside that interval. If the filter rejects a ray, the surface produces no hit and does not participate in surface merging or ray-depth accounting.

Type:
  • Object
Properties:
Name Type Description
wavelength number

The center wavelength in nm.

bandwidth number

The half-width of the wavelength interval in nm.

invert boolean

Whether wavelengths outside, rather than inside, the interval are accepted.

Source:

loadJSONCallback(needFullUpdate, completed)

The callback function when the entire scene or a resource (e.g. image) is loaded.

Parameters:
Name Type Description
needFullUpdate boolean

Whether the scene needs a full update.

completed boolean

Whether the scene is completely loaded.

Source:

objBarValueChangeCallback(obj, value)

The callback function for when a value changes. If "Apply to all" is checked, this function will be called for each scene object of the same type.

Parameters:
Name Type Description
obj Object

The scene object whose value changed.

value any

The new value.

Source:

Events

deviceChange

The event when the device type (touch/mouse) changes.

Properties:
Name Type Description
lastDeviceIsTouch boolean

Whether the last interaction is done by a touch device.

Source:

requestUpdateErrorAndWarning

The event when the error and warning messages in the UI should be updated.

Source:

requestUpdateErrorAndWarning

The event when the error and warning messages in the UI should be updated.

Source:

webglContextLost

The event when the WebGL context is lost.

Source: