All files / lib/services/base dxf.service.ts

95.48% Statements 127/133
89.28% Branches 50/56
100% Functions 7/7
96.92% Lines 126/130

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353                                                  14x   14x   14x   15x   15x         15x   15x   15x 15x 15x     15x 6x 6x 6x   6x 1x 1x 1x       1x 1x         14x 14x 14x 14x 14x               15x 15x           14x               1x                       1x         1x 1x                           14x 14x 14x   14x 43x 43x 43x     43x 11x 11x 11x         43x 43x   43x   25x 25x 18x   11x             11x 11x         11x     11x 11x 11x       11x 11x     11x 11x         11x   7x     4x           11x 11x     7x                       7x 189x 189x       43x       14x 6x 6x 6x 6x       14x       14x           14x                             14x     14x 14x   14x 1x       13x 3x 3x 3x 3x 1x         12x 12x 12x   12x 28x 28x 28x     28x 1x       27x 5x 5x 5x 1x       26x 26x   26x   22x     4x 4x     4x 4x   4x     4x 4x     4x 4x     26x       12x 12x 12x 12x 12x       12x 1x     11x           11x              
import {
    TopoDS_Edge, TopoDS_Shape
} from "../../../bitbybit-dev-occt/bitbybit-dev-occt";
import * as Inputs from "../../api/inputs/inputs";
import { Base } from "../../api/inputs/inputs";
import { IO } from "@bitbybit-dev/base/lib/api/inputs/io-inputs";
import { EdgesService } from "./edges.service";
import { ShapeGettersService } from "./shape-getters";
import { BaseBitByBit } from "../../base";
import { WiresService } from "./wires.service";
export class DxfService {
 
    constructor(
        private readonly base: BaseBitByBit,
        private readonly shapeGettersService: ShapeGettersService,
        private readonly edgesService: EdgesService,
        private readonly wiresService: WiresService,
    ) { }
 
    /**
     * Step 1: Convert OCCT shape to DXF paths (without layer/color info)
     * This analyzes the shape geometry and creates appropriate DXF segments
     */
    shapeToDxfPaths(inputs: Inputs.OCCT.ShapeToDxfPathsDto<TopoDS_Shape>): IO.DxfPathDto[] {
        // Get all wires from the shape
        const wires = this.shapeGettersService.getWires({ shape: inputs.shape });
        
        const paths: IO.DxfPathDto[] = [];
 
        wires.forEach(wire => {
            // Get edges along the wire in order with consistent direction
            const edges = this.edgesService.getEdgesAlongWire({ shape: wire });
            
            Iif (edges.length === 0) {
                return;
            }
 
            // Check if the entire wire is closed once at the beginning
            const isWireClosed = this.wiresService.isWireClosed({ shape: wire });
 
            const segments: (IO.DxfLineSegmentDto | IO.DxfArcSegmentDto | IO.DxfCircleSegmentDto | IO.DxfPolylineSegmentDto)[] = [];
            
            let i = 0;
            while (i < edges.length) {
                const edge = edges[i];
                
                // Check if edge is a full circle - handle separately
                if (this.edgesService.isEdgeCircular({ shape: edge })) {
                    const bounds = this.edgesService.getEdgeBounds(edge);
                    const angleRange = bounds.uMax - bounds.uMin;
                    const isFullCircle = Math.abs(angleRange - 2 * Math.PI) < 0.01;
                    
                    if (isFullCircle) {
                        const circle = this.edgesService.getCircularEdgeCenterPoint({ shape: edge });
                        const radius = this.edgesService.getCircularEdgeRadius({ shape: edge });
                        segments.push({
                            center: [circle[0], circle[2]], // XZ plane (remove Y)
                            radius: radius
                        });
                        i++;
                        continue;
                    }
                }
                
                // Try to collect all edges (linear, arc, and complex) into a unified polyline with bulges
                const polylineResult = this.tryCreateUnifiedPolyline(edges, i, inputs, isWireClosed && i === 0);
                Eif (polylineResult) {
                    segments.push(polylineResult.polyline);
                    i = polylineResult.nextIndex;
                    continue;
                }
                
                // Fallback: shouldn't reach here normally
                i++;
            }
            
            // Create path from segments
            Eif (segments.length > 0) {
                paths.push({
                    segments: segments
                });
            }
        });
 
        return paths;
    }
 
    /**
     * Step 2: Add layer and color information to DXF paths
     * Takes paths from shapeToDxfPaths and adds styling
     */
    dxfPathsWithLayer(inputs: Inputs.OCCT.DxfPathsWithLayerDto): IO.DxfPathsPartDto {
        return {
            layer: inputs.layer,
            color: inputs.color,
            paths: inputs.paths
        };
    }
 
    /**
     * Step 3: Assemble multiple path parts into a complete DXF file
     * Takes multiple outputs from dxfPathsWithLayer and creates final DXF
     */
    dxfCreate(inputs: Inputs.OCCT.DxfPathsPartsListDto): string {
        const model = {
            dxfPathsParts: inputs.pathsParts,
            colorFormat: inputs.colorFormat as "aci" | "truecolor",
            acadVersion: inputs.acadVersion as "AC1009" | "AC1015"
        } as IO.DxfModelDto;
        const dxfContent = this.base.io.dxf.dxfCreate(model);
        return dxfContent;
    }
 
    /**
     * Try to create a unified polyline from consecutive edges (linear, arc, and complex)
     * This creates a single LWPOLYLINE with bulges where applicable
     */
    private tryCreateUnifiedPolyline(
        edges: TopoDS_Edge[],
        startIndex: number,
        inputs: Inputs.OCCT.ShapeToDxfPathsDto<TopoDS_Shape>,
        shouldBeClosed: boolean
    ): { polyline: IO.DxfPolylineSegmentDto, nextIndex: number } | null {
        
        const points: Base.Point2[] = [];
        const bulges: number[] = [];
        let j = startIndex;
        
        while (j < edges.length) {
            const currentEdge = edges[j];
            const isLinear = this.edgesService.isEdgeLinear({ shape: currentEdge });
            const isCircular = this.edgesService.isEdgeCircular({ shape: currentEdge });
            
            // Check if it's a full circle - stop here
            if (isCircular) {
                const bounds = this.edgesService.getEdgeBounds(currentEdge);
                const angleRange = bounds.uMax - bounds.uMin;
                Iif (Math.abs(angleRange - 2 * Math.PI) < 0.01) {
                    break; // Full circle, handle separately
                }
            }
            
            const startPt = this.edgesService.startPointOnEdge({ shape: currentEdge });
            const endPt = this.edgesService.endPointOnEdge({ shape: currentEdge });
            
            if (isLinear) {
                // Linear edge: add start point with bulge 0
                points.push([startPt[0], startPt[2]]);
                bulges.push(0);
            } else if (isCircular) {
                // Arc edge: add start point with calculated bulge
                points.push([startPt[0], startPt[2]]);
                
                // DXF bulge is the tangent of 1/4 of the included angle
                // Positive bulge = arc curves to the left when traveling from start to end (CCW)
                // Negative bulge = arc curves to the right when traveling from start to end (CW)
                
                // Sample a point in the middle of the arc to determine direction
                const midParam = 0.5; // Middle of the arc
                const midPt3d = this.edgesService.pointOnEdgeAtParam({ shape: currentEdge, param: midParam });
                
                // Calculate the included angle from the actual arc geometry
                // We map from 3D (X,Y,Z) to 2D DXF (X,Y) by dropping the Y coordinate
                // So: 3D X → DXF X, 3D Z → DXF Y
                const center = this.edgesService.getCircularEdgeCenterPoint({ shape: currentEdge });
                
                // Calculate angles in the 2D projection (XZ plane → XY in DXF)
                const startAngle = Math.atan2(startPt[2] - center[2], startPt[0] - center[0]);
                const midAngle = Math.atan2(midPt3d[2] - center[2], midPt3d[0] - center[0]);
                const endAngle = Math.atan2(endPt[2] - center[2], endPt[0] - center[0]);
                
                // Calculate the included angle by checking which direction the arc actually goes
                // We use the midpoint to determine if we're going CCW or CW
                let angle1 = endAngle - startAngle;
                let angle2 = midAngle - startAngle;
                
                // Normalize angles to [-π, π] using modulo arithmetic
                angle1 = Math.atan2(Math.sin(angle1), Math.cos(angle1));
                angle2 = Math.atan2(Math.sin(angle2), Math.cos(angle2));
                
                // Check if midpoint is on the path from start to end
                // Both should have the same sign and mid should be about half of end
                let includedAngle: number;
                if (Math.sign(angle1) === Math.sign(angle2) && Math.abs(angle2) < Math.abs(angle1) + 0.1) {
                    // Midpoint is on the short arc from start to end
                    includedAngle = angle1;
                } else {
                    // Midpoint is on the long arc, so we go the other way
                    includedAngle = angle1 > 0 ? angle1 - 2 * Math.PI : angle1 + 2 * Math.PI;
                }
                
                // The bulge is tan(included_angle / 4)
                // Positive angle = CCW = positive bulge (arc curves left)
                // Negative angle = CW = negative bulge (arc curves right)
                const bulge = Math.tan(includedAngle / 4);
                bulges.push(bulge);
            } else {
                // Complex edge: tessellate and add points with bulge 0
                const points3d = this.edgesService.edgeToPoints({
                    shape: currentEdge,
                    angularDeflection: inputs.angularDeflection,
                    curvatureDeflection: inputs.curvatureDeflection,
                    minimumOfPoints: inputs.minimumOfPoints,
                    uTolerance: inputs.uTolerance,
                    minimumLength: inputs.minimumLength
                });
                
                // Add all tessellation points except the last one for all edges
                // The last point of each edge will be the start point of the next edge
                // For closed wires, the last edge's last point equals the first edge's first point
                for (let k = 0; k < points3d.length - 1; k++) {
                    points.push([points3d[k][0], points3d[k][2]]);
                    bulges.push(0);
                }
            }
            
            j++;
        }
        
        // Add the final endpoint for open polylines
        if (j > startIndex && !shouldBeClosed) {
            const lastEdge = edges[j - 1];
            const endPt = this.edgesService.endPointOnEdge({ shape: lastEdge });
            points.push([endPt[0], endPt[2]]);
            bulges.push(0);
        }
        
        // Return null if we didn't process any edges
        Iif (j <= startIndex || points.length < 2) {
            return null;
        }
        
        const polyline: IO.DxfPolylineSegmentDto = {
            points: points,
            closed: shouldBeClosed,
            bulges: bulges
        };
        
        return {
            polyline: polyline,
            nextIndex: j
        };
    }
 
    /**
     * Try to create a polyline with bulges from consecutive line/arc segments
     * Returns the polyline and next index, or null if not applicable
     */
    private tryCreatePolylineWithBulges(
        edges: TopoDS_Edge[],
        startIndex: number,
        shouldBeClosed: boolean
    ): { polyline: IO.DxfPolylineSegmentDto, nextIndex: number } | null {
        const edge = edges[startIndex];
        
        // Must start with either a line or an arc (not a full circle)
        const isLinear = this.edgesService.isEdgeLinear({ shape: edge });
        const isCircular = this.edgesService.isEdgeCircular({ shape: edge });
        
        if (!isLinear && !isCircular) {
            return null; // Complex edge, can't create polyline with bulges
        }
        
        // Check if it's a full circle
        if (isCircular) {
            const bounds = this.edgesService.getEdgeBounds(edge);
            const angleRange = bounds.uMax - bounds.uMin;
            const isFullCircle = Math.abs(angleRange - 2 * Math.PI) < 0.01;
            if (isFullCircle) {
                return null; // Full circle, handle separately
            }
        }
        
        // Collect consecutive linear and arc edges
        const points: Base.Point2[] = [];
        const bulges: number[] = [];
        let j = startIndex;
        
        while (j < edges.length) {
            const currentEdge = edges[j];
            const isCurrentLinear = this.edgesService.isEdgeLinear({ shape: currentEdge });
            const isCurrentCircular = this.edgesService.isEdgeCircular({ shape: currentEdge });
            
            // Stop if we hit a complex edge
            if (!isCurrentLinear && !isCurrentCircular) {
                break;
            }
            
            // Stop if we hit a full circle
            if (isCurrentCircular) {
                const bounds = this.edgesService.getEdgeBounds(currentEdge);
                const angleRange = bounds.uMax - bounds.uMin;
                if (Math.abs(angleRange - 2 * Math.PI) < 0.01) {
                    break;
                }
            }
            
            const startPt = this.edgesService.startPointOnEdge({ shape: currentEdge });
            points.push([startPt[0], startPt[2]]); // XZ plane
            
            if (isCurrentLinear) {
                // Linear segment: bulge = 0
                bulges.push(0);
            } else {
                // Arc segment: calculate bulge
                const endPt = this.edgesService.endPointOnEdge({ shape: currentEdge });
                const center = this.edgesService.getCircularEdgeCenterPoint({ shape: currentEdge });
                
                // Calculate the included angle using the actual arc geometry
                const startAngle = Math.atan2(startPt[2] - center[2], startPt[0] - center[0]);
                const endAngle = Math.atan2(endPt[2] - center[2], endPt[0] - center[0]);
                
                let includedAngle = endAngle - startAngle;
                
                // Normalize to [-2π, 2π]
                while (includedAngle > Math.PI) includedAngle -= 2 * Math.PI;
                while (includedAngle < -Math.PI) includedAngle += 2 * Math.PI;
                
                // Bulge = tan(included_angle / 4)
                const bulge = Math.tan(includedAngle / 4);
                bulges.push(bulge);
            }
            
            j++;
        }
        
        // Add the end point of the last edge
        Eif (j > startIndex) {
            const lastEdge = edges[j - 1];
            const endPt = this.edgesService.endPointOnEdge({ shape: lastEdge });
            points.push([endPt[0], endPt[2]]); // XZ plane
            bulges.push(0); // Last vertex doesn't need a bulge
        }
        
        // Only create polyline with bulges if we have at least 2 edges or if it's beneficial
        if (j - startIndex < 2) {
            return null; // Not enough edges to justify polyline
        }
        
        const polyline: IO.DxfPolylineSegmentDto = {
            points: points,
            closed: shouldBeClosed,
            bulges: bulges
        };
        
        return {
            polyline: polyline,
            nextIndex: j
        };
    }
 
}