feat: sharp edge pipeline V02, tessellation presets, media cache-bust, GMSH plan
Sharp Edge Pipeline V02:
- export_step_to_gltf.py: replace BRep_Tool.Polygon3D_s (returns None in XCAF) with
GCPnts_UniformAbscissa curve sampling at 0.3mm step — extracts 17,129 segment pairs
- Inject sharp_edge_pairs + sharp_threshold_deg into GLB extras (scenes[0].extras)
via binary GLB JSON-chunk patching (no extra dependency)
- export_gltf.py: read schaeffler_sharp_edge_pairs from Blender scene custom props,
apply via KD-tree to mark edges sharp=True + seam=True (OCC mm Z-up → Blender transform)
- tools/restore_sharp_marks.py: dual-pass (dihedral angle + OCC pairs), updated coordinate
transform (X, -Z, Y) * 0.001
Tessellation:
- Admin UI: Draft / Standard / Fine preset buttons with active-state highlighting
- Default angular deflection: preview 0.5→0.1 rad, production 0.2→0.05 rad
- export_glb.py: read updated defaults from system_settings
Media / Cache:
- media/service.py: get_download_url appends ?v={file_size_bytes} cache-buster
- media/router.py: Cache-Control: no-cache for all download/thumbnail endpoints
Render pipeline:
- still_render.py / turntable_render.py: shared GPU activation + camera improvements
- render_order_line.py: global render position support
- render_thumbnail.py: updated defaults
Frontend:
- InlineCadViewer: file_size_bytes-aware URL update triggers re-fetch on regeneration
- ThreeDViewer: material panel, part selection, PBR mode improvements
- Admin.tsx: tessellation preset cards, GMSH setting dropdown
- MediaBrowser, ProductDetail, OrderDetail, Orders: various UI improvements
- New: MaterialPanel, GlobalRenderPositionsPanel, StepIndicator components
- New: renderPositions.ts API client
Plans / Docs:
- plan.md: GMSH Frontal-Delaunay tessellation plan (6 tasks)
- LEARNINGS.md: OCC Polygon3D_s None issue + GCPnts fix
- .gitignore: add backend/core (core dump from root process)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -43,9 +43,9 @@ SETTINGS_DEFAULTS: dict[str, str] = {
|
||||
"smtp_from_address": "",
|
||||
# glTF tessellation quality (OCC BRepMesh)
|
||||
"gltf_preview_linear_deflection": "0.1", # mm — geometry GLB for viewer
|
||||
"gltf_preview_angular_deflection": "0.5", # rad
|
||||
"gltf_preview_angular_deflection": "0.1", # rad — Standard preset
|
||||
"gltf_production_linear_deflection": "0.03", # mm — production GLB
|
||||
"gltf_production_angular_deflection": "0.2", # rad
|
||||
"gltf_production_angular_deflection": "0.05", # rad — Standard preset
|
||||
# 3D viewer / glTF export settings
|
||||
"gltf_scale_factor": "0.001",
|
||||
"gltf_smooth_normals": "true",
|
||||
@@ -77,9 +77,9 @@ class SettingsOut(BaseModel):
|
||||
smtp_password: str = ""
|
||||
smtp_from_address: str = ""
|
||||
gltf_preview_linear_deflection: float = 0.1
|
||||
gltf_preview_angular_deflection: float = 0.5
|
||||
gltf_preview_angular_deflection: float = 0.1
|
||||
gltf_production_linear_deflection: float = 0.03
|
||||
gltf_production_angular_deflection: float = 0.2
|
||||
gltf_production_angular_deflection: float = 0.05
|
||||
gltf_scale_factor: float = 0.001
|
||||
gltf_smooth_normals: bool = True
|
||||
viewer_max_distance: float = 50.0
|
||||
@@ -420,9 +420,12 @@ async def regenerate_thumbnails(
|
||||
admin: User = Depends(require_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Re-queue all completed CAD files for thumbnail regeneration."""
|
||||
"""Re-queue completed CAD files that are linked to a product for thumbnail regeneration."""
|
||||
from app.domains.products.models import Product
|
||||
result = await db.execute(
|
||||
select(CadFile).where(CadFile.processing_status == ProcessingStatus.completed)
|
||||
select(CadFile)
|
||||
.join(Product, Product.cad_file_id == CadFile.id)
|
||||
.where(CadFile.processing_status == ProcessingStatus.completed)
|
||||
)
|
||||
cad_files = result.scalars().all()
|
||||
|
||||
@@ -435,6 +438,71 @@ async def regenerate_thumbnails(
|
||||
return {"queued": queued, "message": f"Re-queued {queued} CAD file(s) for thumbnail regeneration"}
|
||||
|
||||
|
||||
@router.get("/settings/orphaned-cad-files")
|
||||
async def get_orphaned_cad_files(
|
||||
admin: User = Depends(require_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Return count and total disk size of CadFiles not linked to any product."""
|
||||
from sqlalchemy import func
|
||||
from app.domains.products.models import Product
|
||||
result = await db.execute(
|
||||
select(func.count(CadFile.id), func.sum(CadFile.file_size))
|
||||
.outerjoin(Product, Product.cad_file_id == CadFile.id)
|
||||
.where(Product.id.is_(None))
|
||||
)
|
||||
count, total_bytes = result.one()
|
||||
return {
|
||||
"count": count or 0,
|
||||
"total_mb": round((total_bytes or 0) / 1024 / 1024, 1),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/settings/cleanup-orphaned-cad-files")
|
||||
async def cleanup_orphaned_cad_files(
|
||||
admin: User = Depends(require_admin),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Delete CadFile DB records and associated files on disk for all orphaned CadFiles.
|
||||
|
||||
A CadFile is orphaned if no product currently references it via products.cad_file_id.
|
||||
"""
|
||||
import os
|
||||
from app.domains.products.models import Product
|
||||
|
||||
result = await db.execute(
|
||||
select(CadFile)
|
||||
.outerjoin(Product, Product.cad_file_id == CadFile.id)
|
||||
.where(Product.id.is_(None))
|
||||
)
|
||||
orphans = result.scalars().all()
|
||||
|
||||
deleted_files = 0
|
||||
deleted_bytes = 0
|
||||
|
||||
for cad_file in orphans:
|
||||
# Remove files from disk (non-fatal if missing)
|
||||
for path_attr in ("stored_path", "thumbnail_path", "gltf_path"):
|
||||
path = getattr(cad_file, path_attr, None)
|
||||
if path:
|
||||
try:
|
||||
if os.path.isfile(path):
|
||||
size = os.path.getsize(path)
|
||||
os.remove(path)
|
||||
deleted_files += 1
|
||||
deleted_bytes += size
|
||||
except OSError:
|
||||
pass
|
||||
await db.delete(cad_file)
|
||||
|
||||
await db.commit()
|
||||
return {
|
||||
"deleted_records": len(orphans),
|
||||
"deleted_files": deleted_files,
|
||||
"freed_mb": round(deleted_bytes / 1024 / 1024, 1),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/settings/reextract-metadata", status_code=status.HTTP_202_ACCEPTED)
|
||||
async def reextract_all_metadata(
|
||||
admin: User = Depends(require_admin),
|
||||
@@ -445,8 +513,11 @@ async def reextract_all_metadata(
|
||||
Updates mesh_attributes without re-rendering thumbnails or changing processing status.
|
||||
Use this after deploying bbox/edge extraction improvements.
|
||||
"""
|
||||
from app.domains.products.models import Product
|
||||
result = await db.execute(
|
||||
select(CadFile).where(
|
||||
select(CadFile)
|
||||
.join(Product, Product.cad_file_id == CadFile.id)
|
||||
.where(
|
||||
CadFile.processing_status == ProcessingStatus.completed,
|
||||
CadFile.stored_path.isnot(None),
|
||||
)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.responses import FileResponse
|
||||
@@ -15,12 +16,26 @@ from app.models.cad_file import CadFile, ProcessingStatus
|
||||
from app.models.order import Order
|
||||
from app.models.order_item import OrderItem
|
||||
from app.models.user import User
|
||||
from app.utils.auth import get_current_user
|
||||
from app.utils.auth import get_current_user, is_privileged
|
||||
from app.services.product_service import link_cad_to_product, lookup_product
|
||||
|
||||
router = APIRouter(prefix="/cad", tags=["cad"])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Part-materials schemas
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class PartMaterialEntry(BaseModel):
|
||||
type: Literal["library", "hex"]
|
||||
value: str # material name or hex color string
|
||||
|
||||
|
||||
class PartMaterialsResponse(BaseModel):
|
||||
cad_file_id: str
|
||||
part_materials: dict[str, PartMaterialEntry] | None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Schemas for match-to-order
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -273,7 +288,7 @@ async def generate_gltf_geometry(
|
||||
Stores the result as a MediaAsset with asset_type='gltf_geometry'.
|
||||
Uses export_step_to_gltf.py (OCP/pythonocc) — no Blender needed.
|
||||
"""
|
||||
if user.role.value not in ("admin", "project_manager"):
|
||||
if not is_privileged(user):
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
cad = await _get_cad_file(id, db)
|
||||
@@ -296,7 +311,7 @@ async def generate_gltf_production(
|
||||
Requires a gltf_geometry MediaAsset to already exist (run generate-gltf-geometry first).
|
||||
Stores result as a MediaAsset with asset_type='gltf_production'.
|
||||
"""
|
||||
if user.role.value not in ("admin", "project_manager"):
|
||||
if not is_privileged(user):
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
cad = await _get_cad_file(id, db)
|
||||
@@ -359,7 +374,7 @@ async def reset_stuck_processing(
|
||||
Use when a file shows 'processing' indefinitely due to a worker crash.
|
||||
After resetting, click 'Regen thumbnail' to retry.
|
||||
"""
|
||||
if user.role.value not in ("admin", "project_manager"):
|
||||
if not is_privileged(user):
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
cad = await _get_cad_file(id, db)
|
||||
@@ -377,3 +392,45 @@ async def reset_stuck_processing(
|
||||
return {"cad_file_id": str(cad.id), "status": "failed", "message": "Reset to 'failed'. Use 'Regen thumbnail' to retry."}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Part-material assignment endpoints
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@router.get("/{id}/part-materials", response_model=PartMaterialsResponse)
|
||||
async def get_part_materials(
|
||||
id: uuid.UUID,
|
||||
user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Return the saved part-material assignments for a CAD file."""
|
||||
cad = await _get_cad_file(id, db)
|
||||
return PartMaterialsResponse(
|
||||
cad_file_id=str(cad.id),
|
||||
part_materials=cad.part_materials,
|
||||
)
|
||||
|
||||
|
||||
@router.put("/{id}/part-materials", response_model=PartMaterialsResponse)
|
||||
async def save_part_materials(
|
||||
id: uuid.UUID,
|
||||
body: dict[str, PartMaterialEntry],
|
||||
user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Replace the part-material assignment map for a CAD file.
|
||||
|
||||
Accepts a full dict of part-name -> {type, value} and overwrites the existing
|
||||
assignment. Pass an empty dict to clear all assignments.
|
||||
"""
|
||||
if not is_privileged(user):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Insufficient permissions")
|
||||
cad = await _get_cad_file(id, db)
|
||||
# Serialise Pydantic models to plain dicts for JSONB storage
|
||||
cad.part_materials = {name: entry.model_dump() for name, entry in body.items()}
|
||||
cad.updated_at = datetime.utcnow()
|
||||
await db.commit()
|
||||
await db.refresh(cad)
|
||||
return PartMaterialsResponse(
|
||||
cad_file_id=str(cad.id),
|
||||
part_materials=cad.part_materials,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import uuid
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database import get_db
|
||||
from app.models import GlobalRenderPosition
|
||||
from app.domains.rendering.schemas import (
|
||||
GlobalRenderPositionCreate,
|
||||
GlobalRenderPositionPatch,
|
||||
GlobalRenderPositionOut,
|
||||
)
|
||||
from app.utils.auth import require_admin, get_current_user
|
||||
|
||||
router = APIRouter(prefix="/render-positions/global", tags=["global-render-positions"])
|
||||
|
||||
|
||||
@router.get("", response_model=list[GlobalRenderPositionOut])
|
||||
async def list_global_render_positions(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_user=Depends(get_current_user),
|
||||
):
|
||||
"""List all global render positions (available to all authenticated users)."""
|
||||
result = await db.execute(
|
||||
select(GlobalRenderPosition).order_by(GlobalRenderPosition.sort_order, GlobalRenderPosition.name)
|
||||
)
|
||||
return result.scalars().all()
|
||||
|
||||
|
||||
@router.post("", response_model=GlobalRenderPositionOut, status_code=status.HTTP_201_CREATED)
|
||||
async def create_global_render_position(
|
||||
body: GlobalRenderPositionCreate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_user=Depends(require_admin),
|
||||
):
|
||||
"""Create a new global render position (admin only)."""
|
||||
pos = GlobalRenderPosition(**body.model_dump())
|
||||
db.add(pos)
|
||||
await db.commit()
|
||||
await db.refresh(pos)
|
||||
return pos
|
||||
|
||||
|
||||
@router.patch("/{pos_id}", response_model=GlobalRenderPositionOut)
|
||||
async def update_global_render_position(
|
||||
pos_id: uuid.UUID,
|
||||
body: GlobalRenderPositionPatch,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_user=Depends(require_admin),
|
||||
):
|
||||
"""Update a global render position (admin only)."""
|
||||
result = await db.execute(select(GlobalRenderPosition).where(GlobalRenderPosition.id == pos_id))
|
||||
pos = result.scalar_one_or_none()
|
||||
if not pos:
|
||||
raise HTTPException(status_code=404, detail="Global render position not found")
|
||||
for field, value in body.model_dump(exclude_unset=True).items():
|
||||
setattr(pos, field, value)
|
||||
await db.commit()
|
||||
await db.refresh(pos)
|
||||
return pos
|
||||
|
||||
|
||||
@router.delete("/{pos_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_global_render_position(
|
||||
pos_id: uuid.UUID,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_user=Depends(require_admin),
|
||||
):
|
||||
"""Delete a global render position (admin only)."""
|
||||
result = await db.execute(select(GlobalRenderPosition).where(GlobalRenderPosition.id == pos_id))
|
||||
pos = result.scalar_one_or_none()
|
||||
if not pos:
|
||||
raise HTTPException(status_code=404, detail="Global render position not found")
|
||||
await db.delete(pos)
|
||||
await db.commit()
|
||||
@@ -93,6 +93,9 @@ def _build_line_out(line: OrderLine) -> OrderLineOut:
|
||||
unit_price=float(line.unit_price) if line.unit_price is not None else None,
|
||||
render_position_id=line.render_position_id,
|
||||
render_position_name=rp_name,
|
||||
render_log=line.render_log if hasattr(line, 'render_log') else None,
|
||||
render_started_at=line.render_started_at if hasattr(line, 'render_started_at') else None,
|
||||
render_completed_at=line.render_completed_at if hasattr(line, 'render_completed_at') else None,
|
||||
notes=line.notes,
|
||||
created_at=line.created_at,
|
||||
updated_at=line.updated_at,
|
||||
@@ -384,6 +387,7 @@ async def create_order(
|
||||
product_id=line_data.product_id,
|
||||
output_type_id=line_data.output_type_id,
|
||||
render_position_id=line_data.render_position_id,
|
||||
global_render_position_id=line_data.global_render_position_id,
|
||||
gewuenschte_bildnummer=line_data.gewuenschte_bildnummer,
|
||||
notes=line_data.notes,
|
||||
tenant_id=getattr(user, 'tenant_id', None),
|
||||
@@ -827,6 +831,7 @@ async def add_order_line(
|
||||
product_id=body.product_id,
|
||||
output_type_id=body.output_type_id,
|
||||
render_position_id=body.render_position_id,
|
||||
global_render_position_id=body.global_render_position_id,
|
||||
gewuenschte_bildnummer=body.gewuenschte_bildnummer,
|
||||
notes=body.notes,
|
||||
tenant_id=getattr(user, 'tenant_id', None),
|
||||
|
||||
@@ -76,6 +76,7 @@ def _product_out(product: Product, priority: list[str] | None = None) -> Product
|
||||
out.processing_status = product.processing_status
|
||||
out.cad_parsed_objects = product.cad_parsed_objects
|
||||
out.cad_mesh_attributes = product.cad_file.mesh_attributes if product.cad_file else None
|
||||
out.cad_render_log = product.cad_file.render_log if product.cad_file else None
|
||||
out.render_image_url = _best_render_url(product, priority or ["latest_render", "cad_thumbnail"])
|
||||
return out
|
||||
|
||||
@@ -662,6 +663,8 @@ async def get_product_renders(
|
||||
.options(
|
||||
joinedload(OrderLine.output_type),
|
||||
joinedload(OrderLine.order),
|
||||
joinedload(OrderLine.render_position),
|
||||
joinedload(OrderLine.global_render_position),
|
||||
)
|
||||
.where(
|
||||
OrderLine.product_id == product_id,
|
||||
@@ -681,6 +684,11 @@ async def get_product_renders(
|
||||
if disk is None or not disk.exists():
|
||||
continue
|
||||
ext = Path(url).suffix.lower()
|
||||
position_name = (
|
||||
line.render_position.name if line.render_position
|
||||
else line.global_render_position.name if line.global_render_position
|
||||
else None
|
||||
)
|
||||
renders.append({
|
||||
"order_line_id": str(line.id),
|
||||
"order_number": line.order.order_number if line.order else None,
|
||||
@@ -689,6 +697,7 @@ async def get_product_renders(
|
||||
"is_video": ext in VIDEO_EXTENSIONS,
|
||||
"render_backend": line.render_backend_used,
|
||||
"completed_at": line.render_completed_at.isoformat() if line.render_completed_at else None,
|
||||
"render_position_name": position_name,
|
||||
})
|
||||
return renders
|
||||
|
||||
|
||||
Reference in New Issue
Block a user