Git Komut Rehberi & Terminal Asistanı
Sıfırdan Yeni Bir Depo Başlatın:
Mevcut Bir Git Deposu veya Klasörü Gönderin:
Hataları Geri Alma, İptal & Temizlik:
Son commit'i geri al (yapılan değişiklikleri korur):
git reset --soft HEAD~1
Yapılan yerel değişiklikleri iptal et (çalışma ağacını temizler):
git restore .
Takip edilmeyen gereksiz dosyaları sil:
git clean -fd
Değişiklikleri geçici sakla ve geri getir (stash):
git stash git stash pop
Dal (Branch) ve Sürüm Etiketleri:
Yeni dal aç ve geçiş yap:
git checkout -b yeni-ozellik git push -u origin yeni-ozellik
Sürüm etiketi (tag) oluştur ve gönder:
git tag -a v1.0.0 -m "Sürüm 1.0.0" git push origin --tags
- SnapVoice Turkce sesli CAD ve komut konsolu (/denetle, /ram, /eko, /otomatik, /sessiz) - 3B uzamsal sesli radar ve gorme engelli gelistirici geometri denetim motoru - LibreDWG/DXF ikili sikistirma, font tembel yukleme ve RAM optimizasyonu - Monitor cozunurlugune gore otomatik uyarlamali dinamik grafik modu
995 lines
35 KiB
TypeScript
995 lines
35 KiB
TypeScript
import * as THREE from "three";
|
||
import DxfParser from "dxf-parser";
|
||
import { deflateSync, inflateSync, strToU8, strFromU8 } from "fflate";
|
||
import { createLocalId } from "@/lib/localIds";
|
||
import type { WorkplaneShape } from "@/types/sketchforge";
|
||
|
||
export function compressDxfText(source: string): string {
|
||
const bytes = deflateSync(strToU8(source));
|
||
let binary = "";
|
||
for (let offset = 0; offset < bytes.length; offset += 0x8000) {
|
||
binary += String.fromCharCode(...bytes.subarray(offset, Math.min(bytes.length, offset + 0x8000)));
|
||
}
|
||
return globalThis.btoa(binary);
|
||
}
|
||
|
||
export function decompressDxfText(base64: string): string {
|
||
const binary = globalThis.atob(base64);
|
||
const bytes = new Uint8Array(binary.length);
|
||
for (let index = 0; index < binary.length; index += 1) {
|
||
bytes[index] = binary.charCodeAt(index);
|
||
}
|
||
return strFromU8(inflateSync(bytes));
|
||
}
|
||
|
||
export function getImportedDxfText(importedMesh?: WorkplaneShape["importedMesh"]): string | undefined {
|
||
if (!importedMesh) return undefined;
|
||
if (importedMesh.sourceDxfText) return importedMesh.sourceDxfText;
|
||
if (importedMesh.sourceDxfCompressed) {
|
||
try {
|
||
return decompressDxfText(importedMesh.sourceDxfCompressed);
|
||
} catch (err) {
|
||
console.warn("Could not decompress DXF source", err);
|
||
return undefined;
|
||
}
|
||
}
|
||
return undefined;
|
||
}
|
||
|
||
export const MAX_DXF_ENTITIES = 50_000;
|
||
export const MAX_DXF_TRIANGLES = 200_000;
|
||
const DEFAULT_DXF_EXTRUSION_DEPTH = 4;
|
||
/**
|
||
* Büyük ölçekli çizimlerde (ör. milimetre cinsinden mimari planlar) sabit 4 birim
|
||
* kalınlık kâğıt inceliğinde kalır. Bu yüzden kalınlık çizim boyutuna göre
|
||
* ölçeklenir; küçük çizimlerde 4 birim korunur.
|
||
*/
|
||
const DXF_EXTRUSION_SCALE = 0.01;
|
||
const MAX_DXF_EXTRUSION_DEPTH = 50_000;
|
||
|
||
/** Çizim boyutuna göre görünür bir katı kalınlığı hesaplar. */
|
||
export function dxfExtrusionDepthForSpan(maxDimension: number) {
|
||
if (!Number.isFinite(maxDimension) || maxDimension <= 0) return DEFAULT_DXF_EXTRUSION_DEPTH;
|
||
return Math.min(
|
||
MAX_DXF_EXTRUSION_DEPTH,
|
||
Math.max(DEFAULT_DXF_EXTRUSION_DEPTH, maxDimension * DXF_EXTRUSION_SCALE),
|
||
);
|
||
}
|
||
|
||
type Point2D = [number, number];
|
||
type Point3D = [number, number, number];
|
||
type Triangle3D = [Point3D, Point3D, Point3D];
|
||
type LineSegment = { p1: Point2D; p2: Point2D };
|
||
|
||
interface AffineTransform2D {
|
||
tx: number;
|
||
ty: number;
|
||
scaleX: number;
|
||
scaleY: number;
|
||
cosR: number;
|
||
sinR: number;
|
||
}
|
||
|
||
function createIdentityTransform(): AffineTransform2D {
|
||
return { tx: 0, ty: 0, scaleX: 1, scaleY: 1, cosR: 1, sinR: 0 };
|
||
}
|
||
|
||
function applyTransform2D(pt: Point2D, t: AffineTransform2D): Point2D {
|
||
const sx = pt[0] * t.scaleX;
|
||
const sy = pt[1] * t.scaleY;
|
||
return [
|
||
t.tx + sx * t.cosR - sy * t.sinR,
|
||
t.ty + sx * t.sinR + sy * t.cosR,
|
||
];
|
||
}
|
||
|
||
function combineTransforms(parent: AffineTransform2D, child: {
|
||
x?: number;
|
||
y?: number;
|
||
scaleX?: number;
|
||
scaleY?: number;
|
||
rotationDeg?: number;
|
||
}): AffineTransform2D {
|
||
const childRad = ((child.rotationDeg ?? 0) * Math.PI) / 180;
|
||
const childCos = Math.cos(childRad);
|
||
const childSin = Math.sin(childRad);
|
||
const cScaleX = child.scaleX ?? 1;
|
||
const cScaleY = child.scaleY ?? 1;
|
||
const cTx = child.x ?? 0;
|
||
const cTy = child.y ?? 0;
|
||
|
||
// Transform child's translation by parent
|
||
const [transX, transY] = applyTransform2D([cTx, cTy], parent);
|
||
|
||
// Combined scale & rotation approximation for 2D
|
||
const totalScaleX = parent.scaleX * cScaleX;
|
||
const totalScaleY = parent.scaleY * cScaleY;
|
||
const combinedCos = parent.cosR * childCos - parent.sinR * childSin;
|
||
const combinedSin = parent.sinR * childCos + parent.cosR * childSin;
|
||
|
||
return {
|
||
tx: transX,
|
||
ty: transY,
|
||
scaleX: totalScaleX,
|
||
scaleY: totalScaleY,
|
||
cosR: combinedCos,
|
||
sinR: combinedSin,
|
||
};
|
||
}
|
||
|
||
interface DxfPair {
|
||
code: number;
|
||
value: string;
|
||
}
|
||
|
||
function parseDxfPairs(text: string): DxfPair[] {
|
||
const lines = text.split(/\r?\n/);
|
||
const pairs: DxfPair[] = [];
|
||
for (let i = 0; i < lines.length - 1; i += 2) {
|
||
const codeStr = lines[i].trim();
|
||
if (codeStr === "") continue;
|
||
const code = parseInt(codeStr, 10);
|
||
if (isNaN(code)) continue;
|
||
const value = lines[i + 1].trim();
|
||
pairs.push({ code, value });
|
||
}
|
||
return pairs;
|
||
}
|
||
|
||
/**
|
||
* Checks if a 2D point is inside a polygon using ray casting algorithm.
|
||
*/
|
||
function pointInPolygon(point: Point2D, vs: Point2D[]): boolean {
|
||
const x = point[0];
|
||
const y = point[1];
|
||
let inside = false;
|
||
for (let i = 0, j = vs.length - 1; i < vs.length; j = i++) {
|
||
const xi = vs[i][0];
|
||
const yi = vs[i][1];
|
||
const xj = vs[j][0];
|
||
const yj = vs[j][1];
|
||
const intersect = yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi;
|
||
if (intersect) inside = !inside;
|
||
}
|
||
return inside;
|
||
}
|
||
|
||
/**
|
||
* Calculates signed area of a 2D polygon loop.
|
||
*/
|
||
function signedPolygonArea(points: Point2D[]): number {
|
||
let area = 0;
|
||
for (let i = 0; i < points.length; i++) {
|
||
const p1 = points[i];
|
||
const p2 = points[(i + 1) % points.length];
|
||
area += (p2[0] - p1[0]) * (p2[1] + p1[1]);
|
||
}
|
||
return area / 2;
|
||
}
|
||
|
||
/**
|
||
* Chains loose 2D line segments into closed loops without losing unclosed segments.
|
||
* Unclosed segments are safely preserved in `unclosedSegments`.
|
||
*/
|
||
function chainLineSegmentsPreserving(
|
||
segments: LineSegment[],
|
||
tolerance = 0.2,
|
||
): { closedLoops: Point2D[][]; unclosedSegments: LineSegment[] } {
|
||
const closedLoops: Point2D[][] = [];
|
||
const unclosedSegments: LineSegment[] = [];
|
||
const remaining = [...segments];
|
||
|
||
while (remaining.length > 0) {
|
||
const first = remaining.shift()!;
|
||
const loop: Point2D[] = [first.p1, first.p2];
|
||
let expanded = true;
|
||
|
||
while (expanded && remaining.length > 0) {
|
||
expanded = false;
|
||
const lastPoint = loop[loop.length - 1];
|
||
|
||
// Check if loop is already closed back to start
|
||
const distToStart = Math.hypot(lastPoint[0] - loop[0][0], lastPoint[1] - loop[0][1]);
|
||
if (loop.length >= 3 && distToStart <= tolerance) {
|
||
break;
|
||
}
|
||
|
||
for (let i = 0; i < remaining.length; i++) {
|
||
const seg = remaining[i];
|
||
const d1 = Math.hypot(lastPoint[0] - seg.p1[0], lastPoint[1] - seg.p1[1]);
|
||
const d2 = Math.hypot(lastPoint[0] - seg.p2[0], lastPoint[1] - seg.p2[1]);
|
||
|
||
if (d1 <= tolerance) {
|
||
loop.push(seg.p2);
|
||
remaining.splice(i, 1);
|
||
expanded = true;
|
||
break;
|
||
} else if (d2 <= tolerance) {
|
||
loop.push(seg.p1);
|
||
remaining.splice(i, 1);
|
||
expanded = true;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
// Check if the chained sequence forms a valid closed loop
|
||
const distToStart = Math.hypot(
|
||
loop[loop.length - 1][0] - loop[0][0],
|
||
loop[loop.length - 1][1] - loop[0][1],
|
||
);
|
||
|
||
if (loop.length >= 3 && distToStart <= tolerance * 2) {
|
||
closedLoops.push(loop);
|
||
} else {
|
||
// Preserve every single segment in the unclosed chain
|
||
for (let s = 0; s < loop.length - 1; s++) {
|
||
unclosedSegments.push({ p1: loop[s], p2: loop[s + 1] });
|
||
}
|
||
}
|
||
}
|
||
|
||
return { closedLoops, unclosedSegments };
|
||
}
|
||
|
||
/**
|
||
* Parses entities using the robust dxf-parser library.
|
||
* Supports Model Space blocks (*MODEL_SPACE), 3DFACE, LINE, LWPOLYLINE, POLYLINE
|
||
* (with bulge arc interpolation), CIRCLE, ARC, ELLIPSE, SOLID, TRACE, SPLINE, and nested INSERT blocks.
|
||
*/
|
||
function extractEntitiesWithDxfParser(source: string): {
|
||
faces3D: Triangle3D[];
|
||
closedLoops2D: Point2D[][];
|
||
looseLineSegments: LineSegment[];
|
||
} | null {
|
||
try {
|
||
const parser = new DxfParser();
|
||
const dxf = parser.parseSync(source);
|
||
if (!dxf) return null;
|
||
|
||
// Collect all candidate entities across dxf.entities, *MODEL_SPACE block, and non-paper blocks
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
const entitiesToProcess: any[] = [];
|
||
|
||
if (Array.isArray(dxf.entities) && dxf.entities.length > 0) {
|
||
entitiesToProcess.push(...dxf.entities);
|
||
}
|
||
|
||
// Check for *MODEL_SPACE block (typical for AutoCAD DWG converted to DXF)
|
||
if (dxf.blocks) {
|
||
const blockKeys = Object.keys(dxf.blocks);
|
||
const modelSpaceKey = blockKeys.find((k) =>
|
||
k.toUpperCase().includes("*MODEL_SPACE") || k.toUpperCase() === "MODEL_SPACE",
|
||
);
|
||
if (modelSpaceKey && Array.isArray(dxf.blocks[modelSpaceKey]?.entities)) {
|
||
entitiesToProcess.push(...dxf.blocks[modelSpaceKey].entities);
|
||
}
|
||
|
||
// If still empty, check any non-paper space block
|
||
if (entitiesToProcess.length === 0) {
|
||
for (const k of blockKeys) {
|
||
const b = dxf.blocks[k];
|
||
if (
|
||
b &&
|
||
!b.paperSpace &&
|
||
!k.toUpperCase().includes("PAPER") &&
|
||
Array.isArray(b.entities) &&
|
||
b.entities.length > 0
|
||
) {
|
||
entitiesToProcess.push(...b.entities);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
if (entitiesToProcess.length === 0) return null;
|
||
|
||
const faces3D: Triangle3D[] = [];
|
||
const closedLoops2D: Point2D[][] = [];
|
||
const looseLineSegments: LineSegment[] = [];
|
||
|
||
// Recursive entity processor supporting affine transformation for nested blocks
|
||
const processEntity = (
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
ent: any,
|
||
transform: AffineTransform2D,
|
||
depth = 0,
|
||
) => {
|
||
if (!ent || depth > 6) return;
|
||
|
||
if (ent.type === "3DFACE") {
|
||
const v = ent.vertices as Array<{ x: number; y: number; z?: number }> | undefined;
|
||
if (v && v.length >= 3) {
|
||
const tp1 = applyTransform2D([v[0].x, v[0].y], transform);
|
||
const tp2 = applyTransform2D([v[1].x, v[1].y], transform);
|
||
const tp3 = applyTransform2D([v[2].x, v[2].y], transform);
|
||
const z0 = (v[0].z ?? 0) * transform.scaleX;
|
||
const z1 = (v[1].z ?? 0) * transform.scaleX;
|
||
const z2 = (v[2].z ?? 0) * transform.scaleX;
|
||
|
||
faces3D.push([
|
||
[tp1[0], tp1[1], z0],
|
||
[tp2[0], tp2[1], z1],
|
||
[tp3[0], tp3[1], z2],
|
||
]);
|
||
|
||
if (v.length >= 4 && v[3] && v[3].x !== undefined) {
|
||
const tp4 = applyTransform2D([v[3].x, v[3].y], transform);
|
||
const z3 = (v[3].z ?? 0) * transform.scaleX;
|
||
const dist = Math.hypot(tp4[0] - tp3[0], tp4[1] - tp3[1], z3 - z2);
|
||
if (dist > 1e-4) {
|
||
faces3D.push([
|
||
[tp1[0], tp1[1], z0],
|
||
[tp3[0], tp3[1], z2],
|
||
[tp4[0], tp4[1], z3],
|
||
]);
|
||
}
|
||
}
|
||
}
|
||
} else if (ent.type === "LINE") {
|
||
const v = ent.vertices as Array<{ x: number; y: number }> | undefined;
|
||
if (v && v.length >= 2) {
|
||
const p1 = applyTransform2D([v[0].x, v[0].y], transform);
|
||
const p2 = applyTransform2D([v[1].x, v[1].y], transform);
|
||
if (Math.hypot(p2[0] - p1[0], p2[1] - p1[1]) > 1e-4) {
|
||
looseLineSegments.push({ p1, p2 });
|
||
}
|
||
}
|
||
} else if (ent.type === "LWPOLYLINE" || ent.type === "POLYLINE") {
|
||
const v = ent.vertices as Array<{ x: number; y: number; bulge?: number }> | undefined;
|
||
if (v && v.length >= 2) {
|
||
const rawPts: Point2D[] = [];
|
||
for (let idx = 0; idx < v.length; idx++) {
|
||
rawPts.push([v[idx].x, v[idx].y]);
|
||
const bulge = v[idx].bulge;
|
||
if (bulge && Math.abs(bulge) > 1e-4 && idx < v.length - 1) {
|
||
const pA = v[idx];
|
||
const pB = v[idx + 1];
|
||
const chord = Math.hypot(pB.x - pA.x, pB.y - pA.y);
|
||
if (chord > 1e-4) {
|
||
const sagitta = (bulge * chord) / 2;
|
||
for (let step = 1; step <= 4; step++) {
|
||
const t = step / 5;
|
||
const mx = pA.x + (pB.x - pA.x) * t;
|
||
const my = pA.y + (pB.y - pA.y) * t;
|
||
const perpX = -(pB.y - pA.y) / chord;
|
||
const perpY = (pB.x - pA.x) / chord;
|
||
const offset = Math.sin(t * Math.PI) * sagitta;
|
||
rawPts.push([mx + perpX * offset, my + perpY * offset]);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
const transformedPts = rawPts.map((pt) => applyTransform2D(pt, transform));
|
||
const isClosed =
|
||
ent.shape === true ||
|
||
(transformedPts.length >= 3 &&
|
||
Math.hypot(
|
||
transformedPts[transformedPts.length - 1][0] - transformedPts[0][0],
|
||
transformedPts[transformedPts.length - 1][1] - transformedPts[0][1],
|
||
) < 0.2);
|
||
|
||
if (isClosed && transformedPts.length >= 3) {
|
||
closedLoops2D.push(transformedPts);
|
||
} else {
|
||
for (let s = 0; s < transformedPts.length - 1; s++) {
|
||
if (Math.hypot(transformedPts[s + 1][0] - transformedPts[s][0], transformedPts[s + 1][1] - transformedPts[s][1]) > 1e-4) {
|
||
looseLineSegments.push({ p1: transformedPts[s], p2: transformedPts[s + 1] });
|
||
}
|
||
}
|
||
}
|
||
}
|
||
} else if (ent.type === "CIRCLE") {
|
||
const c = ent as { center: { x: number; y: number }; radius: number };
|
||
if (c.radius > 0) {
|
||
const circlePts: Point2D[] = [];
|
||
const segs = 36;
|
||
for (let step = 0; step < segs; step++) {
|
||
const angle = (step / segs) * Math.PI * 2;
|
||
const rawPt: Point2D = [
|
||
c.center.x + Math.cos(angle) * c.radius,
|
||
c.center.y + Math.sin(angle) * c.radius,
|
||
];
|
||
circlePts.push(applyTransform2D(rawPt, transform));
|
||
}
|
||
closedLoops2D.push(circlePts);
|
||
}
|
||
} else if (ent.type === "ARC") {
|
||
const a = ent as { center: { x: number; y: number }; radius: number; startAngle: number; endAngle: number };
|
||
if (a.radius > 0) {
|
||
let sRad = a.startAngle;
|
||
let eRad = a.endAngle;
|
||
if (eRad <= sRad) eRad += Math.PI * 2;
|
||
const arcSegments = Math.max(8, Math.round(((eRad - sRad) / (Math.PI * 2)) * 36));
|
||
const arcPts: Point2D[] = [];
|
||
for (let step = 0; step <= arcSegments; step++) {
|
||
const angle = sRad + (step / arcSegments) * (eRad - sRad);
|
||
const rawPt: Point2D = [
|
||
a.center.x + Math.cos(angle) * a.radius,
|
||
a.center.y + Math.sin(angle) * a.radius,
|
||
];
|
||
arcPts.push(applyTransform2D(rawPt, transform));
|
||
}
|
||
for (let s = 0; s < arcPts.length - 1; s++) {
|
||
if (Math.hypot(arcPts[s + 1][0] - arcPts[s][0], arcPts[s + 1][1] - arcPts[s][1]) > 1e-4) {
|
||
looseLineSegments.push({ p1: arcPts[s], p2: arcPts[s + 1] });
|
||
}
|
||
}
|
||
}
|
||
} else if (ent.type === "ELLIPSE") {
|
||
const el = ent as {
|
||
center?: { x: number; y: number };
|
||
majorAxisEndPoint?: { x: number; y: number };
|
||
axisRatio?: number;
|
||
startAngle?: number;
|
||
endAngle?: number;
|
||
};
|
||
const cx = el.center?.x ?? 0;
|
||
const cy = el.center?.y ?? 0;
|
||
const mx = el.majorAxisEndPoint?.x ?? 0;
|
||
const my = el.majorAxisEndPoint?.y ?? 0;
|
||
const majorLen = Math.hypot(mx, my);
|
||
|
||
if (majorLen > 1e-4) {
|
||
const uX = mx / majorLen;
|
||
const uY = my / majorLen;
|
||
const vX = -uY;
|
||
const vY = uX;
|
||
const minorLen = majorLen * (el.axisRatio ?? 1);
|
||
let sRad = el.startAngle ?? 0;
|
||
let eRad = el.endAngle ?? Math.PI * 2;
|
||
if (eRad <= sRad) eRad += Math.PI * 2;
|
||
const isFull = Math.abs(eRad - sRad) >= Math.PI * 2 - 1e-4;
|
||
const segs = Math.max(12, Math.round(((eRad - sRad) / (Math.PI * 2)) * 36));
|
||
|
||
const elPts: Point2D[] = [];
|
||
for (let step = 0; step <= segs; step++) {
|
||
const angle = sRad + (step / segs) * (eRad - sRad);
|
||
const px = cx + Math.cos(angle) * majorLen * uX + Math.sin(angle) * minorLen * vX;
|
||
const py = cy + Math.cos(angle) * majorLen * uY + Math.sin(angle) * minorLen * vY;
|
||
elPts.push(applyTransform2D([px, py], transform));
|
||
}
|
||
|
||
if (isFull) {
|
||
closedLoops2D.push(elPts);
|
||
} else {
|
||
for (let s = 0; s < elPts.length - 1; s++) {
|
||
looseLineSegments.push({ p1: elPts[s], p2: elPts[s + 1] });
|
||
}
|
||
}
|
||
}
|
||
} else if (ent.type === "SOLID" || ent.type === "TRACE") {
|
||
const pts = ent.points as Array<{ x: number; y: number; z?: number }> | undefined;
|
||
if (pts && pts.length >= 3) {
|
||
const t0 = applyTransform2D([pts[0].x, pts[0].y], transform);
|
||
const t1 = applyTransform2D([pts[1].x, pts[1].y], transform);
|
||
const t2 = applyTransform2D([pts[2].x, pts[2].y], transform);
|
||
const p4 = pts.length >= 4 ? pts[3] : undefined;
|
||
const t3 = p4 ? applyTransform2D([p4.x, p4.y], transform) : undefined;
|
||
|
||
// In AutoCAD SOLID, vertex order is [0, 1, 3, 2] forming a quad
|
||
if (t3) {
|
||
closedLoops2D.push([t0, t1, t3, t2]);
|
||
} else {
|
||
closedLoops2D.push([t0, t1, t2]);
|
||
}
|
||
}
|
||
} else if (ent.type === "SPLINE") {
|
||
const sp = ent as {
|
||
controlPoints?: Array<{ x: number; y: number }>;
|
||
fitPoints?: Array<{ x: number; y: number }>;
|
||
};
|
||
const pts = sp.controlPoints || sp.fitPoints;
|
||
if (pts && pts.length >= 2) {
|
||
const transPts = pts.map((p) => applyTransform2D([p.x, p.y], transform));
|
||
for (let s = 0; s < transPts.length - 1; s++) {
|
||
looseLineSegments.push({ p1: transPts[s], p2: transPts[s + 1] });
|
||
}
|
||
}
|
||
} else if (ent.type === "INSERT") {
|
||
const ins = ent as {
|
||
name?: string;
|
||
position?: { x?: number; y?: number; z?: number };
|
||
xScale?: number;
|
||
yScale?: number;
|
||
scale?: { x?: number; y?: number; z?: number };
|
||
rotation?: number;
|
||
};
|
||
const blockName = ins.name;
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
const block = blockName && dxf.blocks ? (dxf.blocks as any)[blockName] : null;
|
||
if (block && Array.isArray(block.entities)) {
|
||
const nextTransform = combineTransforms(transform, {
|
||
x: ins.position?.x ?? 0,
|
||
y: ins.position?.y ?? 0,
|
||
scaleX: ins.xScale ?? ins.scale?.x ?? 1,
|
||
scaleY: ins.yScale ?? ins.scale?.y ?? 1,
|
||
rotationDeg: ins.rotation ?? 0,
|
||
});
|
||
for (const bEnt of block.entities) {
|
||
processEntity(bEnt, nextTransform, depth + 1);
|
||
}
|
||
}
|
||
}
|
||
};
|
||
|
||
const rootTransform = createIdentityTransform();
|
||
for (const ent of entitiesToProcess) {
|
||
processEntity(ent, rootTransform, 0);
|
||
}
|
||
|
||
if (faces3D.length > 0 || closedLoops2D.length > 0 || looseLineSegments.length > 0) {
|
||
return { faces3D, closedLoops2D, looseLineSegments };
|
||
}
|
||
return null;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Parses an AutoCAD DXF file content and creates a solid 3D WorkplaneShape.
|
||
* Handles 3D mesh entities (3DFACE), 2D closed CAD profiles (LWPOLYLINE, CIRCLE, ELLIPSE, SOLID),
|
||
* and loose architectural lines/walls (LINE, ARC, SPLINE, unclosed polylines).
|
||
*/
|
||
export function importedShapeFromDxf(fileName: string, source: string): WorkplaneShape {
|
||
const parsedFromDxfParser = extractEntitiesWithDxfParser(source);
|
||
|
||
let faces3D: Triangle3D[] = [];
|
||
let candidateLoops2D: Point2D[][] = [];
|
||
let looseLineSegments: LineSegment[] = [];
|
||
|
||
if (parsedFromDxfParser) {
|
||
faces3D = parsedFromDxfParser.faces3D;
|
||
candidateLoops2D = parsedFromDxfParser.closedLoops2D;
|
||
looseLineSegments = parsedFromDxfParser.looseLineSegments;
|
||
} else {
|
||
// Fallback low-level DXF pair parser for corrupted or non-standard DXF files
|
||
const pairs = parseDxfPairs(source);
|
||
if (pairs.length === 0) {
|
||
throw new Error("DXF dosyası okunamadı veya dosya boş.");
|
||
}
|
||
|
||
let inEntitiesOrBlocksSection = false;
|
||
let i = 0;
|
||
|
||
while (i < pairs.length) {
|
||
const pair = pairs[i];
|
||
|
||
if (pair.code === 0 && pair.value.toUpperCase() === "SECTION") {
|
||
const next = pairs[i + 1];
|
||
if (
|
||
next &&
|
||
next.code === 2 &&
|
||
(next.value.toUpperCase() === "ENTITIES" || next.value.toUpperCase() === "BLOCKS")
|
||
) {
|
||
inEntitiesOrBlocksSection = true;
|
||
}
|
||
i += 2;
|
||
continue;
|
||
}
|
||
|
||
if (pair.code === 0 && pair.value.toUpperCase() === "ENDSEC") {
|
||
inEntitiesOrBlocksSection = false;
|
||
i += 1;
|
||
continue;
|
||
}
|
||
|
||
if (inEntitiesOrBlocksSection && pair.code === 0) {
|
||
const entityType = pair.value.toUpperCase();
|
||
i += 1;
|
||
|
||
if (entityType === "3DFACE") {
|
||
const v: Array<Point3D> = [
|
||
[0, 0, 0],
|
||
[0, 0, 0],
|
||
[0, 0, 0],
|
||
[0, 0, 0],
|
||
];
|
||
while (i < pairs.length && pairs[i].code !== 0) {
|
||
const { code, value } = pairs[i];
|
||
const val = parseFloat(value) || 0;
|
||
if (code === 10) v[0][0] = val;
|
||
else if (code === 20) v[0][1] = val;
|
||
else if (code === 30) v[0][2] = val;
|
||
else if (code === 11) v[1][0] = val;
|
||
else if (code === 21) v[1][1] = val;
|
||
else if (code === 31) v[1][2] = val;
|
||
else if (code === 12) v[2][0] = val;
|
||
else if (code === 22) v[2][1] = val;
|
||
else if (code === 32) v[2][2] = val;
|
||
else if (code === 13) v[3][0] = val;
|
||
else if (code === 23) v[3][1] = val;
|
||
else if (code === 33) v[3][2] = val;
|
||
i += 1;
|
||
}
|
||
|
||
faces3D.push([v[0], v[1], v[2]]);
|
||
const isQuad =
|
||
Math.abs(v[3][0] - v[2][0]) > 1e-5 ||
|
||
Math.abs(v[3][1] - v[2][1]) > 1e-5 ||
|
||
Math.abs(v[3][2] - v[2][2]) > 1e-5;
|
||
if (isQuad) {
|
||
faces3D.push([v[0], v[2], v[3]]);
|
||
}
|
||
continue;
|
||
}
|
||
|
||
if (entityType === "LWPOLYLINE") {
|
||
const pts: Point2D[] = [];
|
||
let isClosed = false;
|
||
let currentX: number | null = null;
|
||
|
||
while (i < pairs.length && pairs[i].code !== 0) {
|
||
const { code, value } = pairs[i];
|
||
if (code === 70) {
|
||
const flag = parseInt(value, 10);
|
||
if (!isNaN(flag) && (flag & 1) === 1) isClosed = true;
|
||
} else if (code === 10) {
|
||
currentX = parseFloat(value) || 0;
|
||
} else if (code === 20) {
|
||
if (currentX !== null) {
|
||
pts.push([currentX, parseFloat(value) || 0]);
|
||
currentX = null;
|
||
}
|
||
}
|
||
i += 1;
|
||
}
|
||
|
||
if (pts.length >= 3) {
|
||
const d = Math.hypot(
|
||
pts[pts.length - 1][0] - pts[0][0],
|
||
pts[pts.length - 1][1] - pts[0][1],
|
||
);
|
||
if (isClosed || d < 0.2) {
|
||
candidateLoops2D.push(pts);
|
||
} else {
|
||
for (let s = 0; s < pts.length - 1; s++) {
|
||
looseLineSegments.push({ p1: pts[s], p2: pts[s + 1] });
|
||
}
|
||
}
|
||
}
|
||
continue;
|
||
}
|
||
|
||
if (entityType === "LINE") {
|
||
let x1 = 0, y1 = 0, x2 = 0, y2 = 0;
|
||
while (i < pairs.length && pairs[i].code !== 0) {
|
||
const { code, value } = pairs[i];
|
||
const val = parseFloat(value) || 0;
|
||
if (code === 10) x1 = val;
|
||
else if (code === 20) y1 = val;
|
||
else if (code === 11) x2 = val;
|
||
else if (code === 21) y2 = val;
|
||
i += 1;
|
||
}
|
||
if (Math.hypot(x2 - x1, y2 - y1) > 1e-4) {
|
||
looseLineSegments.push({ p1: [x1, y1], p2: [x2, y2] });
|
||
}
|
||
continue;
|
||
}
|
||
|
||
if (entityType === "CIRCLE") {
|
||
let cx = 0, cy = 0, r = 0;
|
||
while (i < pairs.length && pairs[i].code !== 0) {
|
||
const { code, value } = pairs[i];
|
||
const val = parseFloat(value) || 0;
|
||
if (code === 10) cx = val;
|
||
else if (code === 20) cy = val;
|
||
else if (code === 40) r = val;
|
||
i += 1;
|
||
}
|
||
if (r > 0) {
|
||
const circlePts: Point2D[] = [];
|
||
const segments = 36;
|
||
for (let step = 0; step < segments; step++) {
|
||
const angle = (step / segments) * Math.PI * 2;
|
||
circlePts.push([cx + Math.cos(angle) * r, cy + Math.sin(angle) * r]);
|
||
}
|
||
candidateLoops2D.push(circlePts);
|
||
}
|
||
continue;
|
||
}
|
||
|
||
if (entityType === "ARC") {
|
||
let cx = 0, cy = 0, r = 0, startAngle = 0, endAngle = 360;
|
||
while (i < pairs.length && pairs[i].code !== 0) {
|
||
const { code, value } = pairs[i];
|
||
const val = parseFloat(value) || 0;
|
||
if (code === 10) cx = val;
|
||
else if (code === 20) cy = val;
|
||
else if (code === 40) r = val;
|
||
else if (code === 50) startAngle = val;
|
||
else if (code === 51) endAngle = val;
|
||
i += 1;
|
||
}
|
||
if (r > 0) {
|
||
let sRad = (startAngle * Math.PI) / 180;
|
||
let eRad = (endAngle * Math.PI) / 180;
|
||
if (eRad <= sRad) eRad += Math.PI * 2;
|
||
const arcSegments = Math.max(8, Math.round(((eRad - sRad) / (Math.PI * 2)) * 36));
|
||
const arcPts: Point2D[] = [];
|
||
for (let step = 0; step <= arcSegments; step++) {
|
||
const t = step / arcSegments;
|
||
const a = sRad + t * (eRad - sRad);
|
||
arcPts.push([cx + Math.cos(a) * r, cy + Math.sin(a) * r]);
|
||
}
|
||
for (let s = 0; s < arcPts.length - 1; s++) {
|
||
looseLineSegments.push({ p1: arcPts[s], p2: arcPts[s + 1] });
|
||
}
|
||
}
|
||
continue;
|
||
}
|
||
|
||
continue;
|
||
}
|
||
|
||
i += 1;
|
||
}
|
||
}
|
||
|
||
// Chain any connected loose lines into closed loops, while preserving all unclosed lines
|
||
if (looseLineSegments.length > 0) {
|
||
const { closedLoops, unclosedSegments } = chainLineSegmentsPreserving(looseLineSegments, 0.2);
|
||
candidateLoops2D.push(...closedLoops);
|
||
looseLineSegments = unclosedSegments;
|
||
}
|
||
|
||
// Calculate drawing bounding box to scale wall thickness and extrusion height naturally
|
||
let bMinX = Number.POSITIVE_INFINITY;
|
||
let bMaxX = Number.NEGATIVE_INFINITY;
|
||
let bMinY = Number.POSITIVE_INFINITY;
|
||
let bMaxY = Number.NEGATIVE_INFINITY;
|
||
|
||
const update2DBounds = (x: number, y: number) => {
|
||
if (x < bMinX) bMinX = x;
|
||
if (x > bMaxX) bMaxX = x;
|
||
if (y < bMinY) bMinY = y;
|
||
if (y > bMaxY) bMaxY = y;
|
||
};
|
||
|
||
for (const loop of candidateLoops2D) {
|
||
for (const pt of loop) update2DBounds(pt[0], pt[1]);
|
||
}
|
||
for (const seg of looseLineSegments) {
|
||
update2DBounds(seg.p1[0], seg.p1[1]);
|
||
update2DBounds(seg.p2[0], seg.p2[1]);
|
||
}
|
||
|
||
const drawingSpanX = Number.isFinite(bMaxX - bMinX) ? Math.max(0, bMaxX - bMinX) : 0;
|
||
const drawingSpanY = Number.isFinite(bMaxY - bMinY) ? Math.max(0, bMaxY - bMinY) : 0;
|
||
const maxDim = Math.max(drawingSpanX, drawingSpanY);
|
||
|
||
// Extrusion depth and ribbon thickness adapt smoothly to drawing scale
|
||
const extrusionDepth = dxfExtrusionDepthForSpan(maxDim);
|
||
const ribbonHalfWidth = maxDim > 100 ? Math.max(0.3, maxDim * 0.003) : 0.6;
|
||
|
||
// Master collection of raw 3D triangle coordinates [x, y, z] in Three.js space
|
||
const rawTriangles: number[] = [];
|
||
|
||
// --- Source 1: 3D Faces (from 3DFACE entities) ---
|
||
if (faces3D.length > 0) {
|
||
for (const [v1, v2, v3] of faces3D) {
|
||
rawTriangles.push(v1[0], v1[1], v1[2]);
|
||
rawTriangles.push(v2[0], v2[1], v2[2]);
|
||
rawTriangles.push(v3[0], v3[1], v3[2]);
|
||
}
|
||
}
|
||
|
||
// --- Source 2: 2D Closed Loops (Solid profiles, room boundaries, columns) ---
|
||
if (candidateLoops2D.length > 0) {
|
||
const validClosedLoops: { points: Point2D[]; area: number }[] = [];
|
||
for (const loop of candidateLoops2D) {
|
||
const area = Math.abs(signedPolygonArea(loop));
|
||
if (area > 0.001) {
|
||
validClosedLoops.push({ points: loop, area });
|
||
} else {
|
||
// Loops with degenerate area are kept as lines so geometry is never lost
|
||
for (let i = 0; i < loop.length; i++) {
|
||
looseLineSegments.push({ p1: loop[i], p2: loop[(i + 1) % loop.length] });
|
||
}
|
||
}
|
||
}
|
||
|
||
validClosedLoops.sort((a, b) => b.area - a.area);
|
||
|
||
if (validClosedLoops.length > 0) {
|
||
const threeShapes: THREE.Shape[] = [];
|
||
const usedAsHole = new Set<number>();
|
||
|
||
for (let oIdx = 0; oIdx < validClosedLoops.length; oIdx++) {
|
||
if (usedAsHole.has(oIdx)) continue;
|
||
const outer = validClosedLoops[oIdx];
|
||
const shape = new THREE.Shape();
|
||
const first = outer.points[0];
|
||
shape.moveTo(first[0], first[1]);
|
||
for (let p = 1; p < outer.points.length; p++) {
|
||
shape.lineTo(outer.points[p][0], outer.points[p][1]);
|
||
}
|
||
shape.closePath();
|
||
|
||
for (let hIdx = oIdx + 1; hIdx < validClosedLoops.length; hIdx++) {
|
||
if (usedAsHole.has(hIdx)) continue;
|
||
const candidateHole = validClosedLoops[hIdx];
|
||
if (pointInPolygon(candidateHole.points[0], outer.points)) {
|
||
const holePath = new THREE.Path();
|
||
holePath.moveTo(candidateHole.points[0][0], candidateHole.points[0][1]);
|
||
for (let hp = 1; hp < candidateHole.points.length; hp++) {
|
||
holePath.lineTo(candidateHole.points[hp][0], candidateHole.points[hp][1]);
|
||
}
|
||
holePath.closePath();
|
||
shape.holes.push(holePath);
|
||
usedAsHole.add(hIdx);
|
||
}
|
||
}
|
||
|
||
threeShapes.push(shape);
|
||
}
|
||
|
||
for (const shape of threeShapes) {
|
||
try {
|
||
const geom = new THREE.ExtrudeGeometry(shape, {
|
||
depth: extrusionDepth,
|
||
bevelEnabled: false,
|
||
curveSegments: 16,
|
||
});
|
||
geom.rotateX(-Math.PI / 2);
|
||
const nonIndexed = geom.index ? geom.toNonIndexed() : geom;
|
||
const posAttr = nonIndexed.getAttribute("position");
|
||
if (posAttr && posAttr.count > 0) {
|
||
for (let p = 0; p < posAttr.count; p++) {
|
||
rawTriangles.push(posAttr.getX(p), posAttr.getY(p), posAttr.getZ(p));
|
||
}
|
||
}
|
||
if (nonIndexed !== geom) nonIndexed.dispose();
|
||
geom.dispose();
|
||
} catch {
|
||
// If Three.js ExtrudeGeometry fails on self-intersecting polygon,
|
||
// preserve all shape edges as lines so they render reliably
|
||
const pts = shape.getPoints();
|
||
for (let s = 0; s < pts.length - 1; s++) {
|
||
looseLineSegments.push({
|
||
p1: [pts[s].x, pts[s].y],
|
||
p2: [pts[s + 1].x, pts[s + 1].y],
|
||
});
|
||
}
|
||
for (const hole of shape.holes) {
|
||
const hPts = hole.getPoints();
|
||
for (let s = 0; s < hPts.length - 1; s++) {
|
||
looseLineSegments.push({
|
||
p1: [hPts[s].x, hPts[s].y],
|
||
p2: [hPts[s + 1].x, hPts[s + 1].y],
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// --- Source 3: Loose Line Segments (Open architectural walls, schematics, line drawings) ---
|
||
if (looseLineSegments.length > 0) {
|
||
for (const seg of looseLineSegments) {
|
||
const dx = seg.p2[0] - seg.p1[0];
|
||
const dy = seg.p2[1] - seg.p1[1];
|
||
const len = Math.hypot(dx, dy);
|
||
if (len < 1e-4) continue;
|
||
|
||
const nx = (-dy / len) * ribbonHalfWidth;
|
||
const ny = (dx / len) * ribbonHalfWidth;
|
||
|
||
// 4 corners of bottom face (Y = 0) with CAD (x, y) -> Three.js (x, -y)
|
||
const b1: Point3D = [seg.p1[0] - nx, 0, -(seg.p1[1] - ny)];
|
||
const b2: Point3D = [seg.p1[0] + nx, 0, -(seg.p1[1] + ny)];
|
||
const b3: Point3D = [seg.p2[0] + nx, 0, -(seg.p2[1] + ny)];
|
||
const b4: Point3D = [seg.p2[0] - nx, 0, -(seg.p2[1] - ny)];
|
||
|
||
// 4 corners of top face (Y = extrusionDepth)
|
||
const t1: Point3D = [seg.p1[0] - nx, extrusionDepth, -(seg.p1[1] - ny)];
|
||
const t2: Point3D = [seg.p1[0] + nx, extrusionDepth, -(seg.p1[1] + ny)];
|
||
const t3: Point3D = [seg.p2[0] + nx, extrusionDepth, -(seg.p2[1] + ny)];
|
||
const t4: Point3D = [seg.p2[0] - nx, extrusionDepth, -(seg.p2[1] - ny)];
|
||
|
||
const addQuad = (p1: Point3D, p2: Point3D, p3: Point3D, p4: Point3D) => {
|
||
rawTriangles.push(p1[0], p1[1], p1[2], p2[0], p2[1], p2[2], p3[0], p3[1], p3[2]);
|
||
rawTriangles.push(p1[0], p1[1], p1[2], p3[0], p3[1], p3[2], p4[0], p4[1], p4[2]);
|
||
};
|
||
|
||
// Top face
|
||
addQuad(t1, t2, t3, t4);
|
||
// Bottom face
|
||
addQuad(b4, b3, b2, b1);
|
||
// Side 1
|
||
addQuad(b1, t1, t4, b4);
|
||
// Side 2
|
||
addQuad(b3, t3, t2, b2);
|
||
// End 1
|
||
addQuad(b2, t2, t1, b1);
|
||
// End 2
|
||
addQuad(b4, t4, t3, b3);
|
||
}
|
||
}
|
||
|
||
if (rawTriangles.length === 0) {
|
||
throw new Error(
|
||
"DWG/DXF dosyasında katı 3B modele dönüştürülebilecek herhangi bir çizim çizgisi veya geometri bulunamadı.",
|
||
);
|
||
}
|
||
|
||
// Calculate 3D bounding box for centering and positioning on workplane
|
||
let minX = Number.POSITIVE_INFINITY,
|
||
minY = Number.POSITIVE_INFINITY,
|
||
minZ = Number.POSITIVE_INFINITY;
|
||
let maxX = Number.NEGATIVE_INFINITY,
|
||
maxY = Number.NEGATIVE_INFINITY,
|
||
maxZ = Number.NEGATIVE_INFINITY;
|
||
|
||
for (let p = 0; p < rawTriangles.length; p += 3) {
|
||
minX = Math.min(minX, rawTriangles[p]);
|
||
maxX = Math.max(maxX, rawTriangles[p]);
|
||
minY = Math.min(minY, rawTriangles[p + 1]);
|
||
maxY = Math.max(maxY, rawTriangles[p + 1]);
|
||
minZ = Math.min(minZ, rawTriangles[p + 2]);
|
||
maxZ = Math.max(maxZ, rawTriangles[p + 2]);
|
||
}
|
||
|
||
const width = Math.max(0.1, maxX - minX);
|
||
const height = Math.max(0.1, maxY - minY);
|
||
const depth = Math.max(0.1, maxZ - minZ);
|
||
const centerX = (minX + maxX) / 2;
|
||
const centerZ = (minZ + maxZ) / 2;
|
||
|
||
const positions: number[] = [];
|
||
for (let p = 0; p < rawTriangles.length; p += 3) {
|
||
positions.push(
|
||
rawTriangles[p] - centerX,
|
||
rawTriangles[p + 1] - minY,
|
||
rawTriangles[p + 2] - centerZ,
|
||
);
|
||
}
|
||
|
||
const geom = new THREE.BufferGeometry();
|
||
geom.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
|
||
geom.computeVertexNormals();
|
||
const normAttr = geom.getAttribute("normal");
|
||
const normals: number[] = [];
|
||
for (let n = 0; n < normAttr.count; n++) {
|
||
normals.push(normAttr.getX(n), normAttr.getY(n), normAttr.getZ(n));
|
||
}
|
||
geom.dispose();
|
||
|
||
const isLarge = source.length > 2048;
|
||
const dxfPayload = isLarge
|
||
? { sourceDxfCompressed: compressDxfText(source) }
|
||
: { sourceDxfText: source };
|
||
|
||
return {
|
||
id: createLocalId("uploaded-dxf"),
|
||
name: fileName.replace(/\.[^.]+$/, "") || "İçe Aktarılan DWG/DXF Pafta",
|
||
kind: "mesh",
|
||
color: "#0284c7",
|
||
x: 0,
|
||
z: 0,
|
||
size: Math.max(width, depth),
|
||
width,
|
||
depth,
|
||
height,
|
||
rotation: 0,
|
||
rotationX: 0,
|
||
rotationZ: 0,
|
||
importedMesh: {
|
||
positions,
|
||
normals,
|
||
baseWidth: width,
|
||
baseDepth: depth,
|
||
baseHeight: height,
|
||
triangleCount: positions.length / 9,
|
||
sourceFormat: "dxf",
|
||
...dxfPayload,
|
||
},
|
||
locked: false,
|
||
hidden: false,
|
||
};
|
||
}
|