This commit is contained in:
2026-04-30 17:01:43 +08:00
parent 838604fddf
commit c67755015e
2 changed files with 198 additions and 106 deletions
+54 -9
View File
@@ -4,6 +4,7 @@ import os
from fastapi import APIRouter, Depends, HTTPException, Request from fastapi import APIRouter, Depends, HTTPException, Request
from services.auth_service import get_current_active_user from services.auth_service import get_current_active_user
from services.redis_task_manager import redis_task_manager
from models.database import User from models.database import User
from utils.logger import get_logger from utils.logger import get_logger
from api.routes import ( from api.routes import (
@@ -24,6 +25,16 @@ logger = get_logger(__name__)
router = APIRouter() router = APIRouter()
async def _get_task_data(task_id: str) -> dict:
"""从 Redis 优先查找任务,回退到旧版内存字典"""
task = await redis_task_manager.get_task(task_id)
if task:
return task
if task_id in tasks:
return tasks[task_id]
return None
@router.post("/optimize-layout") @router.post("/optimize-layout")
async def optimize_cavity_layout( async def optimize_cavity_layout(
request: Request, request: Request,
@@ -140,10 +151,13 @@ async def ai_parting_surface_detect(
body = await request.json() body = await request.json()
task_id = body.get("task_id") task_id = body.get("task_id")
if not task_id or task_id not in tasks: if not task_id:
raise HTTPException(404, "缺少 task_id")
task_data = await _get_task_data(task_id)
if not task_data:
raise HTTPException(404, "任务不存在") raise HTTPException(404, "任务不存在")
task_data = tasks[task_id]
geometry_data = task_data.get("geometry_data") geometry_data = task_data.get("geometry_data")
if not geometry_data: if not geometry_data:
raise HTTPException(400, "该任务尚未完成几何分析") raise HTTPException(400, "该任务尚未完成几何分析")
@@ -166,10 +180,13 @@ async def detect_undercuts(
parting_direction = body.get("parting_direction", [0, 0, 1]) parting_direction = body.get("parting_direction", [0, 0, 1])
mold_size = body.get("mold_size", {"length": 300, "width": 300, "height": 200}) mold_size = body.get("mold_size", {"length": 300, "width": 300, "height": 200})
if not task_id or task_id not in tasks: if not task_id:
raise HTTPException(404, "缺少 task_id")
task_data = await _get_task_data(task_id)
if not task_data:
raise HTTPException(404, "任务不存在") raise HTTPException(404, "任务不存在")
task_data = tasks[task_id]
geometry_data = task_data.get("geometry_data") geometry_data = task_data.get("geometry_data")
if not geometry_data: if not geometry_data:
raise HTTPException(400, "该任务尚未完成几何分析") raise HTTPException(400, "该任务尚未完成几何分析")
@@ -288,15 +305,25 @@ async def export_mold_results(
formats = body.get("formats", ["step", "stl"]) formats = body.get("formats", ["step", "stl"])
components = body.get("components", ["cavity", "core"]) components = body.get("components", ["cavity", "core"])
if not task_id or task_id not in tasks: if not task_id:
raise HTTPException(404, "缺少 task_id")
task_data = await _get_task_data(task_id)
if not task_data:
raise HTTPException(404, "任务不存在") raise HTTPException(404, "任务不存在")
task_data = tasks[task_id]
cavity_shapes = task_data.get("cavity_shapes") cavity_shapes = task_data.get("cavity_shapes")
if not cavity_shapes: filename = task_data.get("filename", f"mold_{task_id}")
raise HTTPException(400, "该任务尚未完成模具生成或形状数据不可用")
base_filename = Path(task_data.get("filename", f"mold_{task_id}")).stem if not cavity_shapes:
file_path = task_data.get("file_path")
if file_path and os.path.exists(str(file_path)):
cavity_shapes = await _reparse_stp_for_export(str(file_path), task_data.get("material", "ABS"))
if not cavity_shapes:
raise HTTPException(400, "该任务尚未完成模具生成或形状数据不可用,请等待处理完成后再导出")
base_filename = Path(filename).stem
result = cad_exporter.export_mold_results( result = cad_exporter.export_mold_results(
cavity_data=cavity_shapes, cavity_data=cavity_shapes,
base_filename=base_filename, base_filename=base_filename,
@@ -350,3 +377,21 @@ async def get_export_recommendations(
"""获取导出格式建议(UG/FreeCAD/SolidWorks)""" """获取导出格式建议(UG/FreeCAD/SolidWorks)"""
result = cad_exporter.get_export_recommendations(target) result = cad_exporter.get_export_recommendations(target)
return {"status": "success", "data": result} return {"status": "success", "data": result}
async def _reparse_stp_for_export(file_path: str, material: str = "ABS") -> dict:
"""从 STP 文件重新生成模具型腔数据用于导出"""
try:
from core.stp_parser import STPParser
from core.mold_generator import MoldCavityGenerator
stp_parser = STPParser()
shape = stp_parser.load_step_file(Path(file_path))
mold_gen = MoldCavityGenerator(shrinkage_rate=0.005)
mold_gen.set_material(material)
cavity_result = mold_gen.generate_mold_cavities(shape)
logger.info(f"重新解析 STP 用于导出: {file_path}")
return cavity_result
except Exception as e:
logger.warning(f"重新解析 STP 导出失败: {e}")
return None
+139 -92
View File
@@ -241,11 +241,43 @@ class HTMLGenerator:
y - Number(center[1] || 0), y - Number(center[1] || 0),
z - Number(center[2] || 0) z - Number(center[2] || 0)
); );
}} else {{
normalized.push(0, 0, 0);
}} }}
}} }}
return normalized; return normalized;
}} }}
function filterDegenerateFaces(vertices, faces) {{
const count = vertices.length / 3;
const faceCount = faces.length / 3;
const goodFaces = [];
for (let f = 0; f < faceCount; f++) {{
const a = faces[f * 3];
const b = faces[f * 3 + 1];
const c = faces[f * 3 + 2];
if (a >= 0 && a < count && b >= 0 && b < count && c >= 0 && c < count &&
a !== b && b !== c && a !== c) {{
goodFaces.push(a, b, c);
}}
}}
return goodFaces;
}}
function getPartingDirectionFromData() {{
if (cavityData?.metadata?.scheme_axis) {{
const ax = cavityData.metadata.scheme_axis;
if (ax === 'X') return {{ axis: 'x', normal: [1, 0, 0], planeRot: [0, 0, Math.PI / 2] }};
if (ax === 'Y') return {{ axis: 'y', normal: [0, 1, 0], planeRot: [Math.PI / 2, 0, 0] }};
}}
if (cavityData?.parting?.axis) {{
const ax = cavityData.parting.axis;
if (ax === 'X') return {{ axis: 'x', normal: [1, 0, 0], planeRot: [0, 0, Math.PI / 2] }};
if (ax === 'Y') return {{ axis: 'y', normal: [0, 1, 0], planeRot: [Math.PI / 2, 0, 0] }};
}}
return {{ axis: 'z', normal: [0, 0, 1], planeRot: [0, 0, 0] }};
}}
function fitCameraToScene() {{ function fitCameraToScene() {{
const sceneBox = new THREE.Box3().setFromObject(scene); const sceneBox = new THREE.Box3().setFromObject(scene);
if (sceneBox.isEmpty()) return; if (sceneBox.isEmpty()) return;
@@ -318,50 +350,56 @@ class HTMLGenerator:
scene.add(productMesh); scene.add(productMesh);
}} }}
// 获取分模方向
const partingInfo = getPartingDirectionFromData();
// 创建A板/定模(蓝色,分型面以上) // 创建A板/定模(蓝色,分型面以上)
// 尝试从后端数据获取实际几何,否则使用简化Box
if (cavityData && cavityData.mold_cavities && cavityData.mold_cavities.cavity && cavityData.mold_cavities.cavity.vertices) {{ if (cavityData && cavityData.mold_cavities && cavityData.mold_cavities.cavity && cavityData.mold_cavities.cavity.vertices) {{
const cavityVerts = cavityData.mold_cavities.cavity.vertices; const cavityVerts = cavityData.mold_cavities.cavity.vertices;
const cavityFaces = cavityData.mold_cavities.cavity.faces; const cavityFaces = cavityData.mold_cavities.cavity.faces;
if (cavityVerts.length > 0 && cavityFaces.length > 0) {{ if (cavityVerts.length > 0 && cavityFaces.length > 0) {{
const cavityGeometry = new THREE.BufferGeometry();
const positions = new Float32Array(normalizePositions(cavityVerts, centerOffset)); const positions = new Float32Array(normalizePositions(cavityVerts, centerOffset));
const indices = new Uint32Array(toFlatArray(cavityFaces)); const rawIndices = toFlatArray(cavityFaces);
cavityGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)); const goodFaces = filterDegenerateFaces(positions, rawIndices);
cavityGeometry.setIndex(new THREE.BufferAttribute(indices, 1));
cavityGeometry.computeVertexNormals();
const cavityMaterial = new THREE.MeshPhongMaterial({{ if (goodFaces.length >= 3) {{
color: 0x2196F3, const cavityGeometry = new THREE.BufferGeometry();
transparent: true, cavityGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
opacity: 0.5, cavityGeometry.setIndex(goodFaces);
wireframe: false, cavityGeometry.computeVertexNormals();
side: THREE.DoubleSide
}});
cavityMesh = new THREE.Mesh(cavityGeometry, cavityMaterial); const cavityMaterial = new THREE.MeshPhongMaterial({{
scene.add(cavityMesh); color: 0x2196F3,
transparent: true,
opacity: 0.5,
wireframe: false,
side: THREE.DoubleSide
}});
// 添加线框 cavityMesh = new THREE.Mesh(cavityGeometry, cavityMaterial);
const cavityWireframe = new THREE.WireframeGeometry(cavityGeometry); scene.add(cavityMesh);
const cavityLine = new THREE.LineSegments(cavityWireframe);
cavityLine.material.depthTest = false;
cavityLine.material.opacity = 0.6;
cavityLine.material.transparent = true;
cavityLine.material.color = new THREE.Color(0x1565C0);
cavityMesh.add(cavityLine);
// 设置相机目标为型腔中心 const cavityWireframe = new THREE.WireframeGeometry(cavityGeometry);
cavityGeometry.computeBoundingBox(); const cavityLine = new THREE.LineSegments(cavityWireframe);
const cavityCenter = new THREE.Vector3(); cavityLine.material.depthTest = false;
cavityGeometry.boundingBox.getCenter(cavityCenter); cavityLine.material.opacity = 0.6;
controls.target.set(cavityCenter.x, cavityCenter.y, cavityCenter.z); cavityLine.material.transparent = true;
cavityLine.material.color = new THREE.Color(0x1565C0);
cavityMesh.add(cavityLine);
cavityGeometry.computeBoundingBox();
const cavityCenter = new THREE.Vector3();
cavityGeometry.boundingBox.getCenter(cavityCenter);
controls.target.set(cavityCenter.x, cavityCenter.y, cavityCenter.z);
}} else {{
createSimpleCavity(width, height, depth, partingInfo);
}}
}} else {{ }} else {{
createSimpleCavity(width, height, depth); createSimpleCavity(width, height, depth, partingInfo);
}} }}
}} else {{ }} else {{
createSimpleCavity(width, height, depth); createSimpleCavity(width, height, depth, partingInfo);
}} }}
// 创建B板/动模(橙色,分型面以下) // 创建B板/动模(橙色,分型面以下)
@@ -370,41 +408,50 @@ class HTMLGenerator:
const coreFaces = cavityData.mold_cavities.core.faces; const coreFaces = cavityData.mold_cavities.core.faces;
if (coreVerts.length > 0 && coreFaces.length > 0) {{ if (coreVerts.length > 0 && coreFaces.length > 0) {{
const coreGeometry = new THREE.BufferGeometry();
const positions = new Float32Array(normalizePositions(coreVerts, centerOffset)); const positions = new Float32Array(normalizePositions(coreVerts, centerOffset));
const indices = new Uint32Array(toFlatArray(coreFaces)); const rawIndices = toFlatArray(coreFaces);
coreGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)); const goodFaces = filterDegenerateFaces(positions, rawIndices);
coreGeometry.setIndex(new THREE.BufferAttribute(indices, 1));
coreGeometry.computeVertexNormals();
const coreMaterial = new THREE.MeshPhongMaterial({{ if (goodFaces.length >= 3) {{
color: 0xFF9800, const coreGeometry = new THREE.BufferGeometry();
transparent: true, coreGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
opacity: 0.5, coreGeometry.setIndex(goodFaces);
wireframe: false, coreGeometry.computeVertexNormals();
side: THREE.DoubleSide
}});
coreMesh = new THREE.Mesh(coreGeometry, coreMaterial); const coreMaterial = new THREE.MeshPhongMaterial({{
scene.add(coreMesh); color: 0xFF9800,
transparent: true,
opacity: 0.5,
wireframe: false,
side: THREE.DoubleSide
}});
// 添加线框 coreMesh = new THREE.Mesh(coreGeometry, coreMaterial);
const coreWireframe = new THREE.WireframeGeometry(coreGeometry); scene.add(coreMesh);
const coreLine = new THREE.LineSegments(coreWireframe);
coreLine.material.depthTest = false; const coreWireframe = new THREE.WireframeGeometry(coreGeometry);
coreLine.material.opacity = 0.6; const coreLine = new THREE.LineSegments(coreWireframe);
coreLine.material.transparent = true; coreLine.material.depthTest = false;
coreLine.material.color = new THREE.Color(0xE65100); coreLine.material.opacity = 0.6;
coreMesh.add(coreLine); coreLine.material.transparent = true;
coreLine.material.color = new THREE.Color(0xE65100);
coreMesh.add(coreLine);
}} else {{
createSimpleCore(width, height, depth, partingInfo);
}}
}} else {{ }} else {{
createSimpleCore(width, height, depth); createSimpleCore(width, height, depth, partingInfo);
}} }}
}} else {{ }} else {{
createSimpleCore(width, height, depth); createSimpleCore(width, height, depth, partingInfo);
}} }}
// 创建分型面(红色平面) // 创建分型面(红色平面)- 按分模方向旋转
const partingGeometry = new THREE.PlaneGeometry(width * 1.2, height * 1.2); const partingInfo2 = getPartingDirectionFromData();
let planeW = width * 1.2, planeH = height * 1.2;
if (partingInfo2.axis === 'x') {{ planeW = depth * 1.2; planeH = height * 1.2; }}
else if (partingInfo2.axis === 'y') {{ planeW = width * 1.2; planeH = depth * 1.2; }}
const partingGeometry = new THREE.PlaneGeometry(planeW, planeH);
const partingMaterial = new THREE.MeshBasicMaterial({{ const partingMaterial = new THREE.MeshBasicMaterial({{
color: 0xF44336, color: 0xF44336,
transparent: true, transparent: true,
@@ -413,6 +460,7 @@ class HTMLGenerator:
}}); }});
partingMesh = new THREE.Mesh(partingGeometry, partingMaterial); partingMesh = new THREE.Mesh(partingGeometry, partingMaterial);
partingMesh.rotation.set(partingInfo2.planeRot[0], partingInfo2.planeRot[1], partingInfo2.planeRot[2]);
partingMesh.position.set(0, 0, 0); partingMesh.position.set(0, 0, 0);
scene.add(partingMesh); scene.add(partingMesh);
@@ -425,26 +473,33 @@ class HTMLGenerator:
productLine.material.transparent = true; productLine.material.transparent = true;
productLine.material.color = new THREE.Color(0x2E7D32); productLine.material.color = new THREE.Color(0x2E7D32);
productMesh.add(productLine); productMesh.add(productLine);
}} else if (cavityMesh || coreMesh) {{
// 有型腔/型芯但没有产品模型时,补一个参考产品框
const prodBox = new THREE.BoxGeometry(width * 0.85, height * 0.85, depth * 0.85);
const prodMat = new THREE.MeshPhongMaterial({{
color: 0x4CAF50, transparent: true, opacity: 0.35, wireframe: false
}});
productMesh = new THREE.Mesh(prodBox, prodMat);
scene.add(productMesh);
}} }}
}} }}
// 创建简化型腔/A板(定模,分型面以上)— 备用 // 创建简化型腔/A板(定模,分型面以上)— 备用
function createSimpleCavity(width, height, depth) {{ function createSimpleCavity(width, height, depth, partingInfo) {{
// A板:分型面(Z中心)以上的上半模 const pi = partingInfo || {{ axis: 'z', normal: [0, 0, 1] }};
const halfDepth = depth / 2; let boxW = width * 1.2, boxH = height * 1.2, boxD = depth / 2 + 10;
const cavityGeometry = new THREE.BoxGeometry(width * 1.2, height * 1.2, halfDepth + 10); let pos = [0, 0, boxD / 2];
let rot = [0, 0, 0];
if (pi.axis === 'x') {{ boxW = depth / 2 + 10; boxH = height * 1.2; boxD = width * 1.2; pos = [boxW / 2, 0, 0]; rot = [0, 0, Math.PI / 2]; }}
else if (pi.axis === 'y') {{ boxW = width * 1.2; boxH = depth / 2 + 10; boxD = height * 1.2; pos = [0, boxH / 2, 0]; rot = [Math.PI / 2, 0, 0]; }}
const cavityGeometry = new THREE.BoxGeometry(boxW, boxH, boxD);
const cavityMaterial = new THREE.MeshPhongMaterial({{ const cavityMaterial = new THREE.MeshPhongMaterial({{
color: 0x2196F3, color: 0x2196F3, transparent: true, opacity: 0.4, wireframe: false
transparent: true,
opacity: 0.4,
wireframe: false
}}); }});
cavityMesh = new THREE.Mesh(cavityGeometry, cavityMaterial); cavityMesh = new THREE.Mesh(cavityGeometry, cavityMaterial);
// Z轴开模:A板放在分型面以上 cavityMesh.position.set(pos[0], pos[1], pos[2]);
cavityMesh.position.set(0, 0, halfDepth / 2 + 5); cavityMesh.rotation.set(rot[0], rot[1], rot[2]);
scene.add(cavityMesh); scene.add(cavityMesh);
const cavityWireframe = new THREE.WireframeGeometry(cavityGeometry); const cavityWireframe = new THREE.WireframeGeometry(cavityGeometry);
const cavityLine = new THREE.LineSegments(cavityWireframe); const cavityLine = new THREE.LineSegments(cavityWireframe);
cavityLine.material.depthTest = false; cavityLine.material.depthTest = false;
@@ -455,22 +510,21 @@ class HTMLGenerator:
}} }}
// 创建简化型芯/B板(动模,分型面以下)— 备用 // 创建简化型芯/B板(动模,分型面以下)— 备用
function createSimpleCore(width, height, depth) {{ function createSimpleCore(width, height, depth, partingInfo) {{
// B板:分型面(Z中心)以下的下半模 const pi = partingInfo || {{ axis: 'z', normal: [0, 0, 1] }};
const halfDepth = depth / 2; let boxW = width * 1.2, boxH = height * 1.2, boxD = depth / 2 + 10;
const coreGeometry = new THREE.BoxGeometry(width * 1.2, height * 1.2, halfDepth + 10); let pos = [0, 0, -boxD / 2];
let rot = [0, 0, 0];
if (pi.axis === 'x') {{ boxW = depth / 2 + 10; boxH = height * 1.2; boxD = width * 1.2; pos = [-boxW / 2, 0, 0]; rot = [0, 0, Math.PI / 2]; }}
else if (pi.axis === 'y') {{ boxW = width * 1.2; boxH = depth / 2 + 10; boxD = height * 1.2; pos = [0, -boxH / 2, 0]; rot = [Math.PI / 2, 0, 0]; }}
const coreGeometry = new THREE.BoxGeometry(boxW, boxH, boxD);
const coreMaterial = new THREE.MeshPhongMaterial({{ const coreMaterial = new THREE.MeshPhongMaterial({{
color: 0xFF9800, color: 0xFF9800, transparent: true, opacity: 0.4, wireframe: false
transparent: true,
opacity: 0.4,
wireframe: false
}}); }});
coreMesh = new THREE.Mesh(coreGeometry, coreMaterial); coreMesh = new THREE.Mesh(coreGeometry, coreMaterial);
// Z轴开模:B板放在分型面以下 coreMesh.position.set(pos[0], pos[1], pos[2]);
coreMesh.position.set(0, 0, -halfDepth / 2 - 5); coreMesh.rotation.set(rot[0], rot[1], rot[2]);
scene.add(coreMesh); scene.add(coreMesh);
const coreWireframe = new THREE.WireframeGeometry(coreGeometry); const coreWireframe = new THREE.WireframeGeometry(coreGeometry);
const coreLine = new THREE.LineSegments(coreWireframe); const coreLine = new THREE.LineSegments(coreWireframe);
coreLine.material.depthTest = false; coreLine.material.depthTest = false;
@@ -547,18 +601,11 @@ class HTMLGenerator:
// 根据材料类型确定分模方向 // 根据材料类型确定分模方向
function getPartingDirection() {{ function getPartingDirection() {{
// 优先使用后端传递的 parting_direction if (cavityData?.metadata?.scheme_axis) return cavityData.metadata.scheme_axis;
if (cavityData?.metadata?.parting_direction) {{ if (cavityData?.parting?.axis) return cavityData.parting.axis;
return cavityData.metadata.parting_direction; if (cavityData?.metadata?.parting_direction) return cavityData.metadata.parting_direction;
}} if (cavityData?.manufacturing_info?.parting_direction) return cavityData.manufacturing_info.parting_direction;
if (cavityData?.manufacturing_info?.parting_direction) {{ if (cavityData?.metadata?.is_foam) return 'Z';
return cavityData.manufacturing_info.parting_direction;
}}
// 泡沫材料默认 Z 轴
if (cavityData?.metadata?.is_foam) {{
return 'Z';
}}
// 默认 Z 轴
return 'Z'; return 'Z';
}} }}