Astrometrics Card Architecture
custom:lcards-astrometrics-card: a 3D scene (grids, volumes, globes, orbits, routes, nebulae, models) with DOM labels on named points, rendered on demand with three.js through the page's one shared WebGL context. This page covers how the card, the lazy scene runtime and the Astrometrics Studio fit together.
The options themselves are documented for users under Astrometrics (scene, objects, points, camera, data, effects, scale, models, starters). This page links there instead of repeating option tables.
Purpose and location
The card draws an astrometrics lab or stellar cartography display: a galaxy disc with territories, a sector map, a sky dome with the real sun and moon, a solar system at the scene clock's date, a station with ships at true scale inside a galaxy in light years. Points carry LCARS labels, markers and optional Lovelace cards; taps fly the camera; settings and positions can follow entities.
The work is split so that a dashboard without an astrometrics card pays almost nothing for it:
| Where | What | Loaded |
|---|---|---|
src/cards/lcards-astrometrics-card.js | The card element (LCARdSAstrometricsCard): config, hass, actions, rules, entity bindings, label templates, on-card buttons, warp layer, background layer, Studio hooks | Main chunk |
src/cards/astrometrics-registry.js | window.lcards.cards.astrometrics (fly-to, set-clock, set-model-scale by card id) | Main chunk |
src/cards/astrometrics-buttons.js | Pure layout of the camera D-pad and time slider (cameraButtonLayout, TIME_STOPS, dpadPaths) | Main chunk |
src/core/astrometrics/names.js | Every name the config can use (types, shapes, units, live keys), free of three.js so the schema, validator and registries can read it | Main chunk (small) |
src/core/astrometrics/clock.js, warp-drive.js | Clock parsing and date formatting for the time slider; the warp streak layer | Main chunk |
src/cards/schemas/astrometrics-schema.js | The card schema (one branch per object type) | Lazy chunk astrometrics-schema-* |
src/core/astrometrics/index.js and everything it imports | The scene runtime (createAstroScene), scene builder, camera rig, labels, object builders | Lazy runtime chunk (with three.js in the shared three chunk) |
src/core/astrometrics/effects/ | Noise shaders: nebula, cube, fill.effect | Lazy, only when usesEffects(config) |
src/core/astrometrics/model/ | GLTFLoader, meshopt decoder, hologram material | Lazy, only when usesModels(config) |
src/core/astrometrics/edit-tools.js | Studio edit-mode maths (drag forms, selection box) | Lazy, on the first setEditMode(hooks) |
src/core/astrometrics/tribute.js (+ tribute-portrait.js) | The hidden tribute (four taps on reset) | Lazy, on first trigger |
src/editor/cards/lcards-astrometrics-editor.js, src/editor/dialogs/lcards-astrometrics-studio-dialog.js, src/editor/dialogs/astro-studio/ | The card editor and the Astrometrics Studio | Lazy editor chunk |
src/core/astrometrics/starters/ | Starter scenes and parts | Imported by the Studio only (editor chunk), the docs generator and the showcase script |
Supporting files outside src/:
scripts/make-ships.mjs,scripts/make-starbases.mjs,scripts/lib/model-kit.mjs: the built-in GLB models, made in code.scripts/render-model.mjs: renders a GLB from fixed angles for comparison with reference plates.scripts/astro-pictures.mjs(npm run astro:pictures): the Studio's starter, type and shape pictures.scripts/generate-astro-starters-doc.js(npm run docs:astro-starters): the generated part ofdoc/cards/astrometrics/starters.md.scripts/make-astro-showcase.mjs: writesdemo/views/astro-showcase.yamlfrom the starters.custom_components/lcards/services.py: thelcards.fly_toandlcards.set_clockactions;const.py,frontend.pyandmedia_source.py: the user's model folder.
Chunks and loading
There is no manualChunks setting in vite.config.js: every chunk boundary is a dynamic import() in the source.
- Runtime.
loadRuntime()inlcards-astrometrics-card.jsimports../core/astrometrics/index.jsonce per page (runtimePromise); a failed load is not cached, so a later render retries.index.jsre-exports only what the card needs (createAstroScene,labelSources,bindingValue,collectBindings,settingConfig,tourStop, ...). - Schema.
ensureAstrometricsSchema()imports the schema and callsconfigManager.registerCardSchema('astrometrics', ...). The card's staticregisterSchema()(called bylcards-main.jsafter core init) only registers the defaults ({ height: 400 }).setConfig()starts the schema load on the first config of the page; every card whose config arrives before the schema is registered (not only the first) waits for it once and re-processes its latest config then, so it is validated (schemaReady,_awaitingSchema;tests/core/astro-card-wiring.test.js). The editor also callsensureAstrometricsSchema()(its YAML completion needs it). - Effects and models.
missingChunks()inscene-runtime.jschecksusesEffects(cfg)/usesModels(cfg)(names.js) before eachbuild(). When a chunk is missing, the build waits for it (chunkWaitgeneration) and runs again; a failed chunk leavesctx.effects/ctx.modelsnull and those objects are skipped with a warning. - Budgets.
tests/browser/bundle.spec.jsholds the runtime chunk under 210 KB raw / 68 KB brotli, keeps the runtime and schema out of the main chunk, and checks thatedit-toolsis a chunk of its own.
Module map
Card side (main chunk)
| Module | Role | Key exports / symbols |
|---|---|---|
src/cards/lcards-astrometrics-card.js | The card. Owns the scene's lifetime, passes config and hass, resolves label templates and state colours, follows entities (positions, settings, look, warp, tour), runs actions, registers points and objects as rule targets, renders the camera buttons, time slider, pick banner and failure message | LCARdSAstrometricsCard, ensureAstrometricsSchema (internal: SCENE_KEYS, FAILURES) |
src/cards/astrometrics-registry.js | The page's connected astrometrics cards by id; installed as window.lcards.cards.astrometrics | astrometricsRegistry, registerAstrometricsCard, unregisterAstrometricsCard |
src/cards/astrometrics-buttons.js | Pure layout of camera.buttons and the time slider | cameraButtonLayout, dpadPaths, padTokenStyle, timeMode, TIME_STOPS, BUTTONS_IDLE_MS |
src/core/astrometrics/warp-drive.js | warp / warp_factor: a warp-starfield background layer behind the scene; drives the scene's setCruise | WarpDrive, warpOn, warpSpeed, ENGAGE_MS |
src/core/astrometrics/clock.js | clock: { date, rate } parsing and the scene clock | SceneClock, parseDate, parseRate, RATE_PATTERN, LIVE_RATE, DATE_STOPS, formatSceneDate |
src/core/astrometrics/names.js | Names and small pure helpers shared by schema, runtime, validator and registries | OBJECT_TYPES, TYPE_GUIDE, LIVE_TYPE_KEYS, WHOLE_NUMBER_KEYS, UNITS, kmPerUnit, systemScale, realScale, flattenSystems, objectIds, objectById, withObjectPatches, usesEffects, usesModels |
Runtime core (runtime chunk)
| Module | Role | Key exports |
|---|---|---|
index.js | The lazy entry the card imports | re-exports |
scene-runtime.js | The scene API: DOM wrapper and canvas, shared-context acquire and release, build and rebuild, the frame loop, input (pointer, wheel, keys), picking, fly-to, follow, frames, live values, colour fades, looks, rule patches, Studio edit tools | createAstroScene, CAMERA_COMMANDS, MODEL_MIN_PX; typedefs AstroSceneApi, AstroSceneOptions, AstroEditHooks, AstroTapHit |
scene-builder.js | Builds a scene from config without a renderer (so node tests build it headless): systems and frames, objects in two passes, placements, label items, backdrop, per-frame layout() | buildScene, makeLabelItem, disposeBuilt, BACKDROP_STARS, BACKDROP_DUST; typedef AstroScene |
objects/common.js | The builder contract and shared helpers | built, stepObjects, num, pair, sub, isOn, applyRotation, bodyTurn, disposeNode, gridLook, fillFor, DEFAULT_COLORS; typedefs BuildContext, BuiltObject |
placements.js | Named points and their placement forms (xyz, polar, latlon, altaz, sky, body, satellite, at, cell, part) | Placements, BINDABLE_FORMS, bearingXZ, latlonToLocal, altazToLocal, parseCell |
frames.js | Frames for systems at true scale (one frame per type: system) | Frames, ROOT, ENTER, LEAVE |
camera-rig.js | The camera as seven keys plus a projection; drag, wheel, pinch, limits, fly-to tween | CameraRig, viewToKeys, parseLimits, clampKeys, logFlyKeys, lerpKeys, isLogFly, cameraPose, screenRay, rayPlane, DEFAULT_KEYS |
wheel-input.js | Tells a mouse wheel, a touchpad swipe and a pinch apart (camera.wheel) | classifyWheel, wheelAction, wheelZoomFactor |
bindings.js | Settings that follow entities or templates (pure): collect, map, resolve, write back into a config | collectBindings, settingConfig, mapEntity, mapNumber, entityColor, templateColor, dateValue, tourStop, isTourView, easeStep, objectIds (re-exported from names.js), LIVE_OBJECT_KEYS, DEFAULT_SMOOTH_MS |
point-data.js | Point positions from entities and the label fields the card resolves (templates, state colours), with their dependencies | labelSources, fieldNeedsUpdate, bindingEntity, bindingValue |
looks.js | look: diagram / realistic / mixed weights and part switching (pure) | parseLook, lookTargets, stepLook, lookAlpha, partWeights, switchesParts, PART_KINDS |
recolor.js | Colour changes crossfade in place (any type, no code of its own) | colorBase, colorSlots, ColorFades, RECOLOR_MS |
distance-fade.js | fade, min_distance, max_distance for points and objects | ObjectFader, ObjectBounds, distanceAlpha, localBounds, FADE_MS |
depth-passes.js | Depth slices for true-scale scenes (km station, planet, Sun in one view) | depthSlices, drawPasses, starsBehind, SLICE_RATIO |
depth-occlusion.js | Labels hidden behind meshes: a quarter-size depth pass, read back asynchronously | DepthOcclusion, OCCLUDER_LAYER, DEPTH_ENCODE_GLSL |
facing.js | face: motion and face: <point> | Facing, spinTangent, axisFacing |
ephemeris.js | Sun, planets, Pluto, Ceres and major moons at a date, and their rotation (pure) | position, heliocentric, orbitPath, orientation, sphereAxes, toScene, BODIES, MOONS, VALID_RANGE |
sky.js | Local sun and moon from the Home Assistant location (pure) | skyState, sunPosition, moonPosition, dayPath |
label-layer.js | DOM labels over the canvas, laid out per frame (projection, occlusion, distance, collisions) | LabelLayer, layoutLabels, labelItem, pickLabel, LABEL_STYLES |
label-text.js | Which text fields a point shows and how they are styled (pure) | resolveLabel, plainColor, selectedColor, fieldCss, LABEL_POSITIONS |
card-layer.js | Lovelace cards pinned to points (card:) | CardLayer, pointCard, cardBox |
markers.js | Point markers as inline SVG in currentColor | markerSvg, MARKER_SIZE |
lines.js | Fat lines with dashes in screen px and 64-bit anchored vertices | FatLine, PxDashLineMaterial |
grid-mesh-material.js, surface.js, deform.js | Grid line shader on meshes, tessellated surfaces with surf coordinates, deform: warps | gridFace, gridUniforms, surfaceGeometry, sphereGeometry, makeDeformer |
star-field.js | Backdrop stars and dust (px-sized quads, warp streaks) | createStarField, warpTails, cruiseTails, wrapDust |
loading-ring.js, outline-editor.js | The ring over the scene while models load; the Studio's prism outline handles | createLoadingRing, createOutlineEditor |
object-samples.js | One small scene per type and per shape (Studio pictures and per-type tests) | TYPE_SAMPLES, SHAPE_SAMPLES |
nebula-presets.js | preset: badlands / badlands_voyager / nexus | NEBULA_PRESET_CONFIGS, withNebulaPreset |
Object builders (src/core/astrometrics/objects/)
| Module | Types |
|---|---|
grid.js | grid (plane, disc, dome, sphere, cylinder, well; lettered sector maps) |
volume.js | volume (sector, box, prism) |
sphere.js | sphere (globes and planets, body:) |
lines.js | ring, path, beam, trail (built in the second pass, they read points) |
image.js, glow.js | image, glow |
belt.js, asteroid.js, comet.js | belt, asteroid, comet |
galaxy.js | galaxy (the Milky Way by default) |
crystalline.js | crystalline |
lightning.js | lightning (strike or column; lights volume nebulae) |
stars.js | backdrop.stars, backdrop.dust |
../satellites.js | satellites: no builder of its own; expandSatelliteGroups() (called from scene-builder.js) turns a group into satellite points and orbit rings, from the orbital elements in satellite-data.json (npm run sync:satellites) |
diagram.js | Diagram forms (LCARS wireframes for the diagram look): addDiagram, bodyGroup, redrawDiagram |
../effects/nebula.js, nebula-volume.js, cube.js, fills.js | nebula (puffs, or render: volume), cube, fill.effect (effects chunk) |
../model/index.js, hologram-material.js | model (model chunk) |
system has no builder: it is a frame (see Systems and frames).
Lifecycle
Connect and first update
_handleFirstUpdate()(the card's own;LCARdSCardhas none) registers the card as a rules overlay, which first registers every point and object with anidas a rule target (_registerSceneTargets). In the card picker (hui-card-pickerancestor) it stops there and renders a static SVG preview (_renderPreview), so a picker thumbnail never creates a WebGL scene.- Otherwise it adds the card to the registry, notes whether it is inside the card edit dialog (
hui-dialog-edit-card, for point cards in edit mode), and calls_startScene(). _onConnected()covers a view switch: the scene was disposed on disconnect, so it registers again and starts a new scene.
Starting the scene
_startScene() bumps _sceneGeneration (a load that finishes after a disconnect or a newer start is dropped), awaits loadRuntime() and updateComplete, finds .astro-host and calls createAstroScene(host, config, options):
configis_sceneConfig(): onlySCENE_KEYS(camera,backdrop,labels,points,objects,units,time_scale,clock,look,model_scale) of the flattened config (_flatConfig()cachesflattenSystems(this.config)per config object), with rule patches and setting values merged (_withScenePatches).optionscarrieshass,resolveColor,onTap,onHold,onFail,onSky,onClock,onModelScale,mountCardandsetCardHass(AstroSceneOptionsinscene-runtime.js).
After creation the card re-applies what was set on screen and must survive a new scene: the Studio's edit hooks, a model scale set by the button or the V key (_modelScaleSet), the time slider's speed (_timeScale) and a clock set by the slider or an action (_clockSet, advanced by the wall time since). Then _rebuildPointData() works out label sources, entity positions and setting bindings and resolves them once, and _syncBackground() starts background_animation.
Inside createAstroScene
- Creates
div.astro-scene(role="application", keyboard focusable while controls are on), a 2Dcanvas, theLabelLayer, theCardLayerand the loading ring inside the host. acquire(user)joins the shared WebGL renderer (src/core/packs/backgrounds/webgl/three-runtime.js). With no WebGL,fail('no webgl')runs on a microtask; a context loss callsfail('context lost').fail()releases the context and callsonFail, which the card maps to itsFAILUREStext.- Builds the
BuildContext(ctx): concrete colour resolution (resolveColor(..., { concrete: true, element }), parsed to straight sRGB 0 to 1),sky(),date(),requestFrame(),loadTexture(src)andloadModel(src)(both throughfileUrl(), see Models). - Creates the
CameraRig,ObjectBounds/ObjectFader,DepthOcclusion,ResizeObserver,IntersectionObserver,visibilitychange, reduced-motion anddocument.fontslisteners, the sky timer (SKY_INTERVAL_MS, 60 s) and the clock timer (CLOCK_INTERVAL_MS, 1 s). - Calls
build()once and returns theAstroSceneApi.
build()
build() disposes the old world and builds a new one from cfg:
- Waits for missing chunks (see above).
- Works out
usesSky(sky points, sky paths, label templates readingsky.) andusesClock(body points, body or orbit objects, a clock with a sky), applies the config'sclockandmodel_scaleonly when they changed since the last build (clockCfg,modelScaleCfg), and shows the config'slook. buildScene(cfg, ctx, { cssColor }), then label items, markers, selection box, measure line, and everything the card resolved before (label values, entity positions) put back.- Keeps the camera's frame, re-reads
camera.views, and moves the camera only when the start view changed (cameraKey), so adding a view in the Studio does not move the preview. resize(), puts the live values back (applyLive), thenrenderer.compileAsync(scene, camera): shaders compile off the frame,readyturns true, and a fly-to asked for before then (pendingFly, a tour's first stop) runs.
Updates
- Config.
_onConfigUpdated()and_onRulePatchesChanged()call_syncConfig(): a fullscene.setConfig()only when the JSON of_sceneConfig()changed (a theme re-process with the same values rebuilds nothing). A newtime_scaleorclockin the config drops the slider's and the action's value. - Hass.
_handleHassUpdate()passes hass to the scene (setHass: point cards, the sky) and to the background; on the first hass it refreshes every binding, setting and label. After that, entity changes come through the core:_subscribeEntities()subscribes every tracked entity withsubscribeToEntity()(again when the tracked set changes and on reconnect; the base drops them on disconnect),_onEntityChange()gathers the changes of one update and, a microtask later, refreshes only the bindings, settings and label fields that read a changed one. States are read throughgetEntityState()(_entityState()), neverhass.states. - Alert mode and theme.
_onAlertModeChanged()callsscene.recolor(): every object crossfades to its new colours in place (see Colour crossfades); labels use CSS colours (var()stays live) and need nothing.
Disconnect
_onDisconnected() clears the button timer, leaves the registry, cancels a Studio pick and calls _stopScene(): bumps the generation, clears pending setting patches, scene.dispose(), destroys the background renderer, stops the tribute and the warp layer. dispose() cancels the frame and timers, removes every listener and observer, disposes the rig, depth pass, labels, cards, world (geometries and materials), textures and loading ring, releases the shared context and removes the wrapper.
The frame loop
Nothing draws unless something asked for a frame (requestFrame()): a camera key change, motion, data, a resize, a theme change. Off screen (IntersectionObserver) or in a hidden tab the request is remembered (pending) and drawn once visible again.
All of this is frame() in scene-runtime.js. Points to note:
- The scene clock and the motion clock are separate.
dateNow(the scene date,SceneClock) moves bodies, orbits and the sky whatevertime_scalesays.clock(ms of decorative motion: spin, scans, drift, flow) advances bydt * timeScaleand holds under reduced motion, so motion resumes where it stopped. - Layout runs every frame because points can stand on moving things.
world.layout()(scene-builder.js) updates matrices, re-places systems, places objects on points (up to four passes so chains such as a ship on a drydock over a moving planet settle in one frame), turnsfaceobjects, hands lights to lit objects (lightAt) and redraws line objects whose ends move. - One render per frame through
sharedRender(scene, camera, W, H, draw). Before the passes, each visible object'sprerenderhook runs (a volume nebula captures solid depth and marches its gas).drawPasses()draws one pass per depth slice (one pass for any scene that fits the camera's own planes). - Labels after the render, so their projection uses this frame's camera. The depth readback for label occlusion is one frame late; a new depth image triggers one more layout without a new capture (
depthFresh).
Scene model
Config to scene
- Flattening.
flattenSystems()(names.js) lifts everytype: system'spointsandobjectsinto the card's own lists, each marked_system: <id>, the system's own entry kept without them; a system without an id becomessystem#n. Ids are card-wide, so labels, templates, bindings, rules and the runtime all read one flat list. The card, the runtime (createAstroScene,setConfig) andbuildSceneall call it; a config without systems comes back unchanged. - Ids. An object without an
idis namedtype#n, counted per type in config order.objectIds()(names.js) is the one naming:buildScenenames its objects with it, setting bindings use it for their ids, the card finds a binding's object withobjectById()(_flushSettings) and the runtime'spatch()writes patched configs back withwithObjectPatches(), so a setting bound on an object without an id reaches the scene and survives a full rebuild. The Studio'sscopedObjectIds()(systems.js) must agree with it. Its generated points stand on that name. - Two passes. Objects points can stand on are built first (
FIRSTinscene-builder.js, plus the chunk-built types); thenPlacementsis created over them; then the line objects that read points. Line objects can still be hosts for later points (a planet on its spinning orbit ring). - Groups. Each object's node goes into an outer
Groupnamedat:<id>(itsatposition androtation, turned byface; its inner node spins) inside its frame's group. A real body (body:with anonDate) turns itself, so its group takes norotation, on the first build and onrebuildObject()alike (takesRotation()).visible: falsehides the outer group. - Bounds. The bounding sphere of the first-pass objects frames the default view and sizes the dust (
bounds).
The builder contract
Every builder is build<Type>(cfg, ctx) returning a BuiltObject (objects/common.js), made with built(cfg, node, extra) so the defaults are filled in. The fields the rest of the system reads:
| Field | Read by | Purpose |
|---|---|---|
node, radius, centre, placeNode | placements, fly-to, framing | What points on the object stand on and how big it is |
cellPoint, cellAt, warp, unwarpHit, partNode, partNames | placements, picking | cell: on lettered grids, deformed grids, model parts |
points | builder | Generated points (ring and axis labels) placed before the user's |
lines, gridFaces, field | runtime sizeObject() | Fat lines, grid faces and star fields sized to the canvas (px widths) |
pickMeshes | picking, double-tap zoom | Meshes a tap can hit |
occludes, occluder | label layout | Hides labels behind it, as a sphere or by depth |
spin, tick(dt, t) | stepObjects() | Motion; skipped entirely under reduced motion |
onDate(ms) | frame loop | Follow the scene date (bodies, orbits) |
update, dynamic, repin | layout() | Line objects drawn from points; dynamic redraws every frame |
lod({ camera, height, dpr }) | frame loop | Level of detail before the render (belt rocks to dots, crystalline to a dot) |
live(key, value) | applyLive() | Per-type keys changed in place (see Live keys) |
lightAt(world), setLights, contains | layout(), lightning | Lit from a point; lightning inside a volume nebula |
lookParts | frame loop | Diagram and realistic parts switched by the look |
prerender(renderer, scene, camera, w, h, frame) | frame loop | Drawn before the passes (volume nebula) |
materials | recolor.js | Materials off the node tree that colour fades must still reach |
isReady, loadState, drawnSize, realExtent, magnify, modelInfo | runtime, Studio | Models loading, real size, model_scale: visible |
dispose | world dispose | Cleanup beyond geometry and materials |
buildScene wraps every builder in recordingColors(), which records each colour the build asks for through ctx.color (colorInputs) and a snapshot of what the object looks like as built (colorBase). Builders must therefore ask for every colour through ctx.color and be deterministic for a config (seeded randomness), or colour crossfades cannot line up.
Systems and frames
A type: system is a frame (frames.js): a galaxy in light years can hold a star system in km, and inside it a 1.5 km station is exact, which doubles at 26,000 ly could not hold.
Frameskeeps oneGroupper frame. The camera works in one frame at a time (frames.current): world coordinates are that frame's units, its group sits at the origin unscaled, and every other frame's group is placed and scaled relative to it (place()).scaleis parent units per unit (systemScale(): the system'sscale, else itsunitsover the parent's; null and a warning when the parent names none). Systems are never rotated, so yaw and tilt mean the same in every frame. The runtime handles any depth; the schema allows one level.followFrame()runs every frame:Frames.pick(cameraPosition)returns the deepest system the camera is inside (it enters insideENTER= 4 times a system's radius and leaves pastLEAVE= 6), andsetFrame()re-bases the scene, converting the camera keys, a running fly-to's ends and its landing target, the followed point and the warp streak history, so the picture does not move.- A fly-to into a system moves into that frame first (
fly()), then reads the target there exactly. hide_in_systemshides galaxy-scale objects while the camera is inside a system (hiddenHere()).
Units
units (scene) and a system's units name what one unit is (UNITS in names.js: m, km, au, ly, pc). buildScene sets ctx.kmPerUnit(system) so builders can give real defaults in any named unit (the Crystalline Entity is 3 km tall by default, a galaxy the Milky Way's radius, an orbit: ring the body's real orbit), and models are drawn at their real size (realScale(file_units, kmPerUnit), modelSizing() in model/index.js). A scene without named units keeps plain numbers. See Scale.
Live keys
A setting bound to an entity or template is either live (changed in place, eased, no rebuild) or a rebuild key (the object is built again with the new value).
- Generic live keys on any object:
opacity,radius,size,spin(LIVE_OBJECT_KEYSinbindings.js), top level only.applyLive()in the runtime multiplies opacity in through the fader, setsspin, and scales the node byvalue / builtforradiusandsize. - Per-type live keys:
LIVE_TYPE_KEYSinnames.js, as joined paths so either side of a pair can be one (radius.0):
| Type | Keys | most |
|---|---|---|
belt | radius, radius.0, radius.1, thickness, count | count: MAX_ROCKS |
comet | nucleus.size, coma.size, tail.length, glow | |
nebula | drift, drift.0, drift.1, density | |
crystalline | glow, opacity |
- The built object takes them in
live(key, value), returning true when it did;nullputs the built value back.applyLive()tries the object's ownlivefirst, then the generic keys. most: a key such as a belt'scountis built once for the most it can reach (the top of the binding'soutput, capped bymost; written into the config as_most.countbysettingConfig()) and then draws fewer, so it eases instead of rebuilding.- Card-level:
time_scaleandclock.rateare live (setLivewith id'',setClock);warp_factorgoes to the warp layer;clock.datetosetClock. - Easing:
setLive(list)eases from the current value over the binding'ssmoothms (defaultDEFAULT_SMOOTH_MS, 600) witheaseStep()(smoothstep); the first value lands at once, and reduced motion steps.
Colour crossfades
recolor.js makes any colour change fade in place (an alert mode, a theme, a colour bound to an entity, a rule), so nothing flashes and motion carries on.
- A theme or alert change calls
recolorInPlace(); a rule or setting that changes only colours (colorOnly()) callsrecolorObject(id, next). - An object whose recorded
colorInputsall resolve the same as before is left alone. - Otherwise it is built once more off the scene (
world.buildApart(id, next)),colorSlots(live, fresh)lists every value a colour drives (material colours, uniforms, colour attributes, instance colours) where the fresh build differs from the live object'scolorBase, andColorFadesfades them overRECOLOR_MS; the fresh build is disposed. - When the builds do not line up (a different tree, a colour that does more than change a value),
colorSlotsreturns null and the object is rebuilt (rebuildObject); when the backdrop cannot, the whole scene is rebuilt. Models are always rebuilt (their file loads after the build).
Looks
look (card: diagram, realistic, mixed, or { entity }) and look (object: diagram, realistic, all) are combined by looks.js: the runtime eases weights (stepLook, LOOK_FADE_MS) and multiplies lookAlpha() into each object's opacity. Objects without their own look that have a diagram part and a realistic part (lookParts, made with addDiagram() and bodyGroup() in objects/diagram.js) switch the parts instead (partWeights, fader.scaleNodes). See Scene and Looks.
Rule patches
Points and objects with an id are rule targets (types astrometrics-point and astrometrics-object, registered with the systems manager by _registerSceneTargets()), as MSD overlays are. _applyRulePatches() sends the card's own patches the base way and the points' and objects' merged patches (_scenePatches) to scene.patch():
- Patches per id are merged highest priority last (
deepMergeImmutable), with the engine's metadata dropped and an MSD-stylestyle: { ... }object spread (normalizeScenePatch); a rule'slabelreplacestext.label.content. Only ids whose merged patch changed are sent, and the label sources of patched points are rebuilt. - Points: a placement key (
PLACE_KEYS) re-places the point (places.replaceDef), a label key (LABEL_KEYS) rebuilds only its label,visibleandopacityset the label's alpha. - Objects:
visibleand distance keys apply per frame; a colour-only change crossfades; anything else rebuilds just that object (world.rebuildObject), re-sized and with its live values put back. patch()also writes the patched configs intocfgby scene id (withObjectPatches(), so an object without an id, patched by a bound setting, is kept too), so a later full rebuild keeps them. An object sent without its own id is compared and rebuilt as itstype#n.
Camera rig and fly-to
CameraRig (camera-rig.js) makes the camera a pure function of seven keys (tx, ty, tz, yaw, tilt, distance, fov) plus a projection (perspective or orthographic). Yaw 0 puts the camera south of the target (+z) looking north; tilt 90 looks straight down; the camera turns with a YXZ Euler.
- Input.
rig.attach(canvas)handles drag (orbit or pan), wheel and pinch (wheel-input.jsclassifies wheel events),camera.limitsclamp every change (clampKeys,parseLimits; converted into the current frame's units bylimitsNow()). Keys and the on-card D-pad go throughpress(command)/release()(CAMERA_COMMANDS,KEY_COMMANDS): one step on press, then a rate afterPRESS_REPEAT_MS. Home resets, V toggles the model scale, F frames the selection in edit mode. - Fly-to.
rig.flyTo(keys, { duration, ease, projection, warp })is one anime.js tween of a progress value (animate(progress, { autoplay: false })) that the frame loop seeks (rig.step(now)), not anime's own clock. The keys follow the flight's two ends:lerpKeysfor a short flight,logFlyKeyswhen the distance changes by more thanLOG_FLY_RATIO(the distance moves evenly in log, and the target is tied to the zoom). Yaw takes the short way round (shortestYaw). Reduced motion orduration: 0jumps. - What a fly-to lands on. The runtime's
fly(keys, target, opts)recordsflyRef(a point id, re-read exactly after a frame change, or a position in a frame's units) and starts following a point target (startFollow).stepFollow()moves the target, or a running flight's landing target, by how far the followed point moved since last frame (a planet on a fast clock);camera.follow: falseturns that off. - Entry points.
flyTo(view, opts)takes a view name, a point id,{ point }or keys; before the world is ready it is queued (pendingFly).flyToHit()(a tap),flyClose()(a double tap on a point),zoomTo()(a double tap in blank space),goHome()(reset),frameObject()(Studio) all go throughfly(). - Warp streaks. A flight with
warp(the view's, the action's, elsecamera.warp, orcamera.warpfrom an entity throughsetFlightWarp) stretches the backdrop stars and dust along the motion (streaks(),warpTails). The card-levelwarp(cruising at warp) is separate: theWarpDrivelayer plussetCruise(level, factor)(cruiseTails).
User options: Camera and Views.
Time: clock, ephemeris and sky
SceneClock(clock.js) holds a base date at a wall time and a rate in days per second (LIVE_RATE= 1/86400 is real time, 0 holds, negative runs back).set({ date, rate }, wall)changes either and keeps the other running.parseDatereadsnow, ISO dates and Home Assistant's2026-10-30 12:00:00(local time);parseRatereadslive, numbers and unit strings such as1 h/s(RATE_PATTERN, shared with the schema and theset_clockaction's voluptuous schema).- Who follows it.
body:points (Placements,ephemeris.position),body:spheres and rings (bodyTurn()inobjects/common.js: pole and prime meridian fromsphereAxes()),orbit:rings (orbitPath), and the sky once the config has aclock. The frame loop callsonDate(dateNow)on every object that has it. - Redraws. A fast clock (
sceneClock.fast, more than a minute a second) redraws every frame; a slow one is redrawn by the 1 s clock timer; under reduced motion a fast clock also steps once a second. - Ephemeris.
ephemeris.jsis pure maths (JPL approximate elements for the planets, JPL small-body elements for Pluto and Ceres, JPL satellite mean elements for moons, IAU WGCCRE rotation models), in km, handed out in scene axes bytoScene(y up = ecliptic north, ecliptic +y at the bearing convention's north).tests/core/astro-ephemeris.test.jschecks it against JPL Horizons. - Sky.
sky.jscomputes the local sun and moon fromhass.config.latitude/longitude(skyState). Without aclockthe sky follows real time (andsun.sunwhere available); with one it follows the scene date.refreshSky()runs on the sky timer and onsetHass; a change re-drawsmoon_phasemarkers and callsonSky, which makes the card re-resolve label templates that readsky.*(at most everySKY_NOTIFY_MSwhile the clock runs fast). setClock. The card'ssetClock({ date, rate })(registry,lcards.set_clock,set-clockactions, the time slider) calls the scene'ssetClock, then records_clockSetso a rebuilt scene (a view switch) resumes at the right date. A change to the config's ownclockdrops it.onClockreports the date every frame while the clock runs; the card only re-renders the slider readout when the minute changes (formatSceneDate).
User options: The scene clock.
Labels and card layers
Labels and point cards are DOM, not WebGL: they sit inside div.astro-scene over the canvas.
- Label items.
makeLabelItem(def, labelsCfg, cssColor)(scene-builder.js) resolves a point's text fields throughresolveLabel()(label-text.js: built-in style,labels.default,labels.styles[style], the point'scolor,text.default, the field) and returns an item only when the point shows text, a marker or a card. Colours are CSS values, sovar(--lcars-*)stays live under alert modes. - Layout per frame.
updateLabels()in the runtime first sets each item's world position andalphaScale(a rule'sopacityorvisible: false,hide_in_systems, the point's ownlook,below_horizonfor sky andaltazpoints) and collects the occluders.LabelLayer.update()then calls the purelayoutLabels(items, camera, w, h, occluders, dt): project, hide behind sphere occluders (an analytic ray test) and behind depth occluders (theDepthOcclusionsnapshot, a 3x3 texel window), applyfade/min_distance/max_distance, then cull collisions by priority and distance. A solid object standing at a point never hides that point's label (sitting). Only changed transforms and opacities are written (translate3d); a text or colour change re-measures only that label (style()). - Depth occlusion. Objects that occlude by depth (models, cubes) put meshes on
OCCLUDER_LAYER; once per changed frame the runtime renders that layer into a quarter-size target and reads it back withreadRenderTargetPixelsAsync(no stall, one frame late). A shader object can writeDEPTH_ENCODE_GLSLto occlude correctly. - Runtime values. The card resolves templates (
processTemplatewith the point's entity,skyandpointas extras) and state colours (resolveStateColor), and pushes them withscene.setLabelValues(); the runtime keeps them across rebuilds. A per-field sequence number (_labelSeq) keeps a slow Jinja2 result from overwriting a newer one. - Point cards.
CardLayer(card-layer.js) shows a point'scard:where its label would be (show: taptoggles one at a time,alwayskeeps it). The card supplies the elements (_mountPointCard: ahui-cardwrapper, so lazy card types load and visibility conditions apply; a plain element outside a dashboard) and hass (_setPointCardHass). Elements are kept across rebuilds while their config is the same. - Card-level layers. The card's own shadow DOM stacks
.astro-bg(background_animation, aBackgroundAnimationRenderer),.astro-warp(theWarpDrivestreaks),.astro-host(the scene), then the camera buttons, the Studio pick banner and the failure message.
User options: Points, Scene and Looks.
Entity bindings
Three kinds of live data reach the scene, all resolved by the card (it owns hass and the template evaluator) and applied by the runtime:
| Kind | Config | Collected by | Applied with |
|---|---|---|---|
| Positions from entities | xyz / polar / latlon / altaz with entity on a point | bindingEntity(), bindingValue() (point-data.js) | scene.updatePoints() (no rebuild) |
| Label fields | templates and state colour maps in text fields, a point's color | labelSources(), fieldNeedsUpdate() (point-data.js) | scene.setLabelValues() (no rebuild) |
| Settings (R4b, NB2b) | any numeric key of a point or object as { entity, attribute, input, output, clamp, smooth } or a template; object colours as a state map or template; time_scale, warp_factor, clock.rate, clock.date; camera.view as a tour; look, warp, camera.warp with entity | collectBindings() (bindings.js), _collectSettings() | setLive / setClock (live), else scene.patch() (rebuild or crossfade) |
collectBindings(flatConfig)walks every point and object at any depth (deform steps,fill.effect, parts), skipping text, actions and references (SKIP), and returnsSettingBindings keyed bybindingKey()(object:ring1:deform.0.amplitude). An object's colour keys (COLOR_KEYS) are bindings of kindcolor; whole-number keys (WHOLE_NUMBER_KEYS) are rounded so an entity moving within one step does not rebuild;seedis never a setting.- The mapping uses the shared
map_rangewords:inputdefaults to the entity'smin/max, else 0 to 100; nooutputmeans the number as it is; values outsideinputclamp unlessclamp: false. Colours use the state-colour words of the other cards (stateKeyForinstate-color-resolver.js). settingConfig(config, settings, values)writes the current values into a copy of the config (a liveopacitybuilds at 1, since the scene multiplies the value in), so every rebuild (_withScenePatches) builds at the current values._collectSettings()also reads the tour (camera.viewbound to an entity:tourStop()picksviews[n]or a named view, a stop may set the clock), the card'slookentity,warpandcamera.warpentities.- The card tracks every entity these read (
_updateTrackedEntities()), so the base class forwards hass to the core when one changes, and subscribes each of them (_subscribeEntities(), see Hass above). A binding on an object without an id is keyed by itstype#n(object:grid#2:line_spacing).
User options: Live Data.
Rendering details
- One shared WebGL context. Browsers keep about 16 live contexts per page, so every astrometrics card and every three.js background renders through one offscreen renderer in
three-runtime.js(acquire,release,render).render()grows the shared canvas as needed, draws into its bottom-leftw x h, and returns anImageBitmap(transferToImageBitmap, the default whereOffscreenCanvasexists) or the canvas itself (blitmode); in bitmap mode the card's canvas is abitmaprendererone andpresent()crops the card's frame on the GPU and hands it over (no 2D copy: 2D canvases made after a Kiosk Satellite overlay page copy GPU frames slowly, tablet lab K3 bug 4); inblitmode the runtime copies it into the card's own 2D canvas. A context loss fails every user (onContextLost) and starts the retry inwebgl-support.js(1, 3, 10 s); when a new context works,lcards:webgl-restoredfires and the card rebuilds its scene (_onSceneFail(),_awaitWebGLRestore()).window.lcards.debug.webgl.stats()reports users, contexts created and the canvas size. - On demand. See The frame loop: an idle scene draws nothing, and
tests/browser/astrometrics.spec.jschecks that a static scene stops drawing. The device pixel ratio is capped at 2.resize()uses the layout size (clientWidth), not the bounding box, so a dialog opening from a CSS scale (the Studio's) does not leave a small, stretched canvas. - Depth slices. A true-scale view (a station a few km away, a planet 40,000 km behind, the Sun 150 million km further) exceeds one depth buffer.
depthSlices()splits the view into slices of at mostSLICE_RATIO(2e4) near to far from each object's distance range;drawPasses()draws them far to near, clearing depth between. The star shell draws first in its own pass once objects reach past it (starsBehind). - Precision. Fat lines keep 64-bit positions and draw relative to an anchor near the camera (
lines.js), and frames keep a system's contents in its own units, so a route ending at Sol in a galaxy in light years does not jump when seen from inside the Sol system. - Volume nebula.
nebulawithrender: volume(effects/nebula-volume.js) marches the gas at half resolution in itsprerenderhook: a back-face mesh of the region into a target the size of the solid depth image, front to back, stopping at the nearest solid (effects/solid-depth.js: one half-resolution depth capture per frame of everything that writes depth, shared by every volume). The noise comes from a 64^3 tileable texture made once per page (noise3-texture.js: two reads per sample instead of hashing). The region's own mesh then lays the image over the frame. Lightning inside the region lights the gas (setLights, up toMAX_LIGHTS). - Level of detail.
lod()runs before each render: belt rocks become dots, a crystalline entity under about 10 px becomes one dot and draws fewer fork levels below 400 px, and similar. - Reduced motion.
prefersReducedMotion()/onReducedMotionChange()(src/utils/reduced-motion.js): spin,tick, auto-rotate and the motion clock hold; fly-tos jump; colour fades and look changes land at once; warp and warp streaks do nothing; a fast scene clock steps once a second. - Failures.
FAILURESin the card mapsno webgl,context lost,render failedandload failedto a message over the scene (no webglwhile a loss is being waited out counts ascontext lost, which clears itself on restore); the runtime has its own fallback message when noonFailis given. - Headless and GPU in tests. Headless Chromium has WebGL2 through SwiftShader, which is what
npm run test:browseruses: correct but slow, so long astrometrics cases have generous waits. The docs-site Playwright config andscripts/astro-pictures.mjspass four GPU flags (--ignore-gpu-blocklist,--enable-gpu,--use-angle=vulkan,--enable-features=Vulkan) locally to use the real GPU; CI has no GPU, so docs tests on astrometrics pages are tagged@gpu(gpuTag()intests/docs-site/support.js) and skipped there (grepInvertinplaywright.docs.config.js).
Models
type: model (src/core/astrometrics/model/index.js, a lazy chunk) loads a glTF 2.0 binary (plain or meshopt-compressed, not Draco) with named nodes, PBR materials, textures and animation clips.
- Node structure. The object's node (spins) holds
fit(scales the file tosize, its largest extent, centred on its bounds; withoutsize, to its real size in the scene's or system's units:lengthmetres, else as the file measures infile_units), which holdsfile(the glTF scene in its own coordinates). Points on a model (object: <model>,xyz,part) are in file space, sosizenever moves them, and they wait until the file is in (isReady). A faint pulsing box stands in while it loads; the loading ring (loading-ring.js) shows download progress afterRING_DELAY_MS. - Looks.
material: hologram(default) replaces materials withhologram-material.js(Fresnel rim, scanlines, scan band, a depth-only copy so the model is solid);material: originalshows the file's materials lit, and becomes a hologram in the diagram look. Edges are skipped on dense files (EDGE_TRIANGLE_BUDGET). - Real size and
model_scale. A model at its real size can be smaller than a pixel.model_scale: visible(or the size button, the V key, aset-model-scaleaction) draws each real-size model at leastMODEL_MIN_PX(40 px) across (magnifyModels(),b.magnify(k)); the card keeps an on-screen choice until the config'smodel_scalechanges. - File URLs.
fileUrl(src, kind)inscene-runtime.jsresolvesbuiltin:<key>throughassetManager.resolveModelUrl()(orresolveImageUrl()for textures),media-source://...throughassetManager.resolveMediaSourceUrl()(themedia_source/resolve_mediawebsocket command), and passes anything else through. Each model file is fetched and parsed once per scene persrc(modelFiles); a failed load is retried on the next build.
Built-in models
The built-in ships and stations (builtin:constitution_class_refit, galaxy_class, deep_space_nine, earth_spacedock, utopia_planitia_drydock) are fan art made in code: no third-party mesh or texture ships.
- Generators:
scripts/make-ships.mjs(ships;--meshoptalso writestests/fixtures/constitution-class-refit-meshopt.glb) andscripts/make-starbases.mjs(stations), on the shared geometry kitscripts/lib/model-kit.mjs. They write GLB tosrc/assets/models/; the build's asset copy (scripts/copy-assets.js,modelsinASSET_DIRS) puts them incustom_components/lcards/models/, served at/lcards/models/. - Conventions: Y up, metres, origin in the middle of the bounding box, ships' bows toward +z; parts are named nodes whose origins sit where a label belongs (part names are API once released).
- Registry:
model_assetsinsrc/core/packs/lcards-images-pack.js(url, label, description,parts).scripts/lib/registries.jspublishes them asastrometrics.builtin_models(with parts), which the config checker uses to validatesrcandpart:. - Checks:
scripts/render-model.mjs <glb> <outdir> [views]renders orthographic and perspective views for side-by-side comparison with reference plates;tests/core/astro-model.test.jsholds each model's size within 5% (SIZES) and checks every pack part exists;tests/browser/astro-model.spec.jsloads them in the card. - The full workflow (inputs, measuring from plates, scale against ships, lessons) is the
lcards-modelsproject skill (.claude/skills/lcards-models/SKILL.md).
User models
const.py:USER_DIR = "www/lcards"served atUSER_URL = "/lcards-user"; models inMY_MODELS_DIR(www/lcards/models, so/config/www/lcards/models/) at/lcards-user/models.frontend.pycreates the folder at setup and registers the static path without cache headers (a replaced file shows on reload). Files there survive upgrades.media_source.pyadds the LCARdS media source with a My models folder (my_models), because Home Assistant's own media folder refuses glTF;src: media-source://lcards/my_models/<file>resolves through it.- The Studio's file fields use
lcards-asset-source-picker(schema annotationassetSource: 'model' | 'image').
User docs: Your Own Models.
Services and console API
window.lcards.cards.astrometrics
src/cards/astrometrics-registry.js installs astrometricsRegistry at import time. Cards add themselves on first update and on reconnect, and leave on disconnect; a card shown twice (two views, a wall panel) acts everywhere it is open.
| Method | Does | Returns |
|---|---|---|
getAll() | Every connected astrometrics card element | array |
get(id) | The first connected card whose config.id is id | element or null |
flyTo(id, target, { duration, warp }) | target is a view name or point id, { view } or { point } (point wins); calls each matching card's flyTo() | number of cards |
setClock(id, { date, rate }) | Calls each matching card's setClock() | number of cards |
setModelScale(id, mode) | real, visible or toggle | number of cards that took it |
The card element's own public methods: flyTo(view, opts) (ignored with a debug log before the scene exists), setClock(opts), setModelScale(mode), and the Studio hooks attachStudio(hooks), studioScene(), partNames(objectId), pickPosition(request), cancelPick().
For debugging, a card's scene API is reachable as window.lcards.cards.astrometrics.get('<id>')._scene; _scene.debug() returns the frame count, keys, labels, world, rig, live values, depth slices, current frame and more (the browser tests read it).
Actions from other cards
LCARdSActionHandler (src/base/LCARdSActionHandler.js) handles fly-to, set-clock and set-model-scale by calling the registry with the action's card. Inside the astrometrics card, _onSceneAction() runs these on its own scene when card is left out or is its own id, and sends one with another card through the action handler. Every action it runs plays the card sound (card_tap / card_hold), a fly-to on its own scene included. See Action Handler.
lcards.fly_to and lcards.set_clock
handle_fly_toandhandle_set_clockincustom_components/lcards/services.pycopycard_idand the given keys into the payload and fire thelcards_eventpush event through_fire_targeted_event(); the optional device and user targets restrict which frontends act.- Schemas:
fly_toneeds aviewor apoint(duration0 to 60000 ms,warpbool);set_clockneeds adateor arate(ratea number,live, or a unit string matching the same pattern asRATE_PATTERN). IntegrationService._handleLcardsEvent(src/core/services/IntegrationService.js,case 'fly_to'/case 'set_clock') calls the registry and logs how many cards on this page took it. There is noset_model_scaleservice; that is a card action only.
See Integration Service for the push channel and Home Assistant actions for the user side.
Astrometrics Studio
The card editor (src/editor/cards/lcards-astrometrics-editor.js) is a thin launcher: identification and sizing fields, and a button that opens lcards-astrometrics-studio-dialog on a copy of the config through mountDialogNearHomeAssistant(). Save replaces the config whole (deleted keys must go).
The Studio (src/editor/dialogs/lcards-astrometrics-studio-dialog.js) is a full-screen dialog whose live preview is a real lcards-astrometrics-card (_mountPreview()), so labels, templates, state colours and point cards behave as on the dashboard:
- Edit mode.
card.attachStudio({ onSelect, onDrag, onView })calls the scene'ssetEditMode(hooks): taps select instead of acting, points can be dragged in their own placement form (dragForm()inedit-tools.js), objects are boxed (highlight), F frames the selection. The hooks survive scene rebuilds. - Scene API used by the Studio.
studioScene()resolves with theAstroSceneApionce it exists:cameraKeys,viewNow(a captured view's target as a point id when the camera looks at one),viewIn(the scale bar),frameObject,placeAt/placementAtandpickPosition(place mode),measureAt/showMeasure,setHold,editOutline/finishOutline(prism outlines),modelInfo,modelState. - Preview only. The toolbar's look, isolate and quick views (
astro-studio/preview-tools.js) change the preview's config, never the saved one. - Forms from the schema. Each object's form is generated from its type's schema branch (
lcards-astro-schema-form.js,fieldKind()inschema-fields.js), so a new object type or key needs no Studio form code. Bindings, templates and tours get their own sub-panels. - Scopes. The Points and Objects tabs edit the scene's lists or one system's (
astro-studio/systems.js; ids stay card-wide and must match the runtime'stype#nnaming). - History. Every commit goes through
_commitandstudio-history.js(undo and redo, merged within a short window per path). - Starters. The Starters tab applies
src/core/astrometrics/starters/(applyStarter,fitFactor,unitsClash): a scene replaces, a part merges with its ids prefixed; a starter can be tried in the preview before Keep or Discard.
User docs: Getting Started: The Studio.
Starters
src/core/astrometrics/starters/index.js lists STARTERS: each is { id, kind: 'scene' | 'part', title, summary, description, icon, params, build(params), picture? }, and build returns a fragment (points, objects, views, camera, backdrop, units, clock). applyStarter() prefixes a part's ids and every reference to them (REF_KEYS), fits a part to the target scene's size or units (fitFactor, sceneExtent() in extent.js), and the user owns every line afterwards.
starters/yaml.js(starterYaml) writes a starter's config as the docs write scenes; the Studio's Starters tab andscripts/lib/astro-starters-doc.jsshare it.npm run docs:astro-starters(scripts/generate-astro-starters-doc.js,--checkfor staleness) rewrites the generated part ofdoc/cards/astrometrics/starters.md.npm run astro:picturesrendersstarter-<id>.webp(andtype-<type>.webp,shape-<type>-<shape>.webpfromobject-samples.js) on the browser harness with a pinned date and seed, intosrc/assets/images/astro-studio/(served at/lcards/images/astro-studio/).scripts/make-astro-showcase.mjswritesdemo/views/astro-showcase.yamlfrom the starters, so the showcase stays in step with them.
Testing
| Layer | Files | Covers |
|---|---|---|
Node (npm test) | tests/core/astro-*.test.js (one file per area), tests/core/validation-astrometrics.test.js | Headless scene builds under jsdom (tests/helpers/jsdom-env.js, buildScene without a renderer), each object type, placements, frames and systems, units, camera maths, fly-to keys, bindings, clock, ephemeris (against JPL Horizons), sky (against PyEphem), labels and label text, recolor (every type in TYPE_SAMPLES and SHAPE_SAMPLES must crossfade), diagram forms, models (sizes, parts), starters, the warp and tribute timelines, schema validation |
| Node, editor | tests/editor/astro-*.test.js | Studio fields from the schema, TYPE_GUIDE against the objects page table, camera views, clock fields, history, preview tools, systems scopes, starter, type and shape pictures (every type needs a TYPE_SAMPLES entry and a TYPE_GROUPS slot) |
| Node, docs | tests/docs/astrometrics-config.test.js, tests/core/astro-schema-docs-audit.test.js, tests/docs/astro-starters-doc.test.js, tests/docs/astro-starter-tiles.test.js | Doc examples and schema against the config checker |
Browser (npm run test:browser) | tests/browser/astrometrics.spec.js and tests/browser/astro-*.spec.js (studio, model, cards, deform, satellites, beam on ring, state settings, well morph, whirlpool, wormhole light), fixtures tests/browser/fixtures/astro-*.yaml | The lazy runtime loads; scenes draw on the shared context with labels; an idle scene stops drawing; taps, holds and drags; fly-to and follow; bindings (window.__setState); reconfigure; alert recolour; context loss and restore; disconnect releases the context; picker preview; Studio flows; built-in models; point cards |
Visual (npm run test:visual, local) | tests/browser/visual.spec.js (astro-galaxy, astro-sector, astro-labels, astro-nebula-volume, astro-nebula-shapes, astro-badlands, astro-nexus, astro-crystalline) | Screenshot baselines |
Real Home Assistant (npm run test:ha) | tests/ha/ha.spec.js | lcards.fly_to flies the card on the lcards-test dashboard |
Docs site (npm run test:docs) | tests/docs-site/live-cards.spec.js, demo-board.spec.js | Live astrometrics examples mount; tagged @gpu, skipped on CI |
| Bundle | tests/browser/bundle.spec.js | Runtime and schema are lazy chunks; runtime size ceiling; edit-tools chunk |
Browser tests read the scene through the card element: document.querySelector('#mount > *')._scene.debug() (see sceneState() and pointOnPage() at the top of astrometrics.spec.js). Demo views for review live in demo/views/astro-*.yaml (pushed with npm run demo:push).
Extending: adding an object type
This follows how asteroid and comet (AC1, a20a503e) and crystalline (CE1, 46169ef9) were added, plus what later sessions made every type carry (colour crossfades, d6a8d1d6; diagram forms, 9cfdb3c7, c7acc53c). The lcards-card-option project skill covers the schema, docs and registry side of any new key.
- Name it in
src/core/astrometrics/names.js: add the type toOBJECT_TYPESand a row toTYPE_GUIDE(use and icon). New enums the type takes go here too, whole-number keys that can follow entities inWHOLE_NUMBER_KEYS, and keys it changes in place inLIVE_TYPE_KEYS. The registries (scripts/lib/registries.js) pick upOBJECT_TYPESthemselves. - Write the builder
src/core/astrometrics/objects/<type>.jsexportingbuild<Type>(cfg, ctx)that returnsbuilt(cfg, node, { ... }):- every colour through
ctx.color(value, fallback)and every random choice seeded from the config (recolor needs a fresh build to line up with the live one); - default sizes in named units through
ctx.kmPerUnit?.(cfg._system)when the type has a real size; - motion as
tick(dt, t)(held under reduced motion by the runtime) orspin; level of detail aslod(); in-place keys aslive(key, value)returning true, withnullrestoring the built value; a light source aslightAt(); - a diagram form: put the realistic body in
bodyGroup()and add the wireframe withaddDiagram(out, { runs, color, body })(objects/diagram.js), so the diagram look has something to show; dispose()for anything beyond geometry and materials.
- every colour through
- Register it in
FIRSTinsrc/core/astrometrics/scene-builder.js(a type that reads points goes in the second pass withring,path,beam,trail; one built from the effects or model chunk goes throughctx.effects/ctx.modelsandusesEffects()/usesModels()innames.js). The bounds useb.type in FIRST, so a first-pass type counts for the default view. - Schema: a
<type>Objectbranch insrc/cards/schemas/astrometrics-schema.jswithrequired: ['type'],allOf: [objectCommonSchema],type: { const: '<type>' }, keys made withsetting(),wholeSetting(),objectColor()andpart()so bindings and colours work, and adescriptionon every property (scripts/check-schema-descriptions.js); add it toOBJECT_SCHEMAS. Reuse the words other cards and types use (tests/docs/schema-vocabulary.test.js). - Studio: put the type in a group of
TYPE_GROUPS(src/editor/dialogs/astro-studio/starter-gallery.js), add a sample toTYPE_SAMPLES(andSHAPE_SAMPLESfor shapes) insrc/core/astrometrics/object-samples.js, and render its picture withnpm run astro:pictures type-<type>(writessrc/assets/images/astro-studio/type-<type>.webp). The form itself comes from the schema. - Starter part (optional):
src/core/astrometrics/starters/part-<name>.js, added toSTARTERS, thennpm run docs:astro-startersandnpm run astro:pictures <id>. - Docs: a section with a live example on the right objects topic page (
doc/cards/astrometrics/objects/*.md), and the row in the objects page's "Which type for what" table matchingTYPE_GUIDEexactly. - Demo view:
demo/views/astro-<name>.yamland its entry indemo/order.yaml, usinglcards_test_*helpers (new helpers intests/ha/ha-client.mjs). - Tests: a node suite
tests/core/astro-<type>.test.js(shape, size in units, level of detail, live keys, schema, the starter); the per-type suites pick upTYPE_SAMPLESon their own (recolor, starter pictures; add the type to the list inastro-diagram-forms.test.js); a browser fixturetests/browser/fixtures/astro-<type>.yamlwith a case inastrometrics.spec.jsand, if it should have a baseline, in thevisual.spec.jslist; update the Studio tile count inastro-studio.spec.js. - Run
npm run build,npm testandnpm run test:browser(one at a time), thennpm run demo:pushfor review.
See also
- Astrometrics user docs
- Action Handler:
fly-to,set-clock,set-model-scale - Asset Manager:
model_assets,resolveModelUrl,resolveMediaSourceUrl - Integration Service: the
lcards_eventpush channel - Rules Engine: rule targets and patches
- Background Animation System: the shared three.js runtime and
warp-starfield - Colour resolution:
resolveColorand concrete colours for WebGL