Skip to content

Latest commit

 

History

History
562 lines (387 loc) · 32.4 KB

plan.md

File metadata and controls

562 lines (387 loc) · 32.4 KB

Crystal Viewer — Implementation Plan

This document sequences delivery and acceptance checks. Requirements belong to the documents in the documentation map; the V1 checklist is the authority for release scope.

Implementation Sequence

Recommended implementation sequence for crystal systems:

1. Cubic
2. Tetragonal
3. Hexagonal
4. Trigonal
5. Orthorhombic
6. Monoclinic
7. Triclinic

The order may be changed if required by the selected prototype minerals.


First Complex Prototype

Quartz is the first complex prototype, after the generic engine and a simple cubic mineral validate the architecture.

The quartz implementation should support:

  • trigonal crystallography
  • hexagonal coordinate setting
  • prism forms
  • positive and negative rhombohedra
  • several named habits
  • face identification
  • morphology sliders
  • left/right handedness where applicable

This establishes whether the architecture can correctly generate recognizable crystal forms for a non-trivial system.


V1 Milestones

M1 — Geometry Prototype

Status: complete. See the M1 acceptance audit for bootstrap, delivery, tests, acquisition integrity, and benchmark evidence.

Begin M1 with a repository bootstrap gate. Before scientific feature implementation, establish and document:

  • the package manager and workspace configuration;
  • package directories and enforcement of the allowed dependency graph;
  • shared and package-specific TypeScript configuration;
  • module format and supported runtime targets;
  • build and test commands; and
  • a non-browser test environment for crystal-core.

The gate is complete when a clean workspace installation builds all initially created packages, crystal-core tests run without browser globals, and the package graph conforms to the architecture contract. Record the selected tools and commands in architecture or repository documentation.

Deliver:

unit-cell mathematics
reciprocal lattice
Miller planes
symmetry resolution and input validation
validated operation registry sufficient for the cubic prototype
half-space intersection
generic crystal geometry output
generic crystallography and morphology input contract
explicit invalid-geometry diagnostics
shared structured diagnostic envelope and M1 core diagnostic codes
direct half-space intersection with polygon-loop output

No polished UI required.

Verify that crystal-core builds and runs in a non-browser environment without browser or rendering dependencies, following Package Dependencies and Ownership.

Implement the symmetry contract in Symmetry Resolution and Miller Indices during M1. Expand registry coverage with the later crystal-system and CIF milestones; a complete space-group registry is not required for the first prototype.

Before implementing registry lookup, complete the data acquisition checkpoint for the M1 cubic operation subset. Prefer a pinned, machine-readable, permissively redistributable source and record its normalization method and integrity information under the Operation Registry contract.

During M1, define the exact tagged MillerIndices representation and implement its integer validation, rejection of all-zero indices, canonical reduction, three-index behavior, and preservation of opposite oriented planes.

Required symmetry tests:

  • Explicit operations and registry lookup produce equivalent results.
  • Conflicting identifiers and operations are rejected before geometry generation.
  • Missing symmetry is rejected; explicitly requested identity-only symmetry is accepted.
  • Miller indices transform correctly in a non-orthogonal basis.
  • Opposite faces and inversion symmetry are not added unless generated by the supplied operations.
  • Space-operation translations affect atomic positions but not generated face directions.
  • Operation sets satisfy identity, closure, inverses, and unit-cell metric compatibility under documented tolerances.

Required lattice tests (Coordinate and Lattice Conventions):

  • A cubic cell produces orthogonal axis-aligned direct-lattice vectors.
  • Orthorhombic, monoclinic, and triclinic reference cells reproduce their metric tensors.
  • The determinant of the direct-lattice matrix agrees with the crystallographic cell-volume formula.
  • Cartesian dot products reproduce fractional-coordinate metric products.
  • Direct and reciprocal bases satisfy transpose(L) * reciprocalLattice = identity under the documented tolerance.
  • Invalid lengths, impossible angle combinations, and degenerate cells produce input-validation diagnostics.
  • Equivalent cells supplied through supported length-unit conversions produce equivalent direct and reciprocal bases.

Success criterion:

Given a simple set of crystallographic forms, the engine generates the expected convex crystal.

Required acceptance tests (Geometry Output, Half-Space Intersection, and Geometry Validation):

Input Expected result
Six enclosing cube planes Valid closed polyhedron
Equivalent unit cells supplied through supported unit conversions, with identical symmetry and morphology settings Equivalent normalized cells and geometry under the internal unit convention
All forms disabled or zero development core.geometry.no-active-forms
Prism planes without end caps core.geometry.unbounded
Prism planes with enclosing end caps Valid closed polyhedron
Redundant plane outside an enclosed crystal Valid; no face generated for the redundant plane
Invalid settings followed by valid settings Diagnostic, then successful generation
Same shape at different supported morphology scales Same validity classification
Matching normals with different support distances Tighter boundary retained; looser form excluded from that face's contributors
Coincident constraints from different forms One surviving face with all contributors and operation IDs grouped by form
Multiple symmetry operations producing one direction within a form One constraint retaining all originating operation IDs
Reordered input forms Same geometry and contributor attribution
Development changes that change the controlling constraint Effective boundary and contributors updated, including ties becoming a single contributor without vertex changes
Opposite-facing plane constraints Separate constraints retained

Required numeric tests (Numeric Policy):

  • Non-finite scientific inputs and development values outside [0, 1] are rejected before geometry generation.
  • Zero development omits the form; positive development yielding a non-finite normalized support distance is rejected.
  • Core calculations and geometry output remain double precision; conversion to Float32Array occurs only in crystal-three.
  • Changing only morphologyScale across the documented supported range scales output coordinates and bounds without changing topology, contributor attribution, or validity classification.
  • Named matrix, plane, vertex, and degeneracy tolerances are exercised independently, including near-degenerate cases.

Required algorithm and topology checks (Intersection Algorithm):

  • Positive-spanning normals are recognized as potentially bounded; normals admitting a non-zero recession direction return core.geometry.unbounded.
  • Triple-plane enumeration reconstructs the expected vertices and ordered polygon loops for reference solids.
  • Polygon winding agrees with outward normals, the first boundary index is not repeated, and redundant collinear boundary vertices are removed.
  • Renderer triangulation maps every triangle back to its originating core face and contributors.
  • Reordered forms and constraints produce deterministic topology and attribution.
  • Representative and deliberately large V1 plane sets have recorded benchmark results; failure to meet interactive needs triggers evaluation of a compatible geometry dependency or dual-hull implementation through a superseding decision record.

Exercise the overlapping-constraint rules within bounded fixtures and under the documented comparison tolerances. At viewer integration, verify that picking exposes all current contributors and equivalent-face highlighting respects the selected contributing form (Picking and Face Inspection).

Define scale-relative tolerances and test core.geometry.degenerate and core.geometry.numerical-failure diagnostics. At viewer integration, also verify that an invalid edit retains the last valid mesh with an exposed stale status, an initially invalid request displays no mesh, and a subsequent valid edit clears the diagnostic and replaces the mesh (Viewer Lifecycle).

Define the finite M1 core.* diagnostic-code set under the shared diagnostic contract. Verify that validation reports all safely determinable issues in deterministic order, host logic can branch on stable codes, warnings can accompany successful results, and expected invalid inputs do not escape as untyped exceptions.

M2 and M3 may use provisional mineral records, but they must pass through the generic core input contract established in M1. Mineral-specific generator logic is not permitted at any milestone.

Data Acquisition Checkpoint

At the start of M1, M2, M3, M5, and M6, identify the external records and references required by that milestone and complete the acquisition and licensing record. M1 applies this checkpoint to the symmetry-operation registry and scientific reference fixtures. If access or redistribution requires project-owner action, report the exact action before the affected work becomes blocked. The request must identify the source, artifact, reason, destination, and available integrity check. Continue unrelated milestone work while waiting.

The V1 mineral records remain version-controlled project data under the catalog storage strategy; selecting a runtime database is not a prerequisite for these milestones.


M2 — Simple Cubic Mineral

Status: complete. See the M2 acceptance audit for delivery, tests, provenance, and form-transition evidence.

Implement fluorite as the first cubic mineral in the content delivery matrix.

Support combinations of:

cube
octahedron
other common forms

Success criterion:

Relative form-distance changes produce correct transitions between common cubic morphologies.

Complete fluorite's habit coverage according to the content delivery checks.

Establish the minimum provenance representation with fluorite. Verify coverage of its shipped scientific data, traceable source references, explicit curated values, and methods and input references for any derived values.

Deliver the first runnable milestone demo with the rendered fluorite vertical slice. Provide form-development sliders with visible numeric values, reflect the current requested settings, and display invalid-geometry status. The demo may use a provisional viewer API, but it must use generated geometry and the exported viewer boundary.


M3 — Quartz

Status: complete. See the M3 acceptance audit for delivery, tests, provenance, habit, handedness, and face-inspection evidence.

Implement:

trigonal symmetry
Miller-Bravais notation
quartz forms
basic habit presets
morphology sliders
face picking
face labels

Define and implement the setting-aware Miller-Bravais conversion during M3. Validate it against published hexagonal and trigonal reference cases, including invalid i values and use with an incompatible setting.

Success criterion:

Multiple recognizable quartz habits are produced by the same procedural engine.

Complete quartz's habit coverage according to the content delivery checks.

Validate the supported left/right variants, including symmetry and face assignments, against sourced reference fixtures. Demonstrate variant selection and inspection through the API and reference application; visibly different geometry is not required for every habit.

Resolve the asymmetry decision during M3 habit selection. Acceptance requires either implemented and validated behavior for dependent presets, or a documented selection of V1 habits that can use the existing form-level controls with asymmetry explicitly deferred. Reassess this dependency when selecting the remaining habits in M5.

Validate habit preferred views during M3: vectors use the crystal-local Cartesian frame, invalid or parallel direction/up combinations are rejected, the lattice-based up fallback is deterministic, habit changes preserve the current camera, and initial framing or explicit camera reset applies the preferred view. Restored camera state must take precedence.

Add a quartz demo with habit selection, synchronized form sliders, handedness selection, and face inspection. Keep the M2 fluorite demo runnable.


M4 — Mineral Data Infrastructure

Status: complete. See the M4 acceptance audit for schema, validation, catalog/loading, provisional-record, and viewer regression evidence.

Stabilize the reusable mineral and morphology schemas, catalog organization, validation, and loading paths in crystal-data. Move the provisional fluorite and quartz records from M2 and M3 into this permanent structure without changing the generic core input contract.

Mineral-specific generator logic is prohibited throughout development:

function generateQuartz() {}

The engine must continue to receive generic data:

generateCrystal(mineral, morphology);

Success criterion:

Shipped and provisional mineral records use the same validated data path, and adding a mineral requires no mineral-specific changes to crystal-core.


M5 — Multiple Crystal Systems

Status: complete. See the M5 acceptance audit for the shipped minerals, crystal-system fixtures, paired trigonal-setting fixture, and multi-mineral demo evidence.

Add:

tetragonal
orthorhombic
hexagonal
monoclinic
triclinic

Use representative minerals for validation.

Add one paired trigonal-setting fixture: represent the same sourced crystallographic definition in hexagonal and rhombohedral settings with an explicit basis transformation between them. Calcite is the preferred candidate because its shipped record is delivered in M5; the exact fixture may be selected during M5.

Verify that both settings resolve valid lattice and symmetry operations and that equivalent planes produce the same Cartesian directions after basis conversion. Confirm the expected physical relationships between the converted unit cells and generated geometry. This fixture supplements the M3 quartz coverage; it does not need to define another shipped mineral or habit.

Success criterion:

Complete both the shipped mineral coverage and the crystal-system fixture coverage in Mineral and Crystal-System Coverage, including the remaining mineral records and habits.

Add a multi-mineral demo with mineral and habit selection and visible crystal-system and setting information. Its controls must update when the selected record or habit changes.


M6 — CIF / Structural Data

Status: complete. See the M6 acceptance audit for the V1 import boundary, CIF import, atomic expansion, periodic bonds, rendering, view modes, and demo evidence.

Before implementation, document the supported import subset required by the V1 Import Boundary. CIF bond import is optional; internal periodic bond resolution and rendering remain required.

Implement:

CIF import
unit-cell display
atomic coordinates
symmetry expansion and periodic bond resolution
atomic structure rendering

Success criterion:

The viewer can load structural data independently of morphology data.

Required acceptance tests (Atomic Structure and CIF Support):

  • Symmetry-independent sites expand into the expected complete reference cell.
  • Multiple operations producing the same image of a source site do not duplicate atoms.
  • Complete-cell data is not expanded a second time.
  • Distinct partially occupied source sites are preserved, including coincident alternatives.
  • Periodic bonds connect the correct images across cell boundaries.
  • Incompatible cell/basis combinations are rejected; explicit basis transformations preserve the structure.
  • Atomic structure, unit-cell overlay, and morphology have consistent orientation.
  • Viewer integration of the paired trigonal-setting fixture displays the axes and unit cell appropriate to each declared setting.
  • Separate morphology and atomic structure views provide the V1 view capabilities, including optional axes and a unit-cell overlay for morphology and atoms, available bonds, and repeated cells for atomic structure. Combined view is deferred beyond V1 and is not an M6 acceptance requirement.
  • Missing bonds permit an atoms-only view, and inferred bonds are identified as derived.
  • Ambiguous site representation produces an import diagnostic.
  • Imports preserve available source metadata and distinguish imported values from inferred values, following the provenance contract.
  • Representative CIF 1.1 fixtures within the documented subset import successfully; unsupported formats and constructs produce diagnostics.
  • Files with multiple structural blocks require explicit selection and import the selected structure.
  • Numerical uncertainty notation and missing-value markers receive the documented handling; missing required information produces a diagnostic.
  • Explicit symmetry operations and supported registry identifiers resolve correctly; unsupported or ambiguous identifiers and conflicting descriptions produce diagnostics.
  • Supplied CIF bond data omitted by the importer is reported. If bond import is supported, fixtures verify symmetry-reference and cell-translation resolution into periodic endpoints.

Include fixtures for every rejection case in the documented import boundary, including ambiguous site representation.

Add an atomic-structure demo with view-mode, unit-cell, bond, and lattice-repetition controls. Reflect the loaded structural definition and current repetition settings, and show import or loading diagnostics.


M7 — Viewer API

Status: complete. See the M7 acceptance audit for the stabilized API, Web Component, state serialization, loading/lifecycle contracts, demos, and decisions.

Stabilize public API:

load mineral
set habit
set form development
select face
display axes
display unit cell
serialize state
restore state
dispose viewer
invalid-geometry status, events, and recovery

Document all public interfaces.

Required acceptance checks for the Web Component and reference demos:

  • Embed the component in plain HTML without a framework.
  • Demonstrate two independent instances on one page and verify that their configuration, selection, and lifecycle do not interfere.
  • Ship the basic-embedding and programmatic-controls/events demos, and update all earlier milestone demos to the stabilized API.
  • Verify that demo controls initialize from current state and remain synchronized after user edits, programmatic changes, and state restoration.
  • Exercise lifecycle behavior and state restoration through the component, including preservation of the selected quartz variant.

Exercise the loading and connection contracts during initial viewer integration and complete these acceptance checks by M7:

  • Failed mineral loads preserve the current configuration and geometry and expose a diagnostic.
  • Overlapping loads permit only the newest request to commit; superseded completions cannot mutate state or emit success events, including when the newest request fails.
  • Committing a different mineral clears the previous morphology mesh. Invalid morphology in the newly loaded definition shows no morphology mesh and exposes the diagnostic; invalid edits within the same definition retain its last valid mesh.
  • Disconnecting and reconnecting preserves configuration and the previous rendering mode without duplicate listeners or loops; rendering is paused and external listeners are detached while disconnected.
  • Disposal releases resources and invalidates pending work. Repeated disposal is harmless, later mutating calls report disposal, and reconnection does not reactivate a disposed component.

Required acceptance tests for the state serialization contract:

  • Save and restore a modified habit with disabled forms and a non-default morphology scale.
  • Restore camera, persistent display settings, atomic view mode, and lattice repetition settings.
  • Verify that saved effective settings take precedence over preset defaults for compatible referenced data.
  • Restore an imported structure in a fresh viewer without relying on the original import session.
  • Verify that imported definitions retain their provenance through state restoration.
  • Reject malformed state, unsupported versions, and missing or incompatible required references without partial mutation.
  • Accept structurally valid state that produces invalid geometry; verify both fresh-viewer and retained-mesh behavior and subsequent recovery.
  • Verify that getState → setState → getState preserves equivalent persistent configuration.
  • Restore each representation of the paired trigonal-setting fixture and verify that its declared setting is preserved.

Resolve the versioning, data-compatibility, and face-selection decisions identified in the owning contract during M7. Define appearance-state coverage in M7 and verify selected appearance and user-override round trips when M8 delivers appearance support.


M8 — Appearance

Status: complete. See the M8 acceptance audit for the appearance fields, material mapping, data model, viewer API, state restoration, reference-scene review, and demo evidence.

Add:

base color
roughness
metalness
transmission
IOR
absorption color
absorption density
basic transparent and metallic mineral appearances

Transmission is the only mineral-transparency control in V1. opacity remains deferred; renderer-level fading does not expand the appearance contract.

Use documented quartz, fluorite, and pyrite reference scenes under the appearance validation policy. Verify the intended effects and data-model constraints for baseColor, roughness, metalness, transmission, ior, absorptionColor, and absorptionDensity without changes to scientific geometry. Check face and edge readability during rotation and zoom, and record visual review results alongside automated parameter-mapping checks.

Add an appearance demo whose controls expose the supported appearance fields with their current values. Provide the documented quartz, fluorite, and pyrite reference selections and keep controls synchronized when the selected appearance changes.

Verify that selected appearance and user overrides survive state restoration under the serialization contract, completing the appearance acceptance check scheduled in M7.


Completed Post-V1 Additions

These additions extend the completed product without changing the authoritative V1 checklist or the acceptance status of M1–M8.

A1 — CIF-Derived Morphology

Status: complete.

Add a renderer-neutral generateCrystalFromFaces path for explicit Miller planes and positive perpendicular distances. Extend CIF import to preserve the standard _exptl_crystal_face_index_h/k/l, _exptl_crystal_face_perp_dist, optional name, and optional description fields. The viewer exposes loadCifMorphology, renders measured faces without adding symmetry equivalents, and provides a dedicated CIF morphology demo.

When a valid structural CIF has no measured face loop, the demo uses a simplified BFDH-style fallback: enumerate primitive Miller triplets within [-2, 2], calculate interplanar spacing from the reciprocal lattice, use relative inverse spacing as the central-distance/growth-rate proxy, and expand by the resolved point symmetry. Emit viewer.morphology.bfdh-fallback so hosts cannot mistake the theoretical fallback for reported morphology. This implementation does not yet apply Donnay–Harker systematic absence corrections from screw axes or glide planes and is not a habit prediction.

Acceptance evidence:

  • measured CIF face rows and metadata survive import;
  • invalid indices or distances produce typed core diagnostics;
  • explicit faces pass directly to half-space intersection and must enclose a bounded non-degenerate volume;
  • absence of measured faces is visibly reported as a theoretical fallback; and
  • atomic structure and morphology remain separate viewer modes.

A2 — HDR Environment and Orientation Controls

Status: complete.

Add local Radiance .hdr and OpenEXR .exr environment loading with transactional PMREM replacement and disposal. The reference demo limits encoded uploads to 128 MB; the viewer rejects decoded panoramas above 32 megapixels. Add environment intensity, yaw/pitch/roll, AgX and ACES Filmic tone mapping, exposure, background visibility, and background-only zoom. Use a separate background render pass so zoom does not alter image-based lighting, crystal framing, or picking.

Expand model interaction to X/Y pointer rotation and host-owned keyboard control of X/Y/Z rotation. Preserve all three model angles through the existing camera-state contract. Uploaded environment bytes and renderer presentation controls remain session-only and are not serialized.

Acceptance evidence:

  • invalid formats, dimensions, rotations, exposure, intensity, and zoom are rejected through typed viewer diagnostics;
  • replacing, resetting, and disposing environments release owned GPU resources;
  • environment and model rotations remain independent; and
  • the original M5 demo remains runnable while the HDRI variant demonstrates the additions through the public viewer boundary.

Later Milestones

M9 — Twinning

Implement twin transforms independently of normal morphology generation.

Test with one quartz twin law first.


M10 — Pressure / Temperature

Only after basic crystallography is stable.

Implement:

temperature-dependent cell dimensions
pressure-dependent cell dimensions
phase stability
phase changes

Use minerals with good experimental data.


Recommended First Implementation Target

Build one minimal vertical slice through the full stack (see Crystal Geometry Engine for the generation pipeline):

Cubic mineral data (fluorite)
    ↓
CrystalGeometry
    ↓
Three.js BufferGeometry
    ↓
plain HTML canvas viewer
    ↓
morphology sliders

Deliver this vertical slice as the first plain-HTML milestone demo, including synchronized form-development sliders and geometry status. This validates the entire architecture end-to-end with the simplest crystal system before expanding to trigonal (quartz) and the remaining systems.


Definition of Successful V1

Version 1 succeeds when the authoritative V1 checklist is satisfied and the acceptance criteria for M1–M8 are met. M9–M10 are later work.

Before release, verify the shipped mineral and habit counts against that checklist, with every counted habit meeting the completion requirements. Separately verify all crystal-system fixtures below. Test-only fixtures do not count toward shipped mineral coverage.

Mineral and Crystal-System Coverage

The following delivery assignments use the recommended initial minerals. Habit coverage in each row must meet the count in the V1 checklist.

Shipped mineral Record and habit delivery Acceptance evidence
Fluorite M2 Completed habit presets and valid-geometry checks
Quartz M3 Completed habit presets and valid-geometry checks
Calcite M5 Completed habit presets and valid-geometry checks
Pyrite M5 Completed habit presets and valid-geometry checks
Anatase M5 Completed habit presets and valid-geometry checks

At each assigned milestone, record the mineral and habit IDs and link their records, references, and validation results. These checks establish record and habit coverage; later milestones still deliver their structural, API, and appearance capabilities.

Verify each shipped mineral and habit against the provenance contract, beginning with the representation established in M2 and applying it throughout M3–M5. Scientific data added by later milestones must also meet that contract.

Open decision — deferred to each assigned milestone: Select the exact named habits after checking sources and whether the morphology model can represent them. Apply the asymmetry decision from M3 habit selection and revisit it if a new habit introduces a dependency. Habits that depend on unresolved asymmetry cannot be accepted until that behavior is defined and implemented; later twinning support is not a dependency for completing this matrix.

Engine coverage is tracked separately:

Crystal system Fixture delivery milestone Fixture selection
Cubic M1–M2 Cubic prototype and fluorite reference cases
Trigonal M3 and M5 Quartz reference cases in the hexagonal setting, plus one paired hexagonal/rhombohedral-setting fixture
Tetragonal M5 Reference fixture selected during M5
Hexagonal M5 Reference fixture selected during M5
Orthorhombic M5 Reference fixture selected during M5
Monoclinic M5 Reference fixture selected during M5
Triclinic M5 Reference fixture selected during M5

Open decision — deferred to M5: Select the remaining reference fixtures. For every row, link the fixture, its sources, and expected results before accepting its delivery milestone.

For the paired trigonal-setting fixture, prefer calcite and document the explicit basis transformation. Acceptance requires matching Cartesian plane directions and the expected unit-cell and geometry relationships after conversion; merely generating a mesh in both settings is insufficient.

Validate lattice relationships, symmetry-equivalent plane directions, and bounded geometry for selected enclosing forms against the reference results, following symmetry resolution and geometry validation. Include non-orthogonal cells and the relevant symmetry operations. Successful mesh generation alone is insufficient evidence of crystal-system coverage.

Fixtures may reuse shipped mineral records or use separate test data. They do not need shipped habit or appearance presets unless they also count toward the content delivery matrix.


Priority Order

The development milestones define the implementation order; see the milestone sections above.

Do not implement advanced visual features before the generic crystallographic generator is validated.

Post-V1 surface work is sequenced in the surface-rendering implementation plan. The possible AI-assisted source-ingestion system remains a separate, non-binding automation draft and is not a dependency of the viewer plan.