Skip to content
프로젝트

소개

TypeScript computational geometry for Web3D editors. Unified queries, mesh tools, and zero runtime dependencies. | 面向 Web3D 编辑器的 TypeScript 计算几何库。统一查询、网格工具,核心零运行时依赖。

과학 및 공학

이 수치를 측정하는 방법

측정된 스타 증가

in 24h
0
in 7 days
0
in 15 days
0
in 1 month
기록 수집 중

서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.

README.md

Original

@@file readme.md

cga.js

English · 简体中文

Computational geometry for JavaScript and TypeScript. Unified data structures for distances, closest points, intersections, polygon booleans, triangulation, point clouds and path meshes, plus decimal CSG, IK, GIS and optional Three.js / GLSL adapters.

npm CI License: MIT

Quick start · Playground · Gallery · API · Roadmap · Contributing

0.1.5 ensures npm uses the full English README, alongside complete Chinese documentation. All computation kernels are internal TypeScript with zero core runtime dependencies. The release status records published versions, tags and deployment receipts.

See it in action

These images are captured from the actual running examples. Open a scene to reproduce its parameters; the gallery also includes full screenshots with controls, legends and computed results.

Distances and closest points Concave polygons with multiple holes
Capsule and triangle distance Concave polygon triangulation
Hollow profiles and path sweeps High-precision solid booleans
Hollow closed-path sweep CSG difference
Constrained inverse kinematics GIS globe tiles
Hinge-constrained IK Globe terrain tiles

94 interactive cases · 184 public entry mappings · 225 ordered pairs across 15 geometry types. These figures describe examples and entry coverage; method-level coverage is tracked separately. Analytical, reference and degeneracy tests check numerical behavior.

All 14 illustrated scenes · Example coverage · Reproduce screenshots

Installation and quick start

npm install @xort/cga

Distance, closest points and parameters

// example:distance
import { v3, segment, distance, intersects } from '@xort/cga';

const point = v3(1, 2, 0);
const edge = segment(v3(0, 0, 0), v3(4, 0, 0));
const result = distance(point, edge);

console.log(result.distance);                 // 2
console.log(result.distanceSqr);              // 4
console.log(result.closests.map(p => p.toArray())); // [[1, 2, 0], [1, 0, 0]]
console.log(result.parameters);               // [0, 0.25]
console.log(intersects(point, edge));         // false
console.log(point.queryDistance(edge).distance); // 2

distance(a, b) and a.queryDistance(b) return the same result contract. Vec3.distanceTo(otherPoint) returns a numeric point-to-point distance.

CommonJS

// example:commonjs
const { v3, segment, distance } = require('@xort/cga');
const result = distance(v3(1, 2, 0), segment(v3(), v3(4, 0, 0)));
console.log(result.distance); // 2

Independent copies and serialization

// example:serialization
import { Triangle, geometryFromJSON, v3 } from '@xort/cga';

const original = new Triangle(v3(), v3(2, 0, 0), v3(0, 2, 0));
const clone = original.clone();
const restored = geometryFromJSON(JSON.parse(JSON.stringify(original)));
original[0].x = 3;
console.log(clone[0].x, restored[0].x); // 0, 0; coordinates are independent

Internal TypeScript polygon kernels

// example:polygon
import { v3, triangulation, clipPolygons } from '@xort/cga';

const outer = [v3(-2,-2,0), v3(2,-2,0), v3(2,2,0), v3(-2,2,0)];
const hole = [v3(-.5,-.5,0), v3(.5,-.5,0), v3(.5,.5,0), v3(-.5,.5,0)];
const vertices = [...outer, ...hole];
const indices = triangulation(outer, [hole]);
console.log(vertices.length, indices.length / 3); // 8 vertices, 8 triangles

const contours = clipPolygons([outer], [hole], 'difference', v3(0,0,1));
console.log(contours.length); // 2; boundary and hole have opposite winding

Triangulation, clipping, offsetting and cleanup use maintained internal TypeScript kernels. See polygon kernels for input restrictions, precision and complexity.

Algorithms and runnable examples

Area Examples Capabilities
Geometry queries Distance and intersection Closest points, parameters, reciprocal queries, tolerance-based intersection
Arcs and disks Directed arcs Angular bounds, endpoint constraints, numerical error bounds
Polygon booleans Topology changes Intersection, union, difference, XOR, holes and shared edges
Offsets and strokes Diagonal caps Miter/round/square joins and butt/round/square caps
Triangulation Concave boundary with holes 3D plane projection, original vertex indices, multiple holes
Delaunay / Voronoi Triangles · Cells and neighbors Planar triangulation, clipped cells and adjacency
Point clouds 3D hull · Closest pair Affine degeneracy, outward faces and exact closest pairs
Curves and paths Catmull–Rom · Path distance Parameterization, accumulated distance, slicing and sampling
Extrusion and meshes Hollow sweeps Transported frames, joins, caps, UVs and normals
Plane cutting Volume conservation Separate halves, interpolated attributes and multi-ring caps
Spatial structures KdTree · QuadTree · Frustum Neighbors, ranges, partitions, culling and clipping
Precision and CSG Projection · Solid difference Decimal vectors, planes and BSP booleans
IK CCD · Hinge · Slider Target solving, accumulated limits, convergence and bone lengths
GIS Coordinates · Geodesics · Terrain ECEF/WGS84, tiles, imagery, terrain and tasks
Rendering and GLSL Viewer · Noise Optional Three.js, materials, noise and distance fields

Unified data structures and interfaces

The 15 geometry types are Point / Vec3, Line, Ray, Segment, Plane, Triangle, Rectangle, Circle, Disk, Sphere, Capsule, Box, Polyline, Polygon and Shape.

  • Geometries share kind, copy, clone, distancePoint, queryDistance and toJSON. geometryFromJSON validates and restores data.
  • Distance results always include distance / distanceSqr / closests / parameters, ordered as [a, b]. Iterative curved queries can report errorBound.
  • Constructors and clones own their coordinates; queries preserve inputs. Fixed-arity objects support indexing and iteration without resizing.
  • Mesh algorithms use IGeometry: position:number[], optional index / normal / uv / uv2 / tangent. Indices are local to the returned vertex array.
  • Shape retains holes for queries, triangulation and serialization.

Conventions

Item Contract
Line Line(origin, end) takes two points
Ray Ray(origin, direction) takes an origin and a direction
Segment Parameter interval is [0, 1]
Plane normal · point + w = 0; numeric signed distance has its own method
Circle / Disk Circle is a circumference or directed arc; Disk is a filled surface
Polygon Filled planar region; clean self-intersections first, and keep triangulation holes separate
Units Caller-defined model units; GIS uses radians internally and WGS84 heights in meters
Resources Dispose viewers and effects explicitly; the host owns its model geometry and materials

Precision, IK and GIS

// example:domains
import { HVec3, IK, GIS, v3 } from '@xort/cga';

const precise = new HVec3('0.1', '0.2', '0.3').add(new HVec3('0.2', 0, 0));
console.log(precise.x.toString()); // 0.3; strings preserve decimal input

const skeleton = IK.Skeleton.fromPoints([v3(), v3(1,0,0), v3(2,0,0)]);
const solved = new IK.CCDSolver().solve(skeleton, v3(1,1,0));
console.log(solved.converged, solved.distance);

const ecef = GIS.GVec3.fromDegrees(116.4, 39.9, 50);
console.log(ecef.toCartographic()); // longitude/latitude in radians, height in meters

CSG accepts closed, consistently oriented solids made of convex polygon faces. GIS Globe supplies tile and mesh data for a host renderer; pick queries the reference ellipsoid, while getHeight reads loaded terrain. Fetch/decode adapters integrate imagery and terrain services; examples inject local data. See domain modules.

Browsers and optional Three.js

Core calculations need no DOM, Three.js or GPU. Install the display dependency when needed:

npm install three

For a browser project using a bundler such as Vite, provide a container with an explicit height:

<div id="view" style="height:420px;width:100%"></div>
// example:browser
import { GLView, BreathLight } from '@xort/cga/three';

const view = new GLView({ container: document.querySelector('#view') });
const light = new BreathLight();
view.add(light);
view.addUpdates(time => light.update(time));
view.run();

// Call on unmount; dispose host model resources according to ownership.
const dispose = () => { light.dispose(); view.dispose(); };
window.addEventListener('pagehide', dispose, { once: true });

Additional entries include @xort/cga/shaders, ThreeBSP and DiamondShader. Without a bundler, use the global cga from build/@xort_cga.js or the ESM build/cga.esm.js; these core files do not include the Three.js viewer.

Internal algorithms and dependencies

Geometry, triangulation, booleans, CSG, IK, ellipsoid geodesics and decimal arithmetic are implemented inside the repository in TypeScript. The core has zero runtime dependencies. Decimal uses a BigInt kernel; geodesics use an internal Karney port with antipodal support and retained MIT attribution. Build tools stay out of the runtime package, Three.js is optional, and GPU shaders use GLSL.

// example:decimal
import { Decimal, HVec3 } from '@xort/cga';
const previous = { precision: Decimal.precision, rounding: Decimal.rounding };
try {
  Decimal.set({ precision: 50, rounding: Decimal.ROUND_HALF_EVEN });
  console.log(new Decimal(2).sqrt().toString());
  console.log(new HVec3('0.1').add(new HVec3('0.2')).toJSON());
} finally { Decimal.set(previous); }

Internal Decimal supplies arithmetic, comparison, square roots and formatting for vectors and CSG. It does not implement the complete decimal.js API, including trigonometry and clone configurations. Constructors retain input digits; arithmetic rounds to 1–1000 significant digits, with 20 by default. Non-finite values and out-of-range exponents throw. See implementation and migration.

Limits and remaining work

  • Floating-point queries use tolerances. Exhausting an iteration budget throws; zero distance between intersecting solids does not provide a general contact manifold or penetration depth.
  • Hole triangulation uses visible bridges and ear clipping, with worst-case O(n³) behavior. Polygon intersection enumeration is O(E²), with additional edge scans for classification; use it for small or medium contours.
  • Planar booleans default to roughly 1e-6 model-unit quantization, configurable through scale. Smaller features can merge. Decimal vectors do not turn floating-point boolean operations into exact predicates.
  • Round joins and caps use sampled curves. Large contours, extreme aspect ratios and nearly coincident edges still need dedicated performance/error benchmarks and stronger predicates.
  • Public entries have examples; dedicated method-level examples remain incomplete, especially matrix projection, transforms and buffer attributes. The method inventory separates dedicated tags from shared queries.
  • Constrained Delaunay, BVH, incremental updates, additional curves/surfaces and GIS protocols remain future capabilities. See the roadmap.

Development and verification

Minimum Node.js 22.12; Node 26 from .nvmrc is recommended. CI covers Linux / Windows with Node 22 / 24 / 26.

npm ci
npx playwright install chromium # Windows can use installed Edge
npm run docs:dev                # Local guides and examples
npm run verify                  # Complete checks
npm run algorithms:check        # Internal TS and dependency boundary
npm run docs:screenshots        # Capture 14 scenes / 28 images
npm run media:check             # Image hashes, dimensions and source fingerprint
npm run api:check               # Method-level inventory
npm run readme:check            # Execute README snippets
npm run release:check -- --complete

See architecture for module boundaries and .release/screenshots.json for screenshot parameters and hashes. New public entries need runnable examples; behavior changes need analytical or independent reference checks.

Plan the version and documentation before implementation, verification, commits, deployment and npm publication. Increment once per release, carrying at 100: 0.1.99 → 0.2.0, 0.99.99 → 1.0.0. Commits and authentication retries keep the same planned version.

0.1.5 release notes · Delivery checklist · Contributing · Release status

License

MIT. Ported algorithms and shaders retain their third-party notices.

관련 프로젝트 살펴보기

불러오는 중…