Files
Aislo/B07_DesignDetail/openwebcad/src/helpers/geometry/sample-entity.ts
T
eomsangdonandClaude Opus 5 4cb9b15939 style: 저장소 전체 포맷터 일괄 적용 (prettier·biome·ruff)
파일마다 포맷 폭이 달라(≈80 대 100) 한 줄만 고쳐도 포맷터가 무관한 줄을 대량
재포맷했음. 사용자 지시로 전체를 한 번에 맞춤. 코드 동작 변경 없음 — 포맷만.

- 프론트엔드 `.ts/.css/.html` → 저장소 prettier (`.prettierrc`, printWidth 100)
- `B07_DesignDetail/openwebcad/**` → 자체 biome (tab 들여쓰기·single quote·lineWidth 100).
  `biome format` 만 사용 — `biome lint --write` 는 포맷 아닌 코드 수정까지 하므로 제외
- 파이썬 → `ruff format` (엔진 코드는 이미 정합, resources·scratch 스크립트 24개만 변경)

두 포맷터가 서로 되돌리지 않도록 `.prettierignore` 신규 — openwebcad 와 빌드·산출물
폴더를 prettier 대상에서 뺌. `.prettierrc` 에 `endOfLine: "auto"` 추가 — 기본값 `lf` 가
`core.autocrlf=true` 로 받은 CRLF 파일을 매번 전부 다시 써서 `--list-different` 가
실제 포맷 차이를 가리고 있었음.

검증: `tsc --noEmit` 통과(루트·openwebcad 둘 다), pytest 349 passed / 17 skipped /
0 failed, CAD vitest 87건 중 81 passed / 6 failed(laptop-sub 기준선과 동일, 회귀 없음).
포맷터 재실행 시 prettier·biome 모두 변경 0건.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 07:08:24 +09:00

127 lines
4.7 KiB
TypeScript

/**
* 엔티티를 점렬(폴리라인)로 펴는 순수 함수들.
* 등분(DIVIDE)·길이분할(MEASURE)·경계(BOUNDARY)·해치가 모두 이 표현을 공유한다.
*/
import { Arc, Circle, Point, Polygon, Segment } from '@flatten-js/core';
import type { Entity } from '../../entities/Entity';
import { EntityName } from '../../entities/Entity';
import type { PolyLineEntity } from '../../entities/PolyLineEntity';
import { polygonToSegments } from '../polygon-to-segments';
const CURVE_SEGMENTS = 64;
/** 두 점이 사실상 같은 위치인지 (좌표 오차 허용) */
const samePoint = (a: Point, b: Point, tolerance = 1e-6): boolean =>
Math.abs(a.x - b.x) <= tolerance && Math.abs(a.y - b.y) <= tolerance;
function sampleArc(arc: Arc, segments: number): Point[] {
const points: Point[] = [];
const sweep = arc.sweep * (arc.counterClockwise ? 1 : -1);
// flatten-js 타입 선언이 반지름을 Number 객체로 잡아 두어 숫자로 되돌린다
const radius = Number(arc.r);
for (let index = 0; index <= segments; index++) {
const angle = arc.startAngle + (sweep * index) / segments;
points.push(
new Point(arc.center.x + radius * Math.cos(angle), arc.center.y + radius * Math.sin(angle))
);
}
return points;
}
function sampleCircle(circle: Circle, segments: number): Point[] {
const points: Point[] = [];
for (let index = 0; index <= segments; index++) {
const angle = (2 * Math.PI * index) / segments;
points.push(
new Point(
circle.center.x + circle.r * Math.cos(angle),
circle.center.y + circle.r * Math.sin(angle)
)
);
}
return points;
}
/** 이어지는 중복점을 제거한다 (폴리선 이음매에서 생긴다) */
export function dedupeConsecutive(points: Point[]): Point[] {
return points.filter((point, index) => index === 0 || !samePoint(point, points[index - 1]));
}
/** 엔티티 하나를 점렬로 편다. 곡선은 curveSegments 등분해 근사한다. */
export function sampleEntityPoints(entity: Entity, curveSegments = CURVE_SEGMENTS): Point[] {
if (entity.getType() === EntityName.PolyLine) {
const children = (entity as PolyLineEntity).getEntities();
return dedupeConsecutive(children.flatMap((child) => sampleEntityPoints(child, curveSegments)));
}
const shape = entity.getShape();
if (shape instanceof Segment) return [shape.start, shape.end];
if (shape instanceof Arc) return sampleArc(shape, curveSegments);
if (shape instanceof Circle) return sampleCircle(shape, curveSegments);
if (shape instanceof Polygon) {
const segments = polygonToSegments(shape);
return dedupeConsecutive([
...segments.map((segment) => segment.start),
...(segments.length ? [segments[segments.length - 1].end] : []),
]);
}
if (shape instanceof Point) return [shape];
return [];
}
/** 점렬의 누적 길이 */
export function polylineLengths(points: Point[]): number[] {
const lengths = [0];
for (let index = 1; index < points.length; index++) {
lengths.push(lengths[index - 1] + points[index - 1].distanceTo(points[index])[0]);
}
return lengths;
}
export const polylineLength = (points: Point[]): number => {
const lengths = polylineLengths(points);
return lengths[lengths.length - 1] ?? 0;
};
/** 시작점에서 distance만큼 진행한 위치 (길이를 넘으면 null) */
export function pointAtDistance(points: Point[], distance: number): Point | null {
if (points.length < 2) return null;
const lengths = polylineLengths(points);
const total = lengths[lengths.length - 1];
if (distance < 0 || distance > total) return null;
for (let index = 1; index < points.length; index++) {
if (lengths[index] >= distance) {
const segmentLength = lengths[index] - lengths[index - 1];
const ratio = segmentLength === 0 ? 0 : (distance - lengths[index - 1]) / segmentLength;
const start = points[index - 1];
const end = points[index];
return new Point(start.x + (end.x - start.x) * ratio, start.y + (end.y - start.y) * ratio);
}
}
return points[points.length - 1];
}
/** DIVIDE — 객체를 count 등분하는 내부 점 (count-1개) */
export function dividePoints(points: Point[], count: number): Point[] {
if (count < 2) return [];
const total = polylineLength(points);
const result: Point[] = [];
for (let index = 1; index < count; index++) {
const point = pointAtDistance(points, (total * index) / count);
if (point) result.push(point);
}
return result;
}
/** MEASURE — 시작점에서 spacing 간격마다 찍는 점 */
export function measurePoints(points: Point[], spacing: number): Point[] {
if (spacing <= 0) return [];
const total = polylineLength(points);
const result: Point[] = [];
for (let distance = spacing; distance <= total + 1e-9; distance += spacing) {
const point = pointAtDistance(points, Math.min(distance, total));
if (point) result.push(point);
}
return result;
}