feat: stage 2 real CAD conveyor, hybrid physics drops, mobile policy (WIP)
- CAD pipeline: conveer.FCStd -> FreeCAD headless -> conveyor-web.glb (555KB Draco, 42 named nodes) integrated into main scene; gates and rollers animated from domain state - Domain-driven adapter sorterVisualState.ts; per-SKU visual physics profiles (VISUAL_PHYSICS_ESTIMATE) - Hybrid Rapier physics: kinematic belt travel -> dynamic drop handoff -> verified freeze; shared collider layout (physicsWorldLayout) used by runtime and headless validation sim (physicsDropSim + 13 tests) - Gravity chutes / open roll-cage front redesign (drop tuning in progress: 4/7 routes verified headless) - Premium industrial visual: PBR, ACES, PCFSoft shadows, Lightformer env, UI cleanup behind ?debug=1 - Mobile capability policy: SVG fallback / Mobile Low / full tiers, Telegram WebView forced to SVG, e2e stubs for weak devices - Performance benchmarks cad-light/physics/full pass; stage2 artifacts tsc clean. Physics drop validation for 3 SKU routes still in progress. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
155
tools/stage2-cad/assemble-glb.py
Normal file
155
tools/stage2-cad/assemble-glb.py
Normal file
@@ -0,0 +1,155 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Assemble conveyor GLBs from FreeCAD-exported meshes.
|
||||
|
||||
Pipeline: manifest+STL (CAD-global mm, Z-up) -> mechanism grouping ->
|
||||
dedupe (translation-invariant) -> decimation budget -> material slots ->
|
||||
axis bake (-x, z, y+250)/1000 (proper rotation, det=+1) -> GLB.
|
||||
|
||||
Outputs:
|
||||
public/models/sorter/conveyor-source.glb (full 0.25mm tessellation)
|
||||
public/models/sorter/conveyor-web.glb (optimized, <=250k tris target)
|
||||
tools/stage2-cad/out/glb-stats.json
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import trimesh
|
||||
|
||||
OUT = "/home/coder/arhipovdan/app/tools/stage2-cad/out"
|
||||
DEST = "/home/coder/arhipovdan/app/public/models/sorter"
|
||||
os.makedirs(DEST, exist_ok=True)
|
||||
|
||||
with open(os.path.join(OUT, "manifest.json"), encoding="utf-8") as fh:
|
||||
manifest = json.load(fh)
|
||||
|
||||
# --- mechanism grouping (documented in docs/stage2_real_sorter/mechanism-map.md) ---
|
||||
def group_of(entry):
|
||||
label = entry["label"]
|
||||
name = entry["name"]
|
||||
if "Лента" in label:
|
||||
return "conveyor-belt"
|
||||
if "Барьер" in label:
|
||||
return "stop-gate"
|
||||
if "Крепление камеры" in label or "камера" in label or "Крепление камеры" in label:
|
||||
return "inspection-frame"
|
||||
if "Серво" in label or "серво" in label or "Держатель" in label:
|
||||
return "pusher-servo"
|
||||
if "Роликовый узел" in label:
|
||||
return "rollers"
|
||||
if "Ролик" in label or "Вал" in label or "Подшибник" in label:
|
||||
return "rollers"
|
||||
if "NEMA" in label or "Шкив" in label or "ремень" in label or "двигател" in label:
|
||||
return "motor-and-drive"
|
||||
if "Кронштейн" in label and name in ("Body009", "Link"):
|
||||
return "rollers" # roller support bracket (roller assembly child)
|
||||
return "static-frame"
|
||||
|
||||
MATERIAL_SLOT = {
|
||||
"static-frame": "painted-metal",
|
||||
"conveyor-belt": "rubber-belt",
|
||||
"rollers": "brushed-metal",
|
||||
"motor-and-drive": "dark-mechanical",
|
||||
"inspection-frame": "painted-metal",
|
||||
"stop-gate": "safety-yellow",
|
||||
"pusher-servo": "dark-mechanical",
|
||||
}
|
||||
|
||||
# Per-group decimation target for the web GLB (triangles per UNIQUE mesh).
|
||||
DECIMATE_TARGET = {
|
||||
"conveyor-belt": 1200,
|
||||
"rollers": 9000,
|
||||
"motor-and-drive": 4000,
|
||||
"static-frame": 2500,
|
||||
"stop-gate": 7000,
|
||||
"pusher-servo": 9000,
|
||||
"inspection-frame": 12000,
|
||||
}
|
||||
|
||||
|
||||
def bake(mesh):
|
||||
"""CAD mm Z-up -> GLB meters Y-up. (x,y,z) -> (-x, z, y+250)/1000, det=+1."""
|
||||
v = mesh.vertices
|
||||
x = -v[:, 0] / 1000.0
|
||||
y = v[:, 2] / 1000.0
|
||||
z = (v[:, 1] + 250.0) / 1000.0
|
||||
out = trimesh.Trimesh(vertices=np.column_stack([x, y, z]), faces=mesh.faces.copy(), process=False)
|
||||
out.fix_normals()
|
||||
return out
|
||||
|
||||
|
||||
def dedupe_key(mesh):
|
||||
"""Translation-invariant key: rounded vertices relative to bbox min + face count."""
|
||||
rel = mesh.vertices - mesh.vertices.min(axis=0)
|
||||
return (len(mesh.faces), hash(np.round(rel, 5).tobytes()))
|
||||
|
||||
|
||||
def decimate(mesh, target):
|
||||
if len(mesh.faces) <= target:
|
||||
return mesh
|
||||
try:
|
||||
import fast_simplification
|
||||
pts = np.asarray(mesh.vertices, dtype=np.float32)
|
||||
fcs = np.asarray(mesh.faces, dtype=np.int64)
|
||||
r_pts, r_fcs = fast_simplification.simplify(pts, fcs, target_reduction=1.0 - target / len(mesh.faces))
|
||||
out = trimesh.Trimesh(vertices=r_pts, faces=r_fcs, process=False)
|
||||
out.fix_normals()
|
||||
return out
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f" decimation failed ({exc}); keeping {len(mesh.faces)} tris")
|
||||
return mesh
|
||||
|
||||
|
||||
def build(decimating, label):
|
||||
scene = trimesh.Scene()
|
||||
cache = {}
|
||||
stats = []
|
||||
for entry in manifest:
|
||||
grp = group_of(entry)
|
||||
mesh = trimesh.load(os.path.join(OUT, entry["stl"]), process=False)
|
||||
mesh = bake(mesh)
|
||||
before = len(mesh.faces)
|
||||
key = dedupe_key(mesh)
|
||||
if key in cache:
|
||||
geom_name, offset = cache[key]
|
||||
node_transform = np.eye(4)
|
||||
node_transform[:3, 3] = mesh.vertices.min(axis=0) - offset
|
||||
stats.append({"node": f"{grp}/{entry['label']}", "group": grp, "tris": 0, "instanced": True})
|
||||
scene.add_geometry(
|
||||
scene.geometry[geom_name],
|
||||
node_name=f"{grp}/{entry['label']}",
|
||||
geom_name=geom_name,
|
||||
transform=node_transform,
|
||||
)
|
||||
continue
|
||||
if decimating:
|
||||
mesh = decimate(mesh, DECIMATE_TARGET.get(grp, 4000))
|
||||
geom_name = f"g_{grp}_{entry['name']}"
|
||||
cache[key] = (geom_name, mesh.vertices.min(axis=0))
|
||||
mesh.metadata["material_slot"] = MATERIAL_SLOT.get(grp, "painted-metal")
|
||||
scene.add_geometry(mesh, node_name=f"{grp}/{entry['label']}", geom_name=geom_name)
|
||||
stats.append({
|
||||
"node": f"{grp}/{entry['label']}",
|
||||
"group": grp,
|
||||
"tris": len(mesh.faces),
|
||||
"trisBeforeDecimation": before,
|
||||
"instanced": False,
|
||||
"materialSlot": MATERIAL_SLOT.get(grp),
|
||||
"cadSource": entry["stl"],
|
||||
})
|
||||
path = os.path.join(DEST, f"conveyor-{label}.glb")
|
||||
scene.export(path)
|
||||
total = sum(s["tris"] for s in stats if not s["instanced"])
|
||||
print(f"{label}: nodes={len(stats)} unique-tris={total} file={os.path.getsize(path)} bytes")
|
||||
return path, stats, total
|
||||
|
||||
|
||||
src_path, src_stats, src_tris = build(decimating=False, label="source")
|
||||
web_path, web_stats, web_tris = build(decimating=True, label="web")
|
||||
|
||||
with open(os.path.join(OUT, "glb-stats.json"), "w", encoding="utf-8") as fh:
|
||||
json.dump({
|
||||
"source": {"path": src_path, "uniqueTriangles": src_tris, "bytes": os.path.getsize(src_path), "nodes": src_stats},
|
||||
"web": {"path": web_path, "uniqueTriangles": web_tris, "bytes": os.path.getsize(web_path), "nodes": web_stats},
|
||||
}, fh, ensure_ascii=False, indent=1)
|
||||
print("done")
|
||||
116
tools/stage2-cad/freecad-export.py
Normal file
116
tools/stage2-cad/freecad-export.py
Normal file
@@ -0,0 +1,116 @@
|
||||
# FreeCAD 1.0.2 headless export macro — conveer.FCStd -> per-object STL + manifest JSON.
|
||||
# Run: /tmp/squashfs-root/usr/bin/freecadcmd tools/stage2-cad/freecad-export.py
|
||||
#
|
||||
# Toolchain: FreeCAD 1.0.2 (official AppImage, github.com/FreeCAD/FreeCAD releases).
|
||||
# The document is opened by FreeCAD itself, so App::Link / group semantics and
|
||||
# global placements are resolved by the CAD kernel, not by reimplemented logic.
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
|
||||
import FreeCAD
|
||||
import Mesh
|
||||
import Part
|
||||
|
||||
DOC_PATH = "/home/coder/arhipovdan/app/3d_models/conveer.FCStd"
|
||||
OUT_DIR = "/home/coder/arhipovdan/app/tools/stage2-cad/out"
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
|
||||
doc = FreeCAD.openDocument(DOC_PATH)
|
||||
|
||||
inventory = []
|
||||
renderables = []
|
||||
|
||||
for obj in doc.Objects:
|
||||
entry = {
|
||||
"name": obj.Name,
|
||||
"label": obj.Label,
|
||||
"typeId": obj.TypeId,
|
||||
"visibility": getattr(obj, "Visibility", None),
|
||||
"hasShape": hasattr(obj, "Shape"),
|
||||
}
|
||||
if hasattr(obj, "Shape"):
|
||||
try:
|
||||
bb = obj.Shape.BoundBox
|
||||
entry["shapeBboxMm"] = [bb.XMin, bb.YMin, bb.ZMin, bb.XMax, bb.YMax, bb.ZMax]
|
||||
entry["shapeIsNull"] = obj.Shape.isNull()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
entry["shapeError"] = str(exc)
|
||||
if obj.TypeId == "App::Link":
|
||||
try:
|
||||
linked = obj.LinkedObject
|
||||
entry["linkedObject"] = getattr(linked, "Name", str(linked))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
entry["linkedObject"] = f"ERROR:{exc}"
|
||||
inventory.append(entry)
|
||||
|
||||
# Renderable set = what the viewport shows: visible top-level geometry objects.
|
||||
# PartDesign inner features (Pad/Pocket/Fillet/...) are not rendered separately —
|
||||
# only their Body tip is. Groups and origins carry no geometry.
|
||||
RENDERABLE_TYPES = {"PartDesign::Body", "App::Link", "Part::Feature"}
|
||||
for obj in doc.Objects:
|
||||
if obj.TypeId not in RENDERABLE_TYPES:
|
||||
continue
|
||||
if not getattr(obj, "Visibility", False):
|
||||
continue
|
||||
if not hasattr(obj, "Shape"):
|
||||
continue
|
||||
try:
|
||||
shape = obj.Shape
|
||||
if shape.isNull():
|
||||
continue
|
||||
bb = shape.BoundBox
|
||||
if bb.XLength == 0 and bb.YLength == 0 and bb.ZLength == 0:
|
||||
continue
|
||||
except Exception:
|
||||
continue
|
||||
renderables.append(obj)
|
||||
|
||||
print(f"objects={len(inventory)} renderables={len(renderables)}")
|
||||
|
||||
manifest = []
|
||||
for obj in renderables:
|
||||
shape = obj.Shape
|
||||
# Verified on this document (probe.py): obj.Shape is already in
|
||||
# document-global coordinates for both PartDesign::Body and App::Link —
|
||||
# placement is baked into the stored shape and must NOT be re-applied.
|
||||
# Tessellate as-is; no additional transform.
|
||||
try:
|
||||
verts, facets = shape.tessellate(0.25) # 0.25 mm linear deflection
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f"SKIP tessellate failed: {obj.Name}: {exc}")
|
||||
continue
|
||||
if not facets:
|
||||
continue
|
||||
stl_name = f"{obj.Name}.stl"
|
||||
stl_path = os.path.join(OUT_DIR, stl_name)
|
||||
# binary STL, normals left zero (recomputed downstream)
|
||||
with open(stl_path, "wb") as fh:
|
||||
fh.write(b"\0" * 80)
|
||||
fh.write(struct.pack("<I", len(facets)))
|
||||
for tri in facets:
|
||||
fh.write(struct.pack("<3f", 0.0, 0.0, 0.0))
|
||||
for idx in tri:
|
||||
v = verts[idx]
|
||||
fh.write(struct.pack("<3f", float(v.x), float(v.y), float(v.z)))
|
||||
fh.write(struct.pack("<H", 0))
|
||||
bb = shape.BoundBox
|
||||
manifest.append({
|
||||
"name": obj.Name,
|
||||
"label": obj.Label,
|
||||
"typeId": obj.TypeId,
|
||||
"stl": stl_name,
|
||||
"triangles": len(facets),
|
||||
"globalBboxMm": [bb.XMin, bb.YMin, bb.ZMin, bb.XMax, bb.YMax, bb.ZMax],
|
||||
"linkedObject": next((e.get("linkedObject") for e in inventory if e["name"] == obj.Name), None),
|
||||
})
|
||||
safe_label = obj.Label.encode("ascii", "replace").decode("ascii")
|
||||
print(f" {obj.Name:14s} {safe_label[:28]:28.28s} tris={len(facets):6d} bbox=({bb.XMin:.0f},{bb.YMin:.0f},{bb.ZMin:.0f})..({bb.XMax:.0f},{bb.YMax:.0f},{bb.ZMax:.0f})")
|
||||
|
||||
with open(os.path.join(OUT_DIR, "manifest.json"), "w", encoding="utf-8") as fh:
|
||||
json.dump(manifest, fh, ensure_ascii=False, indent=1)
|
||||
with open(os.path.join(OUT_DIR, "fcstd-inventory.json"), "w", encoding="utf-8") as fh:
|
||||
json.dump(inventory, fh, ensure_ascii=False, indent=1)
|
||||
print(f"exported {len(manifest)} meshes -> {OUT_DIR}")
|
||||
FreeCAD.closeDocument(doc.Name)
|
||||
49
tools/stage2-cad/probe.py
Normal file
49
tools/stage2-cad/probe.py
Normal file
@@ -0,0 +1,49 @@
|
||||
# Probe FreeCAD semantics for links/placements on conveer.FCStd
|
||||
import FreeCAD
|
||||
|
||||
doc = FreeCAD.openDocument("/home/coder/arhipovdan/app/3d_models/conveer.FCStd")
|
||||
|
||||
def bb(s):
|
||||
b = s.BoundBox
|
||||
return f"({b.XMin:.0f},{b.YMin:.0f},{b.ZMin:.0f})..({b.XMax:.0f},{b.YMax:.0f},{b.ZMax:.0f})"
|
||||
|
||||
def pmt(p):
|
||||
return f"pos=({p.Base.x:.0f},{p.Base.y:.0f},{p.Base.z:.0f}) axis=({p.Rotation.Axis.x:.2f},{p.Rotation.Axis.y:.2f},{p.Rotation.Axis.z:.2f}) angle={p.Rotation.Angle:.3f}"
|
||||
|
||||
names = ["Body002", "Body003", "Body010", "Body018", "Body019", "Link005", "Link007", "Link016", "Link025", "Link027", "Link028", "Link000", "Link"]
|
||||
for n in names:
|
||||
o = doc.getObject(n)
|
||||
if o is None:
|
||||
print(n, "MISSING")
|
||||
continue
|
||||
print(f"== {n} type={o.TypeId} label={o.Label.encode('ascii','replace').decode()}")
|
||||
print(" placement:", pmt(o.Placement) if hasattr(o, "Placement") else "n/a")
|
||||
if hasattr(o, "getGlobalPlacement"):
|
||||
try:
|
||||
print(" global:", pmt(o.getGlobalPlacement()))
|
||||
except Exception as e:
|
||||
print(" global ERROR:", e)
|
||||
else:
|
||||
print(" global: NO METHOD")
|
||||
try:
|
||||
print(" shape bbox:", bb(o.Shape))
|
||||
except Exception as e:
|
||||
print(" shape ERROR:", e)
|
||||
if o.TypeId == "App::Link":
|
||||
try:
|
||||
lo = o.LinkedObject
|
||||
print(" linked:", lo.Name, lo.TypeId, lo.Label.encode('ascii','replace').decode())
|
||||
if hasattr(lo, "Shape"):
|
||||
print(" linked shape bbox:", bb(lo.Shape))
|
||||
if hasattr(lo, "Placement"):
|
||||
print(" linked placement:", pmt(lo.Placement))
|
||||
if lo.TypeId == "App::DocumentObjectGroup":
|
||||
for ch in lo.Group:
|
||||
print(f" child {ch.Name} {ch.TypeId} place={pmt(ch.Placement) if hasattr(ch,'Placement') else 'n/a'} bbox={bb(ch.Shape) if hasattr(ch,'Shape') else 'n/a'}")
|
||||
except Exception as e:
|
||||
print(" linked ERROR:", e)
|
||||
# group membership: which group contains this object
|
||||
for g in doc.Objects:
|
||||
if g.TypeId == "App::DocumentObjectGroup" and hasattr(g, "Group") and o in g.Group:
|
||||
print(" member of group:", g.Name, g.Label.encode('ascii','replace').decode())
|
||||
FreeCAD.closeDocument(doc.Name)
|
||||
Reference in New Issue
Block a user