FEAT - BIM CONVERTER: поддержка IGES через Ops

This commit is contained in:
CODEX
2026-07-29 17:56:01 +03:00
parent 1a78dd0dc8
commit c102fa9929
6 changed files with 161 additions and 27 deletions
+41
View File
@@ -0,0 +1,41 @@
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
import worker
class CadFormatTests(unittest.TestCase):
def test_source_format_variants(self) -> None:
self.assertEqual(worker.source_format_for_path(Path("model.STEP")), "step")
self.assertEqual(worker.source_format_for_path(Path("model.stp")), "step")
self.assertEqual(worker.source_format_for_path(Path("model.IGES")), "iges")
self.assertEqual(worker.source_format_for_path(Path("model.igs")), "iges")
self.assertIsNone(worker.source_format_for_path(Path("model.glb")))
def test_process_one_dispatches_iges_converter(self) -> None:
with tempfile.TemporaryDirectory() as directory:
worker.UPLOADS_DIR = Path(directory).resolve()
source_path = worker.UPLOADS_DIR / "model.igs"
source_path.write_bytes(b"IGES")
metadata = {
"artifact": "uploads/model.xkt",
"artifactType": "xkt",
"componentCount": 1,
}
with (
patch.object(worker, "find_ready_conversion_with_same_hash", return_value=None),
patch.object(worker, "convert_iges_assets", return_value=metadata) as convert_iges,
):
self.assertTrue(worker.process_one(source_path))
convert_iges.assert_called_once()
manifest = worker.read_json(worker.manifest_path(source_path))
self.assertEqual(manifest["sourceFormat"], "iges")
self.assertEqual(manifest["status"], "ready")
if __name__ == "__main__":
unittest.main()
+82 -20
View File
@@ -13,6 +13,7 @@ from pathlib import Path
from typing import Any from typing import Any
from OCP.BRepMesh import BRepMesh_IncrementalMesh from OCP.BRepMesh import BRepMesh_IncrementalMesh
from OCP.IGESCAFControl import IGESCAFControl_Reader
from OCP.Message import Message_ProgressRange from OCP.Message import Message_ProgressRange
from OCP.RWGltf import RWGltf_CafWriter from OCP.RWGltf import RWGltf_CafWriter
from OCP.STEPCAFControl import STEPCAFControl_Reader from OCP.STEPCAFControl import STEPCAFControl_Reader
@@ -25,7 +26,7 @@ from OCP.XCAFDoc import XCAFDoc_DocumentTool, XCAFDoc_ShapeTool
CONVERTER_NAME = "NodeDcBimConverter" CONVERTER_NAME = "NodeDcBimConverter"
CONVERTER_VERSION = "0.4.9" CONVERTER_VERSION = "0.5.0"
UPLOADS_DIR = Path(os.environ.get("NODEDC_BIM_CONVERTER_UPLOADS_DIR", "/beam/uploads")).resolve() UPLOADS_DIR = Path(os.environ.get("NODEDC_BIM_CONVERTER_UPLOADS_DIR", "/beam/uploads")).resolve()
POLL_INTERVAL_SECONDS = float(os.environ.get("NODEDC_BIM_CONVERTER_INTERVAL_SECONDS", "10")) POLL_INTERVAL_SECONDS = float(os.environ.get("NODEDC_BIM_CONVERTER_INTERVAL_SECONDS", "10"))
PROCESS_ONCE = os.environ.get("NODEDC_BIM_CONVERTER_ONCE", "").lower() in {"1", "true", "yes"} PROCESS_ONCE = os.environ.get("NODEDC_BIM_CONVERTER_ONCE", "").lower() in {"1", "true", "yes"}
@@ -73,6 +74,11 @@ CADQUERY_TIMEOUT_SECONDS = float(
os.environ.get("NODEDC_BIM_CONVERTER_CADQUERY_TIMEOUT_SECONDS", str(CONVERSION_TIMEOUT_SECONDS)) os.environ.get("NODEDC_BIM_CONVERTER_CADQUERY_TIMEOUT_SECONDS", str(CONVERSION_TIMEOUT_SECONDS))
) )
STEP_EXTENSIONS = {".step", ".stp"} STEP_EXTENSIONS = {".step", ".stp"}
IGES_EXTENSIONS = {".iges", ".igs"}
CAD_SOURCE_FORMAT_BY_EXTENSION = {
**{extension: "step" for extension in STEP_EXTENSIONS},
**{extension: "iges" for extension in IGES_EXTENSIONS},
}
GLB_EXTENSIONS = {".glb"} GLB_EXTENSIONS = {".glb"}
GLB_LOD_PROFILES = [ GLB_LOD_PROFILES = [
{ {
@@ -351,6 +357,9 @@ def find_ready_conversion_with_same_hash(source_path: Path, manifest: dict[str,
sha256 = manifest.get("sha256") or calculate_file_sha256(source_path) sha256 = manifest.get("sha256") or calculate_file_sha256(source_path)
if not sha256: if not sha256:
return None return None
source_format = source_format_for_path(source_path)
if not source_format:
return None
version_id = manifest.get("versionId") version_id = manifest.get("versionId")
version_number = manifest.get("version") version_number = manifest.get("version")
source_manifest_path = manifest_path(source_path).resolve() source_manifest_path = manifest_path(source_path).resolve()
@@ -373,7 +382,7 @@ def find_ready_conversion_with_same_hash(source_path: Path, manifest: dict[str,
update_asset_manifest_version(candidate_source_path, candidate) update_asset_manifest_version(candidate_source_path, candidate)
if candidate_sha256 != sha256: if candidate_sha256 != sha256:
continue continue
if candidate.get("sourceFormat") != "step": if candidate.get("sourceFormat") != source_format:
continue continue
if candidate.get("artifactType") != "xkt" and candidate.get("targetFormat") != "xkt": if candidate.get("artifactType") != "xkt" and candidate.get("targetFormat") != "xkt":
continue continue
@@ -659,27 +668,43 @@ def gltf_component_tree(gltf_json: dict[str, Any], fallback_name: str) -> dict[s
} }
def convert_step_xcaf_to_glb(source_path: Path, glb_path: Path) -> tuple[dict[str, Any], dict[str, Any]]: def source_format_for_path(source_path: Path) -> str | None:
return CAD_SOURCE_FORMAT_BY_EXTENSION.get(source_path.suffix.lower())
def convert_cad_xcaf_to_glb(
source_path: Path,
glb_path: Path,
source_format: str,
) -> tuple[dict[str, Any], dict[str, Any]]:
app = XCAFApp_Application.GetApplication_s() app = XCAFApp_Application.GetApplication_s()
doc = TDocStd_Document(TCollection_ExtendedString("MDTV-XCAF")) doc = TDocStd_Document(TCollection_ExtendedString("MDTV-XCAF"))
app.NewDocument(TCollection_ExtendedString("MDTV-XCAF"), doc) app.NewDocument(TCollection_ExtendedString("MDTV-XCAF"), doc)
print(f"[{CONVERTER_NAME}] STEPCAF read {source_path.name}", flush=True) if source_format == "step":
reader = STEPCAFControl_Reader() reader = STEPCAFControl_Reader()
reader_name = "STEPCAF"
elif source_format == "iges":
reader = IGESCAFControl_Reader()
reader_name = "IGESCAF"
else:
raise ValueError(f"Unsupported CAD source format: {source_format}")
print(f"[{CONVERTER_NAME}] {reader_name} read {source_path.name}", flush=True)
reader.SetNameMode(True) reader.SetNameMode(True)
reader.SetColorMode(True) reader.SetColorMode(True)
reader.SetLayerMode(True) reader.SetLayerMode(True)
read_status = reader.ReadFile(str(source_path)) read_status = reader.ReadFile(str(source_path))
if "RetDone" not in str(read_status): if "RetDone" not in str(read_status):
raise ValueError(f"STEPCAF read failed: {read_status}") raise ValueError(f"{reader_name} read failed: {read_status}")
if not reader.Transfer(doc): if not reader.Transfer(doc):
raise ValueError("STEPCAF transfer failed.") raise ValueError(f"{reader_name} transfer failed.")
shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main()) shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())
labels = TDF_LabelSequence() labels = TDF_LabelSequence()
shape_tool.GetFreeShapes(labels) shape_tool.GetFreeShapes(labels)
if labels.Length() == 0: if labels.Length() == 0:
raise ValueError("STEPCAF document has no free shapes.") raise ValueError(f"{reader_name} document has no free shapes.")
print( print(
f"[{CONVERTER_NAME}] meshing {source_path.name}: " f"[{CONVERTER_NAME}] meshing {source_path.name}: "
@@ -710,6 +735,7 @@ def convert_step_xcaf_to_glb(source_path: Path, glb_path: Path) -> tuple[dict[st
gltf_json, renamed_nodes = normalize_glb_node_names(glb_path) gltf_json, renamed_nodes = normalize_glb_node_names(glb_path)
tree = gltf_component_tree(gltf_json, source_path.stem) tree = gltf_component_tree(gltf_json, source_path.stem)
stats = { stats = {
"sourceFormat": source_format,
"freeShapeCount": labels.Length(), "freeShapeCount": labels.Length(),
"gltfNodeCount": len(gltf_json.get("nodes", [])), "gltfNodeCount": len(gltf_json.get("nodes", [])),
"gltfMeshCount": len(gltf_json.get("meshes", [])), "gltfMeshCount": len(gltf_json.get("meshes", [])),
@@ -841,7 +867,7 @@ def convert_glb_to_xkt(glb_path: Path, xkt_path: Path) -> dict[str, Any]:
} }
def build_step_metadata( def build_cad_metadata(
source_path: Path, source_path: Path,
glb_path: Path, glb_path: Path,
xkt_path: Path, xkt_path: Path,
@@ -850,6 +876,7 @@ def build_step_metadata(
tree: dict[str, Any], tree: dict[str, Any],
stats: dict[str, Any], stats: dict[str, Any],
import_strategy: str, import_strategy: str,
source_format: str,
) -> dict[str, Any]: ) -> dict[str, Any]:
xkt_stats = convert_glb_to_xkt(glb_path, xkt_path) xkt_stats = convert_glb_to_xkt(glb_path, xkt_path)
has_xkt = bool(xkt_stats.get("enabled") and xkt_path.exists()) has_xkt = bool(xkt_stats.get("enabled") and xkt_path.exists())
@@ -862,7 +889,7 @@ def build_step_metadata(
"artifactType": preferred_artifact_type, "artifactType": preferred_artifact_type,
"glbArtifact": src_from_path(glb_path), "glbArtifact": src_from_path(glb_path),
"xktArtifact": src_from_path(xkt_path) if has_xkt else None, "xktArtifact": src_from_path(xkt_path) if has_xkt else None,
"format": "step", "format": source_format,
"targetFormat": "xkt" if has_xkt else "glb", "targetFormat": "xkt" if has_xkt else "glb",
"importStrategy": import_strategy, "importStrategy": import_strategy,
"componentTree": tree, "componentTree": tree,
@@ -881,9 +908,14 @@ def build_step_metadata(
return metadata return metadata
def convert_step_xcaf_to_glb_process(source_path: str, glb_path: str, result_path: str) -> None: def convert_cad_xcaf_to_glb_process(
source_path: str,
glb_path: str,
source_format: str,
result_path: str,
) -> None:
try: try:
tree, stats = convert_step_xcaf_to_glb(Path(source_path), Path(glb_path)) tree, stats = convert_cad_xcaf_to_glb(Path(source_path), Path(glb_path), source_format)
write_json_atomic(Path(result_path), {"ok": True, "tree": tree, "stats": stats}) write_json_atomic(Path(result_path), {"ok": True, "tree": tree, "stats": stats})
except Exception as exc: except Exception as exc:
write_json_atomic(Path(result_path), {"ok": False, "error": str(exc)}) write_json_atomic(Path(result_path), {"ok": False, "error": str(exc)})
@@ -960,7 +992,7 @@ def run_cadquery_stage_with_timeout(result_path: Path, source_path: Path, glb_pa
return result return result
def run_step_glb_stage_with_timeout( def run_cad_glb_stage_with_timeout(
stage_name: str, stage_name: str,
timeout_seconds: float, timeout_seconds: float,
target: Any, target: Any,
@@ -1031,7 +1063,7 @@ def convert_step_assets(source_path: Path, glb_path: Path, xkt_path: Path, metad
"renamedNodeCount": (previous_stats.get("renamedNodeCount") or 0) + renamed_nodes, "renamedNodeCount": (previous_stats.get("renamedNodeCount") or 0) + renamed_nodes,
"reusedExistingGlb": True, "reusedExistingGlb": True,
} }
return build_step_metadata( return build_cad_metadata(
source_path, source_path,
glb_path, glb_path,
xkt_path, xkt_path,
@@ -1039,18 +1071,20 @@ def convert_step_assets(source_path: Path, glb_path: Path, xkt_path: Path, metad
tree=previous_metadata["componentTree"], tree=previous_metadata["componentTree"],
stats=stats, stats=stats,
import_strategy=previous_metadata.get("importStrategy") or "existing-glb", import_strategy=previous_metadata.get("importStrategy") or "existing-glb",
source_format="step",
) )
import_strategy = "occt-xcaf-gltf" import_strategy = "occt-xcaf-gltf"
result_path = metadata_path.with_name(f"{metadata_path.name}.stage-result.json") result_path = metadata_path.with_name(f"{metadata_path.name}.stage-result.json")
try: try:
result = run_step_glb_stage_with_timeout( result = run_cad_glb_stage_with_timeout(
"OCCT/XCAF", "OCCT/XCAF",
XCAF_TIMEOUT_SECONDS, XCAF_TIMEOUT_SECONDS,
convert_step_xcaf_to_glb_process, convert_cad_xcaf_to_glb_process,
result_path, result_path,
str(source_path), str(source_path),
str(glb_path), str(glb_path),
"step",
) )
tree = result["tree"] tree = result["tree"]
stats = result["stats"] stats = result["stats"]
@@ -1072,7 +1106,7 @@ def convert_step_assets(source_path: Path, glb_path: Path, xkt_path: Path, metad
"fallbackReason": str(exc), "fallbackReason": str(exc),
} }
return build_step_metadata( return build_cad_metadata(
source_path, source_path,
glb_path, glb_path,
xkt_path, xkt_path,
@@ -1080,6 +1114,30 @@ def convert_step_assets(source_path: Path, glb_path: Path, xkt_path: Path, metad
tree=tree, tree=tree,
stats=stats, stats=stats,
import_strategy=import_strategy, import_strategy=import_strategy,
source_format="step",
)
def convert_iges_assets(source_path: Path, glb_path: Path, xkt_path: Path, metadata_path: Path) -> dict[str, Any]:
result_path = metadata_path.with_name(f"{metadata_path.name}.stage-result.json")
result = run_cad_glb_stage_with_timeout(
"IGES OCCT/XCAF",
XCAF_TIMEOUT_SECONDS,
convert_cad_xcaf_to_glb_process,
result_path,
str(source_path),
str(glb_path),
"iges",
)
return build_cad_metadata(
source_path,
glb_path,
xkt_path,
metadata_path,
tree=result["tree"],
stats=result["stats"],
import_strategy="occt-xcaf-gltf",
source_format="iges",
) )
@@ -1113,6 +1171,9 @@ def process_one(source_path: Path) -> bool:
xkt_path = source_path.with_name(f"{stem}.xkt") xkt_path = source_path.with_name(f"{stem}.xkt")
metadata_path = source_path.with_name(f"{stem}.metadata.json") metadata_path = source_path.with_name(f"{stem}.metadata.json")
manifest = read_json(manifest_file) manifest = read_json(manifest_file)
source_format = source_format_for_path(source_path)
if not source_format:
return False
if not should_process(source_path, manifest, glb_path, xkt_path): if not should_process(source_path, manifest, glb_path, xkt_path):
return False return False
@@ -1140,7 +1201,7 @@ def process_one(source_path: Path) -> bool:
"componentTreeRequired": True, "componentTreeRequired": True,
"converterName": CONVERTER_NAME, "converterName": CONVERTER_NAME,
"converterVersion": CONVERTER_VERSION, "converterVersion": CONVERTER_VERSION,
"sourceFormat": "step", "sourceFormat": source_format,
"sourceSrc": src_from_path(source_path), "sourceSrc": src_from_path(source_path),
"targetFormat": "xkt" if XKT_ENABLED else "glb", "targetFormat": "xkt" if XKT_ENABLED else "glb",
} }
@@ -1215,7 +1276,8 @@ def process_one(source_path: Path) -> bool:
print(f"[{CONVERTER_NAME}] converting {source_path}", flush=True) print(f"[{CONVERTER_NAME}] converting {source_path}", flush=True)
try: try:
metadata = convert_step_assets(source_path, glb_path, xkt_path, metadata_path) converter = convert_step_assets if source_format == "step" else convert_iges_assets
metadata = converter(source_path, glb_path, xkt_path, metadata_path)
artifact_src = metadata.get("artifact") or src_from_path(xkt_path if xkt_path.exists() else glb_path) artifact_src = metadata.get("artifact") or src_from_path(xkt_path if xkt_path.exists() else glb_path)
artifact_type = metadata.get("artifactType") or ("xkt" if xkt_path.exists() else "gltf") artifact_type = metadata.get("artifactType") or ("xkt" if xkt_path.exists() else "gltf")
ready_manifest = { ready_manifest = {
@@ -1943,7 +2005,7 @@ def scan_once() -> int:
continue continue
suffix = source_path.suffix.lower() suffix = source_path.suffix.lower()
did_process = False did_process = False
if suffix in STEP_EXTENSIONS: if suffix in CAD_SOURCE_FORMAT_BY_EXTENSION:
did_process = process_one(source_path) did_process = process_one(source_path)
elif suffix in GLB_EXTENSIONS: elif suffix in GLB_EXTENSIONS:
did_process = convert_glb_to_xkt_one(source_path) did_process = convert_glb_to_xkt_one(source_path)
+10
View File
@@ -0,0 +1,10 @@
export const CONVERTIBLE_MODEL_FORMATS = new Map([
[".step", "step"],
[".stp", "step"],
[".iges", "iges"],
[".igs", "iges"]
]);
export const conversionQueuedMessage = (sourceFormat) =>
`Оригинальный ${String(sourceFormat || "CAD").toUpperCase()} загружен. ` +
"Просмотр появится после подготовки модели и дерева компонентов.";
+21
View File
@@ -0,0 +1,21 @@
import assert from "node:assert/strict";
import test from "node:test";
import {CONVERTIBLE_MODEL_FORMATS, conversionQueuedMessage} from "./cad-formats.js";
test("routes STEP and IGES filename variants to canonical converter formats", () => {
assert.deepEqual(
Object.fromEntries(CONVERTIBLE_MODEL_FORMATS),
{
".step": "step",
".stp": "step",
".iges": "iges",
".igs": "iges"
}
);
});
test("conversion message names the canonical source format", () => {
assert.match(conversionQueuedMessage("iges"), /IGES/);
assert.match(conversionQueuedMessage("step"), /STEP/);
});
+5 -6
View File
@@ -5,6 +5,7 @@ import path from "path";
import {fileURLToPath} from "url"; import {fileURLToPath} from "url";
import crypto from "crypto"; import crypto from "crypto";
import {pipeline} from "stream/promises"; import {pipeline} from "stream/promises";
import {CONVERTIBLE_MODEL_FORMATS, conversionQueuedMessage} from "./cad-formats.js";
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename); const __dirname = path.dirname(__filename);
@@ -87,14 +88,12 @@ const MIME_TYPES = {
".bim": "application/octet-stream", ".bim": "application/octet-stream",
".step": "application/octet-stream", ".step": "application/octet-stream",
".stp": "application/octet-stream", ".stp": "application/octet-stream",
".iges": "application/octet-stream",
".igs": "application/octet-stream",
".wasm": "application/wasm", ".wasm": "application/wasm",
".txt": "text/plain" ".txt": "text/plain"
}; };
const CONVERTIBLE_MODEL_FORMATS = new Map([
[".step", "step"],
[".stp", "step"]
]);
const GLB_DRACO_OPTIMIZABLE_FORMATS = new Set(["glb"]); const GLB_DRACO_OPTIMIZABLE_FORMATS = new Set(["glb"]);
const GLB_XKT_CONVERTIBLE_FORMATS = new Set(["glb"]); const GLB_XKT_CONVERTIBLE_FORMATS = new Set(["glb"]);
const GLB_LOD_SOURCE_FORMATS = new Set(["glb"]); const GLB_LOD_SOURCE_FORMATS = new Set(["glb"]);
@@ -2854,7 +2853,7 @@ const handleRawUpload = async (req, res, url) => {
const conversion = { const conversion = {
...versionRecord, ...versionRecord,
componentTreeRequired: true, componentTreeRequired: true,
message: "Оригинальный STEP загружен. Просмотр появится после подготовки модели и дерева компонентов.", message: conversionQueuedMessage(sourceFormat),
sourceFormat, sourceFormat,
status: "conversion_required", status: "conversion_required",
targetFormat: "xkt", targetFormat: "xkt",
@@ -3275,7 +3274,7 @@ const handleConversionStatus = async (res, searchParams) => {
if (!manifest) { if (!manifest) {
sendJSON(res, 200, { sendJSON(res, 200, {
componentTreeRequired: true, componentTreeRequired: true,
message: "Оригинальный STEP загружен. Просмотр появится после подготовки модели и дерева компонентов.", message: conversionQueuedMessage(sourceFormat),
sourceFormat, sourceFormat,
sourceSrc: srcFromUploadPath(sourcePath), sourceSrc: srcFromUploadPath(sourcePath),
status: "conversion_required", status: "conversion_required",
+2 -1
View File
@@ -5,6 +5,7 @@
"version": "0.1.0", "version": "0.1.0",
"description": "Lightweight file-based API for xeokit BIM viewer projects", "description": "Lightweight file-based API for xeokit BIM viewer projects",
"scripts": { "scripts": {
"start": "node index.js" "start": "node index.js",
"test": "node --test cad-formats.test.js"
} }
} }