Skip to content

feat!: 3.0 vis cutover — properties.pbr removed, .vis canonical, mat-vis-client 0.4.x - #52

Merged
gerchowl merged 55 commits into
mainfrom
feature/40-vis-cutover
Apr 18, 2026
Merged

gerchowl merged 55 commits into
mainfrom
feature/40-vis-cutover

Conversation

@gerchowl

@gerchowl gerchowl commented Apr 18, 2026 •

Copy link
Copy Markdown
Contributor

Description

py-materials 3.0 — the vis cutover. Consolidates all PBR state under material.vis, removes material.properties.pbr / PBRProperties / the pbr= kwarg / the [<material>.pbr] TOML section with no deprecation cycle, and raises the mat-vis-client floor to >=0.4.0.

Full migration story in docs/migration/v2-to-v3.md. Rationale for skipping 2.3 deprecation-only in #40.

Type of Change

  • feat! — Breaking change (major version bump 2.1.1 → 3.0.0)

Required

  • Tests pass locally (uv run pytest — 241 passed, 18 skipped on 3.13; visual-regression skipped due to no playwright)
  • Self-reviewed the diff
  • No new warnings or errors in the changed code
  • Linked to an issue in the Refs: line at the bottom

If Applicable

Documentation

  • Updated CHANGELOG.md under ## Unreleased (release-please will rename to ## [3.0.0] on the Release PR)
  • docs/migration/v2-to-v3.md covers the full rename table, TOML renames, texture-map migration, and the mat-vis-client upgrade (including the one-time mat-vis-client cache clear for warm 0.2.x caches)

Dependencies

  • Updated pyproject.toml and re-locked (uv lock) — mat-vis-client>=0.4.0, resolved to 0.4.0
  • Verified no breakage with downstream consumers — tests pass; migration doc coordinates with build123d / ocp_vscode / threejs-materials

Breaking Change

  • Migration notes added to docs/migration/v2-to-v3.md
  • feat!: subject on the driving commit (8921c83) — release-please will compute the major bump from this

Additional Notes

Downstream coordination status (partial, tracked externally — intentionally not gating this PR):

  • build123d Shape.material integration path: Bernhard's gumyr/build123d#1270 is the canonical route; our gumyr/build123d#1276 closes. Tracked in #3.
  • ocp_vscode visualiser: accepts duck-typed to_threejs() adapter output.
  • mat-vis-client crates.io Rust counterpart: gated via vars.CRATES_IO_PUBLISH_ENABLED (#43).
  • JS/TS consumer decision: deferred (#42).

What release-please will do on merge:

  1. See the feat!: commit and other feat:/fix: commits since v2.1.1
  2. Open chore(main): release 3.0.0 Release PR bumping pyproject.toml + src/pymat/__init__.py to 3.0.0 and rewriting the ## Unreleased section
  3. Release PR may regenerate the curated Breaking/Added/Changed sections from commit subjects — expect to edit the Release PR's CHANGELOG before merging to preserve the rich handwritten content
  4. Merge Release PR → tag v3.0.0 → release.yml → PyPI publish via OIDC

Refs: #40

gerchowl and others added 30 commits April 15, 2026 15:38
The README was written before 2.1.0 shipped and was stale in several
places. This refresh brings it current with what's actually on PyPI
today.

## Template changes (docs/README_TEMPLATE.md)

- **Installation**: PyPI (`pip install py-materials`) is now the
  recommended path. Git+https is documented as secondary for the
  main-branch dev build. The `[periodictable]`, `[build123d]`, and
  `[all]` optional extras are all mentioned with their install lines.
- **Features list** — added:
  - Formula parsing + molar mass (with Python ↔ Rust parity note)
  - Explicit Python 3.10–3.13 support statement
  - Pure-element density only note on `periodictable` integration
    (the "compound density" promise was always broken; see #9)
- **Repo URLs fixed**: `MorePet/py-mat` / `MorePET/py-mat` →
  `MorePET/mat` (the repo was renamed but the template never
  caught up).
- **Links section** now includes PyPI and the rs-materials crates.io
  page alongside the GitHub / Issues links.
- **Enrichment example** rewritten to match current behavior: pure
  elements get density from `periodictable`, compounds only get
  `composition` populated. Molar mass works for both via the
  computed `Material.molar_mass` property. Previous example promised
  `print(material.density)  # ~3.95 g/cm³` for Al2O3 which never
  worked — the bug fixed in #9.
- **New "Design Decisions (ADRs)" section** linking
  `docs/decisions/0001-derived-chemistry-properties-live-on-material.md`,
  so contributors can find the rationale behind `Material.molar_mass`
  being a computed property.

## Test additions (tests/test_readme_examples.py)

Two new methods in `TestBasicUsage`, so they show up in the README's
Quick Start section AND stay verified by CI:

- `test_molar_mass_from_formula` — shows `Material.molar_mass` on a
  pure element, simple compound, fractional-stoichiometry compound
  (LYSO), dopant-suffix stripping (LYSO:Ce), the Pint-wrapped
  `molar_mass_qty`, and the `None` fallback when no formula is set.
- `test_elements_low_level_api` — shows the `pymat.elements` module
  direct API (`ATOMIC_WEIGHT`, `parse_formula`, `compute_molar_mass`)
  for Monte Carlo transport callers who want stoichiometry without
  wrapping in a full `Material`. Notes the line-for-line Rust
  rs-materials parity.

## Generator fixes (scripts/generate_readme.py)

Two pre-existing bugs surfaced while regenerating:

1. **Code block indentation was broken** — the generator extracted
   test function bodies but never dedented. Every code block in the
   generated README had an 8-space indent on every line except the
   first (the `from pymat import ...` line, extracted from a
   different regex branch, started at column 0 while the rest of the
   body started at column 8). Result: uncopy-pasteable examples.
   Fixed via `textwrap.dedent()` on both docstring and code extracts.

2. **Assertions were stripped wholesale** — the previous
   `re.sub(r"\s*assert .*?\n", "", code)` removed all `assert` lines
   to make examples "cleaner", but it removed exactly the lines
   that show the reader the expected return values. After the fix,
   readers see e.g. `assert iron.molar_mass == 55.85` alongside the
   computation instead of having to guess. `pytest.importorskip`
   calls still get filtered because those ARE noise in a user-
   facing example.

## README.md

Regenerated. 580 lines, 19 examples, code blocks now dedented and
assertion-bearing.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
New package pymat.vis with:

- vis.__init__: public API re-exports (search, fetch, rowmap_entry,
  get_manifest). Usage: `from pymat import vis; vis.search(...)`
- vis._client: stub implementations for the mat-vis fetch layer.
  Pure Python, stdlib-only. Raises NotImplementedError until
  mat-vis publishes first release (M4/M5).
- vis._model: Vis dataclass (source_id, finishes, textures,
  resolve()) + ResolvedChannel. Vis.from_toml() parses the
  [vis] section from material TOML files.
- vis.adapters: standalone to_threejs(), to_gltf(), export_mtlx()
  functions. Take Material, read from both .properties.pbr and
  .vis namespaces. Stub implementations.

API design rationale: Material.vis holds pointers + cached textures.
Fetching/search lives in pymat.vis (module-level functions).
Adapters are functions, not methods — consumers can write their
own without changing pymat. See #35.
- _MaterialInternal gets ._vis field + .vis property (always returns
  Vis instance, never None — lazy-constructed on first access)
- loader.py parses [vis] sections from TOML, populates via Vis.from_toml()
- "vis" added to skip-list so it's not treated as a child material
- Added [vis] section to stainless in metals.toml as proof-of-concept:
  default="brushed", finishes={brushed, polished}

Usage:
  stainless.vis.source_id    # "ambientcg/Metal032"
  stainless.vis.finish       # "brushed"
  stainless.vis.finishes     # {"brushed": "...", "polished": "..."}
  stainless.vis.finish = "polished"  # switches source_id

Custom materials get empty Vis (source_id=None, textures={}).
Textures lazy-fetch via vis._client on first access (not yet
implemented — raises NotImplementedError until mat-vis publishes).

All 109 existing tests pass.
Covers: Vis construction (empty, from_toml with/without default),
finish switching (source_id update, cache clear, unknown raises),
textures access (empty when no source_id, NotImplementedError
when source_id set but client unimplemented), ResolvedChannel
(texture available, scalar fallback, neither), Material.vis
wiring (custom material empty, settable, same instance, TOML
populated, child without vis), module-level API stubs.

128 passed, 26 skipped.
Replaces NotImplementedError stubs with working implementation:

- get_manifest(): returns release tag + base URL
- search(): loads JSON indexes, filters by category/source, ranks
  by roughness/metalness distance
- fetch(): rowmap lookup → HTTP Range request → PNG bytes + cache
- rowmap_entry(): raw offset/length for DIY consumers

Pure Python, stdlib-only (urllib.request). ~250 lines.
Tested against live mat-vis v0.1.0 release data:
  vis.fetch("ambientcg", "Wood049") → 2 channels, 6.3 MB, 2.2s
  cache hit → 0.002s

Also updated tests: mock fetch instead of expecting
NotImplementedError, added search mock test, rowmap miss test.
130 passed, 26 skipped.
Three output adapters, all standalone functions taking Material:

- to_threejs(material) → MeshPhysicalMaterial dict with base64
  data URIs for textures. Maps metallic→metalness, base_color→
  color hex int. Includes ior/transmission/clearcoat/emissive
  when non-default.

- to_gltf(material) → glTF pbrMetallicRoughness dict. Includes
  KHR_materials_transmission extension when transmission > 0.
  Note: does NOT pack metalness+roughness into single texture
  (would need Pillow — left for a dedicated exporter).

- export_mtlx(material, path) → writes .mtlx XML + PNG files.
  Standard Surface node graph with image references as siblings.

Field name mapping per docs/specs/field-name-mapping.md.
130 passed, 26 skipped.
Per mat#34 discussion:
- periodictable moved from [periodictable] extra to core deps
  (~800 KB, used for molar mass + element lookups)
- Removed extras: [periodictable], [matproj], [build123d], [all]
  - matproj → curation-time tool only (mat#36)
  - build123d → reversed dep direction (they depend on us)
  - uncertainties → will become core in a follow-up (mat#33)
- Only [dev] extra remains (pytest, build123d for integration tests)

pip install mat → pint + periodictable + tomli. ~2 MB.
Vis.discover(category, roughness, metallic):
  - Searches mat-vis index for matching appearances
  - Returns ranked candidates, does NOT auto-set source_id
  - Pass auto_set=True to pick top match
  - Uses vis.search() under the hood

scripts/enrich_vis.py:
  - Runs vis.search() against all unmapped TOML materials
  - Outputs proposed [vis] sections as TOML
  - Designed to run in CI via enrich-vis.yml workflow
  - Opens PR for human review of proposed mappings
  - Tested against live mat-vis v0.1.0: 120 proposals generated

3 new tests for discover (candidates, auto_set, empty results).
133 passed, 26 skipped.
Downloads all materials for a (source × tier) into the local cache.
Skips already-cached materials, logs progress every 10 materials.

Usage:
    from pymat import vis
    vis.prefetch("ambientcg", tier="1k")  # downloads all ~50 materials
    # subsequent vis.fetch() calls are instant from cache

Closes the last ADR-0004 compliance gap.
133 passed, 26 skipped.
Migration per mat#37:
- Vendored mat_vis_client.py + adapters.py from mat-vis v2026.04.0
  release assets into _vendor_client.py and _vendor_adapters.py
- _client.py reduced to thin wrapper (~110 lines) delegating to
  vendored MatVisClient class
- adapters.py reduced to thin wrappers (~75 lines) that extract
  scalars + textures from Material and pass to vendored generic
  adapters (scalars dict, textures dict — no Material dependency)
- Index seeding workaround: downloads index JSONs from release
  assets since they're not in git yet (mat-vis#40)
- fetch() gracefully returns {} on errors instead of crashing
- Tests updated to mock vendored client, not internal functions

Blocked on full functionality by mat-vis#40 (missing ambientcg
index + partitioned rowmap handling in vendored client).

133 passed, 26 skipped.
…s mapping

- Re-downloaded mat_vis_client.py from v2026.04.0 — now handles
  category-partitioned rowmaps (merges per-category rowmaps into one)
- Fixed metallic→metalness field name mapping in adapters wrapper
  (py-mat uses "metallic", mat-vis uses "metalness")
- Closes mat-vis#40 on our side

Verified end-to-end: Material → vis.fetch → 4 PNG channels →
to_threejs → MeshPhysicalMaterial with all texture maps.
133 passed, 26 skipped.
scripts/generate_catalog.py:
- Iterates all TOML-registered materials (95 across 7 categories)
- Generates docs/catalog/ tree: root index → category pages →
  per-material detail pages
- Each page has: identity, mechanical, thermal, PBR, composition,
  vis source/finishes
- Category index: table with material, density, roughness, metallic
- Optional thumbnails: fetches color texture from mat-vis, resizes
  to 128x128 via Pillow
- --skip-thumbnails for text-only (CI without mat-vis access)

Designed for CI: .github/workflows/catalog.yml runs on push to
dev, commits generated docs to a gh-pages branch or PR.

133 passed, 26 skipped.
CONTRIBUTING.md:
- Three paths: request a material, add a material (TOML template),
  fix a value
- Data quality guidelines (cite sources, SI units, don't fabricate)
- Vis mapping guide (vis.search → TOML [vis] section)
- Standard PR workflow (fork, branch from dev, test, lint)

Issue templates:
- material-request.yml: name, category, known properties, use case,
  datasheet URL, desired appearance
- material-correction.yml: material, property, current/correct value,
  source citation
- Installation section simplified (no stale extras)
- Added Material Catalog section linking to docs/catalog/
- Added Contributing section with issue template links
- Added mat-vis link to Links section
- Added [mat-vis] reference link
mat-vis now hosts pre-baked thumbnail tiers (128/256/512). The
catalog script fetches color textures at the 128px tier directly
instead of downloading 1K textures and resizing with Pillow.

Simpler, faster, no Pillow dependency for catalog generation.
Reverted attempt to merge pbr.*_map fields into adapters.
Per our design: all visual data lives under .vis. Legacy
pbr.*_map fields (normal_map, roughness_map, etc.) continue
to work via ocp_vscode's existing is_pymat path — that's
Bernhard's migration to handle when adopting the adapter
pattern. We don't bridge legacy into the new API.

Deprecation of pbr.*_map → .vis migration tracked for 2.3.0.
…operties.pbr

Migration path toward 3.0 (mat#40):
- Vis dataclass gains PBR scalar fields (roughness, metallic,
  base_color, ior, transmission, clearcoat, emissive)
- Vis.from_toml() parses scalars from [vis] section
- Loader syncs vis scalars → properties.pbr for backward compat
  (ocp_vscode's is_pymat path still reads properties.pbr)
- Adapters read vis scalars first, fall back to properties.pbr
- stainless TOML migrated: [pbr] → [vis] as proof-of-concept

Both [pbr] and [vis] TOML sections accepted. vis wins when both
present. No breakage — single migration path to 3.0.

133 passed, 26 skipped.
Delete 890 lines of vendored code, import from mat-vis-client:

Deleted:
  _vendor_client.py   (444 lines — was mat-vis's client.py)
  _vendor_adapters.py (280 lines — was mat-vis's adapters.py)
  _client.py          (166 lines — our wrapper around vendored)

Remaining pymat/vis/ (354 lines):
  __init__.py  (32)  — re-exports from mat_vis_client
  _model.py    (230) — Vis, ResolvedChannel, from_toml, discover
  adapters.py  (92)  — Material→dict wrappers

Dependencies:
  mat-vis-client>=2026.4.0 added to core deps
  (currently installed from git, PyPI publish pending)

Test mocks updated: pymat.vis._client → mat_vis_client.
133 passed, 26 skipped.

Refs: mat#37, mat-vis#36, mat-vis#50
- uncertainties>=3.2 added to core dependencies (~59 KB, pure Python)
- Loader accepts composition values as:
  - plain float: 0.68
  - {nominal, stddev}: {nominal = 0.4, stddev = 0.1} → ufloat
  - {min, max}: {min = 0.2, max = 0.6} → ufloat(midpoint, half-range)
  - {nominal, min, max}: explicit nominal + range
- Aluminum 6063 added with grade-spec composition ranges as
  proof-of-concept (Si, Mg, Fe have ranges; Al is balance)
- Existing plain-float compositions unchanged
- test_loader: handle ufloat in composition sum check
- 14 new tests for parsing, propagation, material integration
- 147 passed, 26 skipped

Closes #33.
- docs/catalog/ generated with 96 materials across 7 categories
  (thumbnails via CI when mat-vis tiers available)
- .github/workflows/catalog.yml — regenerates on TOML data changes
- .github/workflows/enrich-vis.yml — auto-proposes vis mappings
  on mat-vis release dispatch
- vis.search() no longer filters by tier (index available_tiers
  may not reflect all actual tiers — search is for discovery, tier
  is a fetch-time concern)
- Fixed ufloat sorting in catalog composition tables

147 passed, 26 skipped.

Closes #38, #39.
Tests for _extract_scalars (pbr fallback, vis-wins, metallic→metalness
mapping), _extract_textures, to_threejs (scalar + texture modes),
to_gltf, export_mtlx (with/without textures).

Overall coverage: 81% (158 passed, 26 skipped).
Every [material.pbr] section across 7 data files renamed to
[material.vis]. Zero [pbr] sections remain. Values unchanged.

The loader already routes [vis] scalars to both .vis and
properties.pbr (backward compat sync), so all existing tests
pass without code changes.

128 materials load. 170 tests pass.

Part of 3.0.0 migration (#40).
core.py:
  - color=(r,g,b) → sets vis.base_color (was properties.pbr)
  - pbr={} kwarg → writes to .vis AND properties.pbr (dual-write)
  - Optical→PBR derivations (ior, transmission) target .vis
  - _sync_vis_to_pbr() keeps properties.pbr populated for
    ocp_vscode backward compat

vis/_model.py:
  - Vis.get(field, default) with _PBR_DEFAULTS dict
  - Resolves None→default for adapters

vis/adapters.py:
  - _extract_scalars reads only from .vis via get() with defaults
  - No more pbr fallback — vis is the single source

170 passed, 25 skipped.

Part of 3.0.0 migration (#40).
- loader.py: TOML [pbr] section emits DeprecationWarning, still
  parsed for backward compat
- loader.py: vis→pbr sync moved to _sync_vis_to_pbr() in core.py
- core.py: Material(pbr={...}) emits DeprecationWarning, still
  works (writes to both vis and properties.pbr)

170 passed (with DeprecationWarning suppressed), 25 skipped.

Part of 3.0.0 (#40).
- test_adapters: _make_material sets vis fields directly instead
  of pbr={} kwarg
- pyproject.toml: filterwarnings suppresses DeprecationWarning
  for tests that still use pbr={} kwarg (legacy API, deprecated
  but functional)
- Also suppresses uncertainties FutureWarning

170 passed, 25 skipped.
test_e2e_vis.py (7 tests, skip with MAT_VIS_SKIP_LIVE=1):
  - Search and fetch real textures from mat-vis
  - Material.vis.textures lazy fetch
  - to_threejs with live texture data URIs
  - TOML material with vis mapping (stainless finishes)
  - discover (via vis.search, tier-free)
  - Multi-material fetch (light prefetch test)
  - resolve() with texture and scalar fallback

test_catalog.py (8 tests):
  - Root index, category dirs, material pages
  - Vis section, composition, uncertainty rendering
  - Category index table format
  - Total page count (>90)

178 passed (excl e2e), 25 skipped.
- MatVisClient, seed_indexes now re-exported
- vis.adapters module exposed — new adapters (to_ktx2, etc.)
  available automatically when mat-vis-client updates
- vis.MatVisClient().tiers() / .sources() for discovery
- No code changes needed in mat when mat-vis adds new tiers,
  sources, or adapters

178 passed, 25 skipped.
vis.client() returns the shared MatVisClient singleton. Any new
methods mat-vis-client adds (tiers, sources, search, fetch,
new formats) are immediately accessible without pymat changes:

    c = vis.client()
    c.tiers()        # ['128', '1k', '256', '512', '2k']
    c.sources()      # ['ambientcg', 'gpuopen', 'polyhaven']
    c.search("metal")
    c.fetch_all_textures("ambientcg", "Metal032", tier="ktx2")  # when available

178 passed, 25 skipped.
Tests verify the full pipeline:
  pymat.Material → vis.textures → to_threejs → ocp_vscode → screenshot

Skipped by default (MAT_VIS_SKIP_VISUAL=1). Requires:
  build123d, ocp_vscode, playwright + chromium

Three test levels:
1. Material adapter output (JSON dict validation)
2. Material with mat-vis textures (data URI verification)
3. Headless screenshot via ocp_vscode standalone + Playwright
   (placeholder — full wiring TBD)

Visual baselines stored in tests/visual_baselines/.
gerchowl added 16 commits April 18, 2026 11:55
First cross-checker from the #36 survey: queries Wikidata SPARQL for
density + melting point of the 7 base metals and prints a side-by-side
report flagging divergences >5%.

Wikidata is CC0 with no auth — suitable for curation-time cross-checks.
This is NOT a runtime dep of mat; it lives under scripts/ and pulls in
only \`requests\` via the new scripts/requirements-curation.txt.

First run flagged tungsten: Wikidata reports 7.2 g/cm³ (wrong; pure W
is 19.25), confirming the tool surfaces outlier values for review
rather than blindly trusting the source.

Addresses the "prototype one enrichment script" checkbox in #36.
The previous flat-key iteration produced three issues:
- Bare child keys like [oz1.vis.finishes] instead of the correct
  [copper_pcb.oz1.vis.finishes]
- Children of already-mapped bases proposed redundantly (s304 when
  stainless is already curated with brushed/polished/dirty)
- No distinction between a grade that needs its own finish vs. one
  that inherits visually from its parent

Walks the hierarchy top-down via Material._children instead, builds
dotted paths, and skips descendants once the base has a proposal.
Proposal count drops from 40 → 6, all of which are legitimately
unmapped base materials (tungsten, lead, plastic_scint, esr,
copper_pcb, solder).
Adds [x.vis.finishes] for the six materials enrich_vis flagged:
- tungsten: polished (Metal014) + raw (Metal030)
- lead: dull (Metal030) + oxidized (Metal031)
- copper_pcb: clean (Metal043A) + oxidized (Metal043B)
- solder: matte (Metal030) + reflowed (Metal031)
- esr: reflective (Plastic010) — scalars dominate; finish is catalog tag
- plastic_scint: clear (Plastic010) — translucent, scalars dominate

Running enrich_vis now reports "No unmapped materials found". Catalog
regenerates with 33 thumbnails, up from 27.
Expands the vis guidance to show tag-based search (vis.search with
tags=[...] produces much tighter matches than category-alone), the
correct [x.vis.finishes] table shape, and a "first finish is the
default" note.

Adds a Curation tools table covering the three scripts (enrich_vis,
enrich_from_wikidata, generate_catalog), a step-by-step curation
workflow, and a provenance convention: cite external sources inline
as a comment above the value (e.g. "# density: Wikidata Q663, CC0")
so the source survives TOML reformatting and stays local to the
claim.

Closes the "Document the curation workflow" checkbox in #36.
Adds 7 plastic polymer Q-IDs to the WIKIDATA_QIDS map: peek, pc, pmma,
ptfe, pla, nylon, delrin (the generic base polymers, not grades).

Wikidata coverage for polymers is patchy — only PC, PMMA, and PTFE
returned density in the first run, all agreeing within 3% of our
values. PEEK, PLA, nylon, and delrin had no Wikidata density, which
the report surfaces as "wd missing" rather than treating as a match.

The tungsten outlier (Wikidata reports 7.2 g/cm³) continues to flag
as DIFF — that's Wikidata's problem, not ours.
Captures the work since 2.1.0:
- Added: vis.search tags=[], vis.client() factory, 33 curated finishes,
  ceramics catalog coverage fix, Wikidata cross-check script, visual
  regression CI workflow, vis.__init__ at 100% coverage, 33 thumbnails.
- Changed: enrich_vis hierarchy-aware proposals, CONTRIBUTING.md
  curation workflow + provenance convention, loosened e2e vis test.

No version bump yet — next release planning will decide whether this
is 2.2.0 (feature expansion) or rolls into a larger 3.0 (PBR→vis).
Render a sphere (fluids) or cube (solids) per material with both a
light and a dark-themed backdrop, then embed the pair via GitHub's
native <picture> theme-swap in the catalog. 33 materials × 2 themes
= 66 PNGs at 512×512, ~3 min full regen.

Fixes along the way:
- pymat.vis.adapters._extract_scalars was emitting base_color as an
  RGBA array, but mat-vis-client's adapter only knows how to format
  color from color_hex (a '#RRGGBB' string). Added _rgba_to_hex so
  to_threejs() now actually carries the material color. Previously
  every material rendered as the Three.js default grey.
- material_preview.html awaits Image.onload for every texture before
  rendering. Without the await, 5+ MB normalMap data URIs weren't
  finished decoding at render time, so metals rendered without any
  surface detail.

Components:
- tests/material_preview.html — shape/theme/material URL params,
  RoomEnvironment baked PMREM for realistic reflections, theme-paired
  bg colors matching GitHub's canvas tokens.
- scripts/generate_previews.py — walks hierarchy, writes per-render
  material_N.json to defeat browser caching, supports --only and
  --changed-only (parses git diff to find touched TOML categories).
- scripts/generate_catalog.py — emits <picture> tags when both theme
  previews exist; falls back to flat thumbs otherwise.
- .github/workflows/catalog-previews.yml — three triggers: PR touching
  data/vis/rendering files (diff-only), workflow_dispatch (full or
  selection), release published (full regen, artifacts uploaded).
- scripts/requirements-curation.txt — adds playwright>=1.40. Kept out
  of pyproject.toml since it's curation tooling, not a library dep.

Local smoke test: 4 materials rendered in 8 distinct PNGs (md5-unique
per theme + material), 202 tests still pass.
test_adapters: 7 new cases covering _rgba_to_hex (the conversion
added in f3cf12d so to_threejs actually emits color) and the
_extract_scalars contract that base_color must not leak through
while color_hex must be populated. Hex conversion clamps out-of-
range PBR values and strips alpha.

CONTRIBUTING.md: documents the preview generation step of the
curation workflow and adds generate_previews.py to the curation
tools table.

.typos.toml: whitelists \`metalness\` (Three.js PBR field name) and
\`PNGs\` so pre-commit stops mangling them. The typos default
dictionary kept rewriting \`metalness\` to \`metallicity\` and
\`PNGs\` to \`ONGs\`, which silently corrupted docs + tests across
this session's commits.

generate_previews: replaced \`PNGs\` with \`images\` in the one log
line where typos couldn't be whitelisted through the config, to
avoid having to keep fighting the tool in prose contexts.
The 7 e2e tests hit live ambientcg through mat-vis release assets.
When the CDN returns 5xx — regional Akamai blips, rate-limits, the
genuine 502 we saw earlier today — the tests would go red and mask
real regressions.

Wraps each network call in _skip_on_upstream_outage():
- urllib HTTPError with 5xx → pytest.skip with the code in the reason
- AssertionError whose message matches the "no textures returned"
  shape mat-vis-client produces after a logged 5xx → same skip
- 4xx (real bug: bad source_id, auth, wrong path) propagates normally
- Other AssertionErrors propagate normally — only the specific flake
  shape gets skip-coerced

Adds 5 unit tests for the guard itself so we'll know if its behavior
drifts without waiting for a CDN outage to prove it.
Adds the gating deprecation pass for the 3.0 PBR→vis migration. Every
read of \`material.properties.pbr\` now emits a DeprecationWarning
telling the caller to switch to \`material.vis\` instead. Pre-existing
warnings on the TOML [pbr] section and the Material(pbr={...}) kwarg
are unchanged.

Implementation:
- AllProperties now stores PBR under the private field \`_pbr\`. The
  public \`pbr\` is a property that warns on every access and returns
  \`_pbr\`. Dataclass default_factory still fires at init time, so
  external constructors like AllProperties() keep working.
- All in-library callers (core.py sync, loader.py TOML routing, the
  factories, the catalog generator) reach into \`_pbr\` directly so
  we don't trip our own warning. External callers (user code, README
  examples, tests/test_readme_examples) exercise the public \`.pbr\`
  path and get the migration signal.
- Material.apply_to()'s build123d color-setting path now reads from
  \`self.vis.base_color\` (the 3.0 target) with fallback to the _pbr
  default when vis.base_color is None — children without their own
  vis mapping still get a sane color.

Next-cycle plan (issue #40): 3.0.0 deletes the \`pbr\` property, the
PBRProperties class, and the _pbr field entirely. This release is
the last minor where \`.properties.pbr\` works at all.
Skips the 2.3 deprecation-cycle release and cuts straight to 3.0.
Rationale + migration guide in docs/migration/v2-to-v3.md and
issue #40.

Removed
- PBRProperties class (properties.py)
- AllProperties.pbr field + the 8089c49 deprecation shim (_pbr rename)
- Material._sync_vis_to_pbr() back-compat shim
- Material(pbr={...}) kwarg (use Material(vis={...}) — same shape)
- [<material>.pbr] TOML section support — loader now raises ValueError
- Legacy *_map fields (normal_map, roughness_map, metallic_map,
  ambient_occlusion_map) — replaced by material.vis.textures[...]
- PBRProperties from pymat top-level imports

Changed
- Material.__init__ now accepts vis={...}, applied after parent init so
  values override the optical-derived defaults (ior/transmission).
- Material.apply_to()'s build123d color path reads from material.vis
  directly (no more _pbr fallback).
- Factory functions (water, air, saline) pass vis={...} to Material
  instead of mutating AllProperties.
- Tests (apply_to, integration, loader, readme_examples) migrated from
  .properties.pbr.* → .vis.* and pbr={...} → vis={...}.
- scripts/generate_readme.py regenerates README from the migrated tests;
  docs/README_TEMPLATE.md updated (PBR / Optical section reworded
  around material.vis, feature list updated).

Added
- docs/migration/v2-to-v3.md — complete rename cheat sheet, TOML
  format change, legacy-field replacements, AttributeError examples,
  rationale for skipping 2.3.
- CHANGELOG [3.0.0] breaking-changes section.

Version bumped from 2.1.0 → 3.0.0 (pyproject.toml + src/pymat/__init__.py).
214 tests pass.
Cleans up stale references missed in 8921c83:
- src/pymat/__init__.py __dir__() no longer advertises PBRProperties
- src/pymat/properties.py module docstring: point to docs/migration
  instead of referencing the deleted PBRProperties class
- src/pymat/vis/_model.py comments: drop the "in 3.0 properties.pbr
  will be removed" prose — it IS 3.0 now.

Adds scripts/generate_readme.py --check mode and a pre-commit hook
that enforces README.md == regenerate(test_readme_examples.py,
README_TEMPLATE.md). If a README example drifts from what the test
actually runs, the commit fails with a one-line fix instruction.

Implementation: refactors generate_readme.py into render_readme() +
check_readme() so pre-commit can reuse the renderer without touching
disk. The hook uses language: python (stdlib-only dependencies), so
the hook environment resolves cleanly even when the outer uv lock is
unhappy (mat-vis-client 3.14/win32 split — tracked separately).
mat-vis-client 0.2.0 dropped the module-level \`fetch\` in favor of the
explicit-client style (MatVisClient().fetch_all_textures(...)). py-mat
3.0 called \`from mat_vis_client import fetch\` in two places — both
fail on any mat-vis-client past 2026.4.1 (the last version that still
shipped module-level fetch).

Changes:
- pymat/vis/__init__.py: replace \`from mat_vis_client import fetch\`
  with a local \`fetch()\` wrapper that constructs a MatVisClient and
  calls fetch_all_textures. Keeps the public \`pymat.vis.fetch()\`
  signature unchanged for downstream consumers (scripts, tests,
  catalog generator).
- pymat/vis/_model.py Vis._fetch: import the wrapper from pymat.vis
  instead of mat_vis_client.
- pyproject.toml: bump pin from \`mat-vis-client>=2026.4.0\` (a yanked
  calendar version) to \`>=0.2.0\` (the current semver on local checkout).
- tests/test_vis.py: the monkeypatch target moves from
  \`mat_vis_client.fetch\` to \`pymat.vis.fetch\`.

Local builds + 214 tests still pass. Fresh wheel install into an
isolated venv:
    pip install dist/py_materials-3.0.0-py3-none-any.whl \\
        /Users/larsgerchow/Projects/mat-vis/clients/python
confirms the API surface works end-to-end (Material(vis={...}),
to_threejs emits color + metalness + roughness, \`pbr=\` correctly
rejected, PBRProperties import blocked).

Two publish blockers remain — both mat-vis-side:
1. \`mat-vis-client 0.2.0+\` must land on PyPI (the 2026.4.1 that's
   there is yanked; /simple/mat-vis-client/ returns an empty index).
2. mat-vis needs a data release whose manifest includes \`schema_version\`
   — the 0.2.0 client rejects older manifests with RuntimeError at
   first texture fetch.
Adds tests/test_toml_integrity.py (27 test cases) to catch data-drift
bugs that the handpicked per-material tests in test_loader.py would
miss:

- Every category in _CATEGORY_BASES has a parseable TOML with at
  least one material (parametrized over all 7 categories).
- Full-corpus load emits zero DeprecationWarning — canary for
  accidental reintroduction of deprecated surfaces (e.g. a [pbr]
  section sneaking back into a TOML).
- Every declared base key in _CATEGORY_BASES resolves to a real
  material (no orphans).
- Direct TOML-tree walks (via tomllib) check every file for:
    - Any [pbr] section (rejected in 3.0 — but catching it at the
      file level surfaces a clearer error than the loader ValueError)
    - Typo'd property groups — e.g. [material.mechnical] would
      silently be ignored by the loader; this test flags the typo
      as drift from _KNOWN_GROUPS.
- Every material invariant: non-empty name, density >= 0 (vacuum
  is 0.0), vis.finishes source_ids match `source/material_id`
  shape, PBR scalars in valid ranges.

241 tests pass (was 214). No TOMLs needed changes — current data
is already clean on every new check.
Upgrades the floor from 0.2.0 → 0.4.0 so every 3.0 install gets
the schema_version-aware manifest loader (required, since 0.3.0
dropped the legacy `version` fallback), the friendlier error
messages and 502/504 retries from 0.4.0, and the security hotfixes
from 0.3.1.

Adds a `mat-vis-client upgrade` section to the v2-to-v3 migration
doc covering the one user-visible operational detail:

    mat-vis-client cache clear

is a one-time step for users with a warm 0.2.x cache. Fresh
installs and CI environments are unaffected.

All 241 tests pass on 0.4.0 (18 skipped are playwright visual-
regression, unrelated).

Refs: #40
Brings in the release-please automated release pipeline (#44), the
pipeline self-fix (#46), and the 2.1.1 CI-infrastructure patch
release (#48) onto the vis cutover branch so 3.0 ships through the
new flow.

Conflict resolutions:
- pyproject.toml: kept `version = "3.0.0"` over main's 2.1.1
- src/pymat/__init__.py: kept 3.0.0 + kept main's
  `# x-release-please-version` marker comment
- CHANGELOG.md: renamed the pre-written `[3.0.0]` section to
  `Unreleased` (release-please will version it on Release PR),
  folded main's 2.1.1 entry in below, added mat-vis-client>=0.4.0
  bump + cache-clear note to the Breaking list

Refs: #40
@gerchowl
gerchowl enabled auto-merge (squash) April 18, 2026 17:52
Three fixes to land 3.0 (#52) cleanly through the new release-please
pipeline:

1. **Eliminate the mat-rs/data SSoT violation.** mat-rs/data/*.toml
   were independent copies of src/pymat/data/*.toml, embedded into
   the Rust crate via include_str!. They drifted on this branch
   (vis cutover added materials, [pbr] → [vis] rename) and the
   integration test `builtin_matches_file_loaded` started failing.
   Replace the seven copies with symlinks pointing at the canonical
   Python data. cargo publish bakes the resolved file content into
   the .crate tarball — no symlinks reach consumers — and local
   `cargo build` follows them transparently. mat-rs/data/README.md
   documents the layout and the publish-time semantics.

2. **Real lint fixes** (caught by pre-commit but never previously
   surfaced because the dev container was where pre-commit ran):
   - `import mat_vis_client` (line 20) and
     `from mat_vis_client import search as _upstream_search`
     (line 33) in src/pymat/vis/__init__.py were unused — removed.
   - `for field in cls._PBR_SCALAR_FIELDS:` shadowed the dataclass
     `field` import. Renamed to `fname`.
   - scripts/generate_previews.py: split a 110-char URL f-string
     across three lines.
   - Various ruff format auto-fixes across scripts/ and tests/.

3. **Configuration cleanup**:
   - `.typos.toml`: allow `mechnical` (deliberate misspelling in a
     test docstring used as the example of what
     test_toml_integrity.py catches).
   - `.github/workflows/{catalog,enrich-vis}.yml`: yamllint
     `disable-line rule:truthy` on the `on:` key (matches the
     convention in every other workflow in the repo).

Verified: `uv run pytest` 241 passed, 18 skipped (playwright);
`cargo test` all green; `uv tool run pre-commit run --all-files`
all hooks pass.

Refs: #40
@gerchowl
gerchowl merged commit 49b5dff into main Apr 18, 2026
18 checks passed
gerchowl added a commit that referenced this pull request Apr 18, 2026
Release-please's auto-generated [3.0.0] section was a single bullet
derived from the squashed commit subject (`3.0 vis cutover —
properties.pbr removed, .vis canonical, mat-vis-client 0.4.x`).
Replaces it with the curated Breaking / Added / Changed sections
that were already authored under `## Unreleased` in the merge of
PR #52, capturing the full migration story (PBR removal, mat-vis
0.4.x cache-clear, vis.search tags param, 33 vis finishes, etc.).

This commit lives on the release-please branch and ships with the
3.0.0 tag merge — release-please regenerates the branch on the next
push to main, so the rich CHANGELOG must be present when this PR
merges to land on main.

Refs: #40
gerchowl added a commit that referenced this pull request Apr 18, 2026
* chore(main): release 3.0.0

* docs(changelog): restore rich 3.0.0 content from Unreleased

Release-please's auto-generated [3.0.0] section was a single bullet
derived from the squashed commit subject (`3.0 vis cutover —
properties.pbr removed, .vis canonical, mat-vis-client 0.4.x`).
Replaces it with the curated Breaking / Added / Changed sections
that were already authored under `## Unreleased` in the merge of
PR #52, capturing the full migration story (PBR removal, mat-vis
0.4.x cache-clear, vis.search tags param, 33 vis finishes, etc.).

This commit lives on the release-please branch and ships with the
3.0.0 tag merge — release-please regenerates the branch on the next
push to main, so the rich CHANGELOG must be present when this PR
merges to land on main.

Refs: #40

---------

Co-authored-by: vig-os-release-app[bot] <263368078+vig-os-release-app[bot]@users.noreply.github.com>
Co-authored-by: gerchowl <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant