Repository: robbykraft/Origami
Branch: main
Commit: b717948c7123
Files: 632
Total size: 2.9 MB
Directory structure:
gitextract_wpm0yi8j/
├── .eslintrc.json
├── .github/
│ └── workflows/
│ └── main.yml
├── .gitignore
├── .npmignore
├── .travis.yml
├── bundle-shaders.py
├── changelog.md
├── license
├── package.json
├── rabbit-ear.js
├── readme.md
├── rollup.config.js
├── src/
│ ├── axioms/
│ │ ├── axioms.js
│ │ ├── boundary.js
│ │ ├── index.js
│ │ └── validate.js
│ ├── convert/
│ │ ├── foldToObj.js
│ │ ├── foldToSvg.js
│ │ ├── foldToSvg.md
│ │ ├── general/
│ │ │ ├── dom.js
│ │ │ ├── options.js
│ │ │ ├── planarize.js
│ │ │ └── svg.js
│ │ ├── index.js
│ │ ├── objToFold.js
│ │ ├── opxToFold.js
│ │ ├── svg/
│ │ │ ├── color.js
│ │ │ ├── drawBoundaries.js
│ │ │ ├── drawEdges.js
│ │ │ ├── drawFaces.js
│ │ │ ├── drawVertices.js
│ │ │ ├── index.js
│ │ │ ├── parse.js
│ │ │ └── stylesheet.js
│ │ ├── svgToFold.js
│ │ └── svgToFold.md
│ ├── diagrams/
│ │ ├── arrows.js
│ │ ├── axiomArrows.js
│ │ ├── general.js
│ │ ├── index.js
│ │ └── svgArrows.js
│ ├── environment/
│ │ ├── detect.js
│ │ ├── messages.js
│ │ └── window.js
│ ├── fold/
│ │ ├── bases.js
│ │ ├── colors.js
│ │ ├── frames.js
│ │ ├── primitives.js
│ │ ├── rabbitear.js
│ │ └── spec.js
│ ├── general/
│ │ ├── array.js
│ │ ├── clone.js
│ │ ├── cluster.js
│ │ ├── get.js
│ │ ├── hashCode.js
│ │ ├── index.js
│ │ ├── number.js
│ │ ├── sort.js
│ │ └── string.js
│ ├── graph/
│ │ ├── add/
│ │ │ ├── edge.js
│ │ │ └── vertex.js
│ │ ├── boundary.js
│ │ ├── clean.js
│ │ ├── connectedComponents.js
│ │ ├── count.js
│ │ ├── cycles.js
│ │ ├── directedGraph.js
│ │ ├── disjoint.js
│ │ ├── edges/
│ │ │ ├── circular.js
│ │ │ ├── duplicate.js
│ │ │ ├── lines.js
│ │ │ └── overlap.js
│ │ ├── epsilon.js
│ │ ├── explode.js
│ │ ├── faces/
│ │ │ ├── facePoint.js
│ │ │ ├── matrix.js
│ │ │ ├── planes.js
│ │ │ └── winding.js
│ │ ├── flaps.js
│ │ ├── fold/
│ │ │ ├── flatFold.js
│ │ │ ├── flatFoldSplitFace.js
│ │ │ ├── foldGraph.js
│ │ │ ├── foldGraphIntoSegments.js
│ │ │ ├── foldGraphIntoSubgraph.js
│ │ │ └── general.js
│ │ ├── index.js
│ │ ├── intersect.js
│ │ ├── join.js
│ │ ├── make/
│ │ │ ├── edges.js
│ │ │ ├── edgesAssignment.js
│ │ │ ├── edgesEdges.js
│ │ │ ├── edgesFaces.js
│ │ │ ├── edgesFoldAngle.js
│ │ │ ├── edgesVertices.js
│ │ │ ├── faces.js
│ │ │ ├── facesEdges.js
│ │ │ ├── facesFaces.js
│ │ │ ├── facesVertices.js
│ │ │ ├── index.js
│ │ │ ├── lookup.js
│ │ │ ├── vertices.js
│ │ │ ├── verticesEdges.js
│ │ │ ├── verticesFaces.js
│ │ │ └── verticesVertices.js
│ │ ├── maps.js
│ │ ├── nearest.js
│ │ ├── normalize.js
│ │ ├── normals.js
│ │ ├── orders.js
│ │ ├── overlap.js
│ │ ├── planarize/
│ │ │ ├── intersectAllEdges.js
│ │ │ ├── makeFacesMap.js
│ │ │ ├── planarize.js
│ │ │ ├── planarizeCollinearEdges.js
│ │ │ ├── planarizeCollinearVertices.js
│ │ │ ├── planarizeMakeFaces.js
│ │ │ └── planarizeOverlaps.js
│ │ ├── planarize.js
│ │ ├── pleat.js
│ │ ├── populate.js
│ │ ├── raycast.js
│ │ ├── remove.js
│ │ ├── rendering.js
│ │ ├── replace.js
│ │ ├── split/
│ │ │ ├── general.js
│ │ │ ├── splitEdge.js
│ │ │ ├── splitFace.js
│ │ │ ├── splitGraph.js
│ │ │ └── splitLine.js
│ │ ├── subgraph.js
│ │ ├── sweep.js
│ │ ├── symmetry.js
│ │ ├── transfer.js
│ │ ├── transform.js
│ │ ├── trees.js
│ │ ├── triangulate.js
│ │ ├── validate/
│ │ │ ├── validate.js
│ │ │ ├── validateAssignments.js
│ │ │ ├── validateOrders.js
│ │ │ ├── validateReferences.js
│ │ │ ├── validateReflexive.js
│ │ │ ├── validateTypes.js
│ │ │ └── validateWinding.js
│ │ ├── vertices/
│ │ │ ├── clusters.js
│ │ │ ├── collinear.js
│ │ │ ├── duplicate.js
│ │ │ ├── folded.js
│ │ │ ├── isolated.js
│ │ │ └── sort.js
│ │ └── walk.js
│ ├── index.js
│ ├── layer/
│ │ ├── constraints3D.js
│ │ ├── constraints3DEdges.js
│ │ ├── constraints3DFaces.js
│ │ ├── constraintsFlat.js
│ │ ├── facesSide.js
│ │ ├── general.js
│ │ ├── getBranches.js
│ │ ├── index.js
│ │ ├── initialSolutionsFlat.js
│ │ ├── layer.js
│ │ ├── propagate.js
│ │ ├── prototype.js
│ │ ├── prototypeOneDepth.js
│ │ ├── solve.js
│ │ ├── solver.js
│ │ ├── solverOneDepth.js
│ │ ├── table.js
│ │ ├── tacosTortillas.js
│ │ └── transitivity.js
│ ├── libTypes.d.ts
│ ├── math/
│ │ ├── clip.js
│ │ ├── compare.js
│ │ ├── constant.js
│ │ ├── convert.js
│ │ ├── convexHull.js
│ │ ├── encloses.js
│ │ ├── index.js
│ │ ├── intersect.js
│ │ ├── line.js
│ │ ├── matrix2.js
│ │ ├── matrix3.js
│ │ ├── matrix4.js
│ │ ├── nearest.js
│ │ ├── overlap.js
│ │ ├── plane.js
│ │ ├── polygon.js
│ │ ├── polynomial.js
│ │ ├── quaternion.js
│ │ ├── radial.js
│ │ ├── range.js
│ │ ├── straightSkeleton.js
│ │ ├── triangle.js
│ │ └── vector.js
│ ├── prototypes/
│ │ ├── graph.js
│ │ └── index.js
│ ├── singleVertex/
│ │ ├── degree4.js
│ │ ├── flatFoldable.js
│ │ ├── foldable.js
│ │ ├── index.js
│ │ ├── kawasaki.js
│ │ └── maekawa.js
│ ├── svg/
│ │ ├── arguments/
│ │ │ ├── makeCoordinates.js
│ │ │ ├── makeViewBox.js
│ │ │ └── semiFlattenArrays.js
│ │ ├── colors/
│ │ │ ├── convert.js
│ │ │ ├── cssColors.js
│ │ │ ├── index.js
│ │ │ └── parseColor.js
│ │ ├── constructor/
│ │ │ ├── elements.js
│ │ │ ├── extensions/
│ │ │ │ ├── arc/
│ │ │ │ │ └── index.js
│ │ │ │ ├── arrow/
│ │ │ │ │ ├── index.js
│ │ │ │ │ ├── init.js
│ │ │ │ │ ├── makeArrowPaths.js
│ │ │ │ │ ├── methods.js
│ │ │ │ │ └── options.js
│ │ │ │ ├── circle.js
│ │ │ │ ├── curve/
│ │ │ │ │ ├── arguments.js
│ │ │ │ │ ├── getCurveEndpoints.js
│ │ │ │ │ ├── index.js
│ │ │ │ │ ├── makeCurvePath.js
│ │ │ │ │ └── methods.js
│ │ │ │ ├── ellipse.js
│ │ │ │ ├── g.js
│ │ │ │ ├── index.js
│ │ │ │ ├── line.js
│ │ │ │ ├── maskTypes.js
│ │ │ │ ├── origami/
│ │ │ │ │ ├── index.js
│ │ │ │ │ ├── init.js
│ │ │ │ │ └── methods.js
│ │ │ │ ├── path.js
│ │ │ │ ├── polys.js
│ │ │ │ ├── rect.js
│ │ │ │ ├── shared/
│ │ │ │ │ ├── dom.js
│ │ │ │ │ ├── makeArcPath.js
│ │ │ │ │ ├── transforms.js
│ │ │ │ │ └── urls.js
│ │ │ │ ├── style.js
│ │ │ │ ├── svg/
│ │ │ │ │ ├── animation.js
│ │ │ │ │ ├── getSVGFrame.js
│ │ │ │ │ ├── index.js
│ │ │ │ │ ├── makeBackground.js
│ │ │ │ │ ├── methods.js
│ │ │ │ │ └── touch.js
│ │ │ │ ├── text.js
│ │ │ │ └── wedge/
│ │ │ │ └── index.js
│ │ │ └── index.js
│ │ ├── environment/
│ │ │ ├── detect.js
│ │ │ ├── lib.js
│ │ │ ├── messages.js
│ │ │ ├── strings.js
│ │ │ └── window.js
│ │ ├── general/
│ │ │ ├── algebra.js
│ │ │ ├── cdata.js
│ │ │ ├── dom.js
│ │ │ ├── index.js
│ │ │ ├── path.js
│ │ │ ├── string.js
│ │ │ ├── transforms.js
│ │ │ └── viewBox.js
│ │ ├── index.js
│ │ └── spec/
│ │ ├── classes_attributes.js
│ │ ├── classes_nodes.js
│ │ ├── namespace.js
│ │ ├── nodes.js
│ │ ├── nodes_attributes.js
│ │ └── nodes_children.js
│ ├── text/
│ │ ├── axioms.json
│ │ ├── edge_assignments.json
│ │ ├── index.js
│ │ └── instructions.json
│ ├── types.js
│ └── webgl/
│ ├── creasePattern/
│ │ ├── arrays.js
│ │ ├── data.js
│ │ ├── index.js
│ │ ├── models.js
│ │ ├── shaders/
│ │ │ ├── cp-100.frag
│ │ │ ├── cp-100.vert
│ │ │ ├── cp-300.frag
│ │ │ ├── cp-300.vert
│ │ │ ├── thick-edges-100.vert
│ │ │ └── thick-edges-300.vert
│ │ ├── shaders.js
│ │ └── uniforms.js
│ ├── foldedForm/
│ │ ├── arrays.js
│ │ ├── data.js
│ │ ├── index.js
│ │ ├── models.js
│ │ ├── shaders/
│ │ │ ├── model-100.frag
│ │ │ ├── model-100.vert
│ │ │ ├── model-300.frag
│ │ │ ├── model-300.vert
│ │ │ ├── outlined-model-100.frag
│ │ │ ├── outlined-model-100.vert
│ │ │ ├── outlined-model-300.frag
│ │ │ ├── outlined-model-300.vert
│ │ │ ├── simple-100.frag
│ │ │ ├── simple-300.frag
│ │ │ ├── thick-edges-100.vert
│ │ │ └── thick-edges-300.vert
│ │ ├── shaders.js
│ │ └── uniforms.js
│ ├── general/
│ │ ├── colors.js
│ │ ├── index.js
│ │ ├── model.js
│ │ ├── view.js
│ │ └── webgl.js
│ ├── index.js
│ └── readme.md
├── tests/
│ ├── axioms.axioms.test.js
│ ├── axioms.boundary.test.js
│ ├── axioms.validate.test.js
│ ├── clean.js
│ ├── convert.foldToObj.test.js
│ ├── convert.foldToSvg.origami.test.js
│ ├── convert.foldToSvg.test.js
│ ├── convert.objToFold.test.js
│ ├── convert.opxToFold.test.js
│ ├── convert.svgToFold.test.js
│ ├── diagram.arrows.axiom.test.js
│ ├── diagram.arrows.simple.test.js
│ ├── diagram.general.test.js
│ ├── docs.js
│ ├── environment.window.test.js
│ ├── files/
│ │ ├── cp/
│ │ │ ├── bird-base.cp
│ │ │ ├── square-fish.cp
│ │ │ └── windmill.cp
│ │ ├── fold/
│ │ │ ├── abstract-graph.fold
│ │ │ ├── bad-edges.fold
│ │ │ ├── bird-base-3d-cp.fold
│ │ │ ├── bird-base-3d.fold
│ │ │ ├── bird-disjoint-edges.fold
│ │ │ ├── blintz-frames.fold
│ │ │ ├── bowtie.fold
│ │ │ ├── command-strip-with-back.fold
│ │ │ ├── command-strip.fold
│ │ │ ├── crane-cp-bmvfcj-simple.fold
│ │ │ ├── crane-cp-bmvfcj.fold
│ │ │ ├── crane-cp.fold
│ │ │ ├── crane-step.fold
│ │ │ ├── crane.fold
│ │ │ ├── cube-octagon.fold
│ │ │ ├── cycles-3d.fold
│ │ │ ├── disjoint-cps.fold
│ │ │ ├── disjoint-triangles-3d.fold
│ │ │ ├── fan-cp.fold
│ │ │ ├── fan-flat-cp.fold
│ │ │ ├── fan-folded-through-cp.fold
│ │ │ ├── fish-cp-3d.fold
│ │ │ ├── flat-pleat-fish.fold
│ │ │ ├── invalid-box-pleat-3d.fold
│ │ │ ├── invalid-key-names.fold
│ │ │ ├── invalid-mismatch-length.fold
│ │ │ ├── invalid-mismatch-references.fold
│ │ │ ├── invalid-self-intersect.fold
│ │ │ ├── invalid-single-vertex-2d.fold
│ │ │ ├── invalid-single-vertex-3d.fold
│ │ │ ├── isolated-line-in-face.fold
│ │ │ ├── kabuto.fold
│ │ │ ├── kissing-squares.fold
│ │ │ ├── kraft-bird-base.fold
│ │ │ ├── layer-4-flaps.fold
│ │ │ ├── layer-solver-conflict.fold
│ │ │ ├── layers-3d-edge-edge.fold
│ │ │ ├── layers-3d-edge-face.fold
│ │ │ ├── layers-cycle-nonconvex.fold
│ │ │ ├── layers-flat-grid.fold
│ │ │ ├── layers-zipper.fold
│ │ │ ├── maze-8x8.fold
│ │ │ ├── maze-s.fold
│ │ │ ├── maze-u.fold
│ │ │ ├── moosers-train-carriage-fourth.fold
│ │ │ ├── moosers-train-carriage.fold
│ │ │ ├── moosers-train-engine.fold
│ │ │ ├── moosers-train.fold
│ │ │ ├── nested-frames.fold
│ │ │ ├── no-faces.fold
│ │ │ ├── non-flat-paper.fold
│ │ │ ├── non-planar-100-chaotic.fold
│ │ │ ├── non-planar-100-lines.fold
│ │ │ ├── non-planar-25-lines.fold
│ │ │ ├── non-planar-50-chaotic.fold
│ │ │ ├── non-planar-50-lines.fold
│ │ │ ├── non-planar-500-chaotic.fold
│ │ │ ├── non-planar-75-lines.fold
│ │ │ ├── non-planar-bird-base.fold
│ │ │ ├── non-planar-nonconvex.fold
│ │ │ ├── non-planar-polygons.fold
│ │ │ ├── non-planar-square-fish.fold
│ │ │ ├── overlapping-assignments.fold
│ │ │ ├── panels-3x3-invalid.fold
│ │ │ ├── panels-3x3.fold
│ │ │ ├── panels-4x2.fold
│ │ │ ├── panels-5.fold
│ │ │ ├── panels-6x2-90deg.fold
│ │ │ ├── panels-simple.fold
│ │ │ ├── panels-zig-zag.fold
│ │ │ ├── pleats-angle-3d.fold
│ │ │ ├── preliminary-offset-cp.fold
│ │ │ ├── randlett-flapping-bird.fold
│ │ │ ├── random-triangles-3d.fold
│ │ │ ├── resch-tess.fold
│ │ │ ├── separated-parallel-edges.fold
│ │ │ ├── square-fish-3d.fold
│ │ │ ├── square-tube-with-overlap.fold
│ │ │ ├── square-twist.fold
│ │ │ ├── strip-weave-concave.fold
│ │ │ ├── strip-weave.fold
│ │ │ ├── strip-with-angle.fold
│ │ │ ├── surrounded-square.fold
│ │ │ ├── triangle-strip-2.fold
│ │ │ ├── triangle-strip.fold
│ │ │ ├── two-bird-cp.fold
│ │ │ ├── wavy-miura-no-faces.fold
│ │ │ ├── windmill-no-edges.fold
│ │ │ ├── windmill-variations.fold
│ │ │ └── windmill.fold
│ │ ├── json/
│ │ │ ├── crane-faces-edges-overlap.json
│ │ │ ├── crane-faces-faces-overlap.json
│ │ │ ├── crane-layer-solver-no-depth.json
│ │ │ ├── crane-layer-solver.json
│ │ │ ├── cube-octagon-constraints.json
│ │ │ ├── kabuto-constraints.json
│ │ │ ├── kabuto-faces-faces-overlap.json
│ │ │ ├── kabuto-layer-solver-no-depth.json
│ │ │ ├── kabuto-layer-solver.json
│ │ │ ├── kraft-bird-faces-faces-overlap.json
│ │ │ ├── layer-table.json
│ │ │ ├── maze-u-constraints.json
│ │ │ ├── panels-3x3-layer-solver-no-depth.json
│ │ │ ├── panels-3x3-layer-solver.json
│ │ │ └── randlett-flapping-bird-layer-solver.json
│ │ ├── obj/
│ │ │ ├── sphere-with-holes.obj
│ │ │ └── stanford-bunny.obj
│ │ └── opx/
│ │ ├── bird-base-2012.opx
│ │ ├── bird-base.opx
│ │ ├── one-crease.opx
│ │ ├── square-fish.opx
│ │ ├── test.opx
│ │ └── windmill.opx
│ ├── fold.bases.test.js
│ ├── fold.colors.test.js
│ ├── fold.frames.test.js
│ ├── fold.spec.test.js
│ ├── general.array.test.js
│ ├── general.cluster.test.js
│ ├── general.get.test.js
│ ├── general.hashCode.test.js
│ ├── general.number.test.js
│ ├── general.sort.test.js
│ ├── general.string.test.js
│ ├── generate.test.js
│ ├── graph.add.edge.test.js
│ ├── graph.add.vertex.test.js
│ ├── graph.boundary.test.js
│ ├── graph.clean.test.js
│ ├── graph.connectedComponents.test.js
│ ├── graph.count.test.js
│ ├── graph.countImplied.test.js
│ ├── graph.cycles.test.js
│ ├── graph.directedGraph.test.js
│ ├── graph.disjoint.test.js
│ ├── graph.edges.circular.test.js
│ ├── graph.edges.duplicate.test.js
│ ├── graph.edges.lines.test.js
│ ├── graph.edges.overlap.test.js
│ ├── graph.explode.test.js
│ ├── graph.faces.facePoint.test.js
│ ├── graph.faces.matrix.test.js
│ ├── graph.faces.planes.getFacesPlane.test.js
│ ├── graph.faces.planes.overlapping.test.js
│ ├── graph.faces.winding.test.js
│ ├── graph.flaps.test.js
│ ├── graph.fold.flatFold.test.js
│ ├── graph.fold.foldGraph.layers.test.js
│ ├── graph.fold.foldGraph.test.js
│ ├── graph.fold.foldGraphIntoSegments.test.js
│ ├── graph.fold.foldGraphIntoSubgraph.test.js
│ ├── graph.intersect.test.js
│ ├── graph.intersect.vertices.test.js
│ ├── graph.join.test.js
│ ├── graph.make.edges.test.js
│ ├── graph.make.edgesEdges.test.js
│ ├── graph.make.edgesFaces.test.js
│ ├── graph.make.facesFaces.test.js
│ ├── graph.make.facesMatrix.test.js
│ ├── graph.make.facesVertices.test.js
│ ├── graph.make.facesWinding.test.js
│ ├── graph.make.lookup.test.js
│ ├── graph.make.verticesEdges.test.js
│ ├── graph.make.verticesFaces.test.js
│ ├── graph.make.verticesVertices.test.js
│ ├── graph.maps.test.js
│ ├── graph.nearest.test.js
│ ├── graph.normalize.test.js
│ ├── graph.normals.test.js
│ ├── graph.orders.test.js
│ ├── graph.overlap.components.test.js
│ ├── graph.overlap.edgesEdges.test.js
│ ├── graph.overlap.facesEdges.test.js
│ ├── graph.overlap.facesFaces.test.js
│ ├── graph.planarize.collinearEdges.test.js
│ ├── graph.planarize.faceMap.test.js
│ ├── graph.planarize.intersect.test.js
│ ├── graph.planarize.new.test.js
│ ├── graph.planarize.test.js
│ ├── graph.planarizeOverlap.test.js
│ ├── graph.pleat.test.js
│ ├── graph.populate.test.js
│ ├── graph.remove.test.js
│ ├── graph.rendering.test.js
│ ├── graph.replace.test.js
│ ├── graph.split.splitEdge.test.js
│ ├── graph.split.splitFace.test.js
│ ├── graph.split.splitGraph.test.js
│ ├── graph.split.splitLine.test.js
│ ├── graph.subgraph.test.js
│ ├── graph.sweep.test.js
│ ├── graph.symmetry.test.js
│ ├── graph.transfer.test.js
│ ├── graph.transform.test.js
│ ├── graph.trees.test.js
│ ├── graph.triangulate.test.js
│ ├── graph.validate.test.js
│ ├── graph.vertices.clusters.test.js
│ ├── graph.vertices.collinear.test.js
│ ├── graph.vertices.duplicate.test.js
│ ├── graph.vertices.folded.test.js
│ ├── graph.vertices.isolated.test.js
│ ├── graph.vertices.sort.test.js
│ ├── graph.walk.test.js
│ ├── index.html
│ ├── layer.constraints3DEdges.edgesFaces.test.js
│ ├── layer.constraints3DEdges.test.js
│ ├── layer.constraints3DFaces.test.js
│ ├── layer.constraints3d.test.js
│ ├── layer.constraintsFlat.test.js
│ ├── layer.facesSide.test.js
│ ├── layer.general.test.js
│ ├── layer.initialSolution.test.js
│ ├── layer.layer.solveLayerOrders.test.js
│ ├── layer.layer.solveLayerOrders3D.test.js
│ ├── layer.propagate.test.js
│ ├── layer.prototype.test.js
│ ├── layer.solver.2D.test.js
│ ├── layer.solver.3D.test.js
│ ├── layer.table.test.js
│ ├── layer.transitivity.test.js
│ ├── lineno.js
│ ├── math.algebra.matrix2.test.js
│ ├── math.algebra.matrix3.test.js
│ ├── math.algebra.matrix4.test.js
│ ├── math.algebra.quaternion.test.js
│ ├── math.algebra.vector.resize.test.js
│ ├── math.algebra.vector.test.js
│ ├── math.debug.test.js
│ ├── math.general.array.test.js
│ ├── math.general.constant.test.js
│ ├── math.general.convert.test.js
│ ├── math.general.function.test.js
│ ├── math.general.get.test.js
│ ├── math.general.sort.test.js
│ ├── math.general.typeof.test.js
│ ├── math.geometry.convexHull.test.js
│ ├── math.geometry.line.test.js
│ ├── math.geometry.nearest.test.js
│ ├── math.geometry.polygon.test.js
│ ├── math.geometry.radial.test.js
│ ├── math.geometry.straightSkeleton.test.js
│ ├── math.geometry.triangle.test.js
│ ├── math.intersect.clip.line.test.js
│ ├── math.intersect.clip.polygon.test.js
│ ├── math.intersect.encloses.test.js
│ ├── math.intersect.method.test.js
│ ├── math.intersect.overlap.test.js
│ ├── math.intersect.polyLine.test.js
│ ├── math.intersect.split.test.js
│ ├── math.intersect.test.js
│ ├── math.overlap.test.js
│ ├── math.primitives.circle.test.js
│ ├── math.primitives.clip.test.js
│ ├── math.primitives.ellipse.test.js
│ ├── math.primitives.json.test.js
│ ├── math.primitives.junction.test.js
│ ├── math.primitives.line.test.js
│ ├── math.primitives.matrix.test.js
│ ├── math.primitives.paths.test.js
│ ├── math.primitives.polygon.test.js
│ ├── math.primitives.rect.test.js
│ ├── math.primitives.types.test.js
│ ├── math.primitives.vector.test.js
│ ├── math.range.test.js
│ ├── prototypes.cp.test.js
│ ├── prototypes.graph.test.js
│ ├── prototypes.static.test.js
│ ├── singleVertex.degree4.test.js
│ ├── singleVertex.flatFoldable.test.js
│ ├── singleVertex.foldable.test.js
│ ├── singleVertex.kawasaki.test.js
│ ├── singleVertex.maekawa.test.js
│ ├── svg.arrow.test.js
│ ├── svg.attributes.test.js
│ ├── svg.circle.test.js
│ ├── svg.class.id.test.js
│ ├── svg.colors.test.js
│ ├── svg.coordinates.test.js
│ ├── svg.dom.test.js
│ ├── svg.ellipse.test.js
│ ├── svg.environment.test.js
│ ├── svg.line.test.js
│ ├── svg.nodes.test.js
│ ├── svg.object.assign.test.js
│ ├── svg.path.test.js
│ ├── svg.polygon.test.js
│ ├── svg.primitives.test.js
│ ├── svg.rect.test.js
│ ├── svg.stylesheet.test.js
│ ├── svg.svg.animation.test.js
│ ├── svg.svg.args.test.js
│ ├── svg.svg.background.test.js
│ ├── svg.svg.controls.test.js
│ ├── svg.svg.load.test.js
│ ├── svg.svg.save.test.js
│ ├── svg.svg.viewbox.test.js
│ ├── svg.transforms.test.js
│ ├── svg.types.test.js
│ ├── svg.urls.test.js
│ ├── svg.use.test.js
│ ├── svg.window.test.js
│ └── webgl.initialize.test.js
├── tsconfig.json
└── typedoc.config.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .eslintrc.json
================================================
{
"env": {
"browser": true,
"es2021": true,
"node": true
},
"extends": "airbnb-base",
"ignores": ["*.d.ts"],
"parserOptions": {
"ecmaVersion": "latest",
"ecmaFeatures": { "jsx": true },
"sourceType": "module"
},
"rules": {
"arrow-parens": 0,
"camelcase": ["error", { "allow": [".*"] }],
"func-names": ["error", "never"],
"indent": ["error", "tab"],
"no-bitwise": 0,
"no-continue": 0,
"no-labels": 0,
"no-plusplus": 0,
"no-param-reassign": ["error", {
"props": true,
"ignorePropertyModificationsFor": [
"graph",
"epsilon",
"faces_edges"
]
}],
"no-sparse-arrays": 0,
"no-tabs": 0,
"no-restricted-syntax": ["error", "ForInStatement", "ForOfStatement", "WithStatement"],
"import/extensions": ["error", "always", { "ignorePackages": true }],
"import/no-relative-packages": 0,
"object-shorthand": 0,
"object-curly-newline": 0,
"import/prefer-default-export": 0,
"prefer-rest-params": 0,
"prefer-default-export": 0,
"prefer-destructuring": 0,
"quotes": ["error", "double", { "allowTemplateLiterals": true }]
}
}
================================================
FILE: .github/workflows/main.yml
================================================
name: CI
on:
# Triggers the workflow on push or pull request events but only for the main branch
push:
branches: [ main ]
pull_request:
branches: [ main ]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
jobs:
test:
name: run all tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
- name: install dependencies
run: npm install
- name: run tests
run: npm run test
================================================
FILE: .gitignore
================================================
*.DS_Store
node_modules/
coverage/
docs/
module/
tests/tmp/
types/
package-lock.json
*.d.ts.map
================================================
FILE: .npmignore
================================================
.DS_Store
.eslintrc.js
.git
.gitignore
.travis.yml
coverage/
docs/
src/
tests/
build-shaders.py
changelog.md
contribute.md
developers.md
docs-style.css
rollup.config.js
tsconfig.json
typedoc.config.json
================================================
FILE: .travis.yml
================================================
language: node_js
node_js:
- lts/*
================================================
FILE: bundle-shaders.py
================================================
# due to the issues around loading raw text files,
# this bundler will convert the shader files into an
# es6 Javascript file with named exports of the
# raw text as strings
# IMPORTANT! this will ignore any filenames containing
# the substring "sketch". there are a few files that
# are being worked on in development we want to ignore
import re
from os import listdir
from os.path import isfile, join
# list here the locations where shader files exist, and the
# location and filename to write the bundled named export file
sources = [{
"read": "src/webgl/creasePattern/shaders/",
"write": "src/webgl/creasePattern/shaders.js"
}, {
"read": "src/webgl/foldedForm/shaders/",
"write": "src/webgl/foldedForm/shaders.js"
}]
# convert a raw text file into a javascript string which follows this format:
# export const FILENAME = `FILECONTENTS`;
# where FILENAME is the file's name but made into a valid javascript variable
def makeNamedExport(file, path):
f = open(join(path, file))
# convert the file into a valid JS variable name
variablename = re.sub("[-\.]", "_", file)
# compress multiple consecutive newlines into just one
contents = re.sub("[\n]{2,}", "\n", f.read())
string = "export const " + variablename + " = `" + contents + "`;"
f.close()
return string
# run makeNamedExport on all files in a directory and
# join them into one large newline-separated string
def makeBundle(files, path):
return "\n\n".join(map(lambda file: makeNamedExport(file, path), files)) + "\n"
# iterate over the locations from sources, convert them to bundles,
# save the stringified bundle as a new file
for source in sources:
# ignore "sketch" files
files = [f for f in listdir(source["read"]) if (isfile(join(source["read"], f)) and "sketch" not in f)]
bundle = makeBundle(files, source["read"])
with open(source["write"], 'w') as f:
f.write(bundle)
================================================
FILE: changelog.md
================================================
# 0.9.33 alpha
`pleat()` when given parallel lines will now correct for the case when the lines' vectors point in the opposite directions.
many of the intersection methods have been refactored and have small or dramatic speedups.
new method: `getEdgesRectOverlap()`
new method: `findSymmetryLines()` and `findSymmetryLine()` using the lines in the graph to uncover a line of symmetry.
new method: `getEdgesLine()` and its subroutine `clusterParallelVectors()` which performs a similar function as `clusterScalars()`.
new overlap methods:
```javascript
ear.graph.getFacesLineOverlap()
ear.graph.getFacesRayOverlap()
ear.graph.getFacesSegmentOverlap()
```
new method `ear.graph.getFramesByClassName()`
new method `ear.graph.getEdgeBetweenVertices()`
ear.graph.makePlanarFaces now returns an object already in FOLD form, instead of the data being inverted into an array of objects
All axiom methods return an *array* of lines. Before, some would and others would not. The system is now consistent.
replace `getGraphKeysWithPrefix` with `filterKeysWithPrefix`, maintaining the functionality of `getGraphKeysWithPrefix` where it will add the `_` character to match against. same with Suffix methods.
new method: `subgraph` and `subgraphWithFaces`, where *subgraphWithEdges* and *subgraphWithVertices* could be written in similar form.
Methods renamed:
- `{graph/cp/origami}.copy` -> `{graph/cp/origami}.clone`
- `fragment` -> `planarize`
- `getBoundingBox` -> `boundingBox`
- `getBoundaryVertices` -> `boundaryVertices`
- `getBoundary` -> `boundary`
- `getPlanarBoundary` -> `planarBoundary`
- `makeFacesFacesOverlap` -> `getFacesFaces2DOverlap`
- `makeFacesCenter` -> `makeFacesCentroid2D`
- `makeFacesCenterQuick` -> `makeFacesConvexCenter`
- `getDuplicateEdges` -> `duplicateEdges`
- `getCircularEdges` -> `circularEdges`
- `getVerticesClusters` -> `verticesClusters`
- `getDuplicateVertices` -> `duplicateVertices`
- `getEdgeIsolatedVertices` -> `edgeIsolatedVertices`
- `getFaceIsolatedVertices` -> `faceIsolatedVertices`
- `getIsolatedVertices` -> `isolatedVertices`
- `getCoplanarFacesGroups` -> `coplanarFacesGroups`
- `getOverlappingFacesGroups` -> `overlappingFacesGroups`
- `makeTrianglePairs` -> `chooseTwoPairs`
- `clusterArrayValues` -> `clusterScalars`
- `getDisjointedVertices` -> `disjointVerticesSets`
`makeEdgesAssignment` has been renamed to `makeEdgesAssignmentSimple` and `makeEdgesAssignment` now also assigns "B" boundary edges by checking edges_faces for # of incident faces.
new WebGL implementation. see: [readme.md](https://github.com/robbykraft/Origami/tree/master/src/webgl) and [foldfile.com](https://foldfile.com)
Various methods will now throw Errors instead of console.error or console.warn. Not all console.warn have been removed however. The distinction is that if the function is still able to generate a solution, it will console.warn. If the function generated something which contains errors or misleading information, it throws an error.
New subcategory `ear.webgl` containing at least: `createProgram`, `initialize`, `foldedForm`, `creasePattern`, `rebuildViewport`, `makeProjectionMatrix`, `makeModelMatrix`, `drawProgram`, `deallocProgram`, with many more methods specific to drawing different styles with different shaders.
new Matrix4 type. new Quaternion type. new projection matrices.
new method `ear.graph.nearest`, which was already in the `graph()` object as a prototype method. now exists in the top level.
all matrix scale methods takes an array of values instead of one number, allowing non-uniform axis scaling.
`ear.graph.getBoundingBox` will return "undefined" if the graph does not contain any vertices_coords. previously this would throw an error.
new `nudgeVerticesWithFacesLayer`, `nudgeVerticesWithFaceOrders` for nudging vertices in an exploded graph based on layer order.
`src/layer/topological.js` contains a new topological sort method. currently not being exported.
new `.convert` with the first (of many, hopefully) file conversions: `.obj` to `.fold`, which includes computing edges_foldAngle and giving them a "M" "V" assignment.
new methods `getCoplanarFacesGroups`, `getOverlappingFacesGroups` which will find all groups of faces which share the same plane in 3D space (`getCoplanarFacesGroups`), and then in the case of `getOverlappingFacesGroups` actually compute whether or not they overlap.
new method `selfRelationalUniqueIndexPairs`, given any array of self-referential data (vertices_vertices, faces_faces, etc), create a list of unique pairwise combinations of related indices.
rewrite of `getVerticesClusters`, implemented a line sweep and the runtime has been massively improved.
refactor fold/keys and fold/spec, simplify methods that get exposed in the final build.
# 0.9.32 alpha
new layer solver implementation at ear.layer.solver(), huge performance improvement. solver returns data bound to a prototype which includes methods to process and analyze the data. methods include
```javascript
count()
solution(...indices)
allSolutions()
facesLayer(...indices)
allFacesLayers()
faceOrders(...indices)
allFaceOrders()
```
ear.layer.assignmentSolver renamed to ear.layer.singleVertexAssignmentSolver.
ear.math.enclosingBoundingBoxes, new method. test if one bounding box is entirely inside another.
ear.graph.makeEdgesEdgesSimilar, answers which edges have the same endpoints (vertices) as other edges. endpoints can be in any order.
performance improvements for ear.graph.makeFacesFacesOverlap, ear.graph.makeEdgesFacesOverlap.
# 0.9.31 alpha
axiom function wrapper has changed. `validate()` is now exposed to the user, as is the `axiomInBoundary` methods. Normal-distance parameterization methods are now named as such.
new convex hull algorithm. two entrypoints: `convexHull` returns points, `convexHullIndices` returns indices of points from your points parameter array.
`onLeave` added to the other three methods `onMove` `onPress` `onRelease` for SVG elements.
# 0.9.3 alpha
no longer requiring @xmldom/xmldom as a dependency. This library now has zero dependencies! [1]
`clean()` takes no options now and performs one consistent task: removes all bad edges and vertices. if you like you can call each submethod now `removeDuplicateVertices`, `removeCircularEdges`, `removeDuplicateEdges`, `removeIsolatedVertices`.
axiom function parameters have now changed to the much simpler "point, line" to consistenly separate types. This replaces "point, origin, vector" inputs where "origin, vector" are two components which describe a line, and "point" is points... **to update: modify your axiom function parameters, whever it asks for a line, make a ear.line() objects from your previous origin/vector pairs.**
```javascript
ear.graph.getBoundaryVertices // unsorted
ear.graph.getBoundary.vertices // sorted
```
> [1] if you use Rabbit Ear in NodeJS and create a SVG elements (virtually), you will need to import @xmldom. Because this is such a unique rare case, this is left to the user. This will be explained in the documentation.
================================================
FILE: license
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: package.json
================================================
{
"name": "rabbit-ear",
"version": "0.9.4",
"description": "origami design library",
"exports": {
".": {
"import": "./module/index.js",
"require": "./rabbit-ear.js",
"types": "./types/index.d.ts"
},
"./*": {
"import": "./module/*",
"types": "./types/*"
}
},
"type": "module",
"types": "./types/index.d.ts",
"scripts": {
"build": "npm run clean && rollup -c && npm run types && npm run docs",
"clean": "node tests/clean.js",
"docs": "typedoc --options typedoc.config.json",
"test": "mkdir -p ./tests/tmp && vitest",
"types": "tsc"
},
"files": [
"./rabbit-ear.js",
"./rabbit-ear.module.js",
"./license",
"./package.json",
"./readme.md",
"./module",
"./types"
],
"license": "GPLv3",
"author": {
"name": "Maya Kraft",
"email": "maya@kraft.work",
"url": "https://kraft.work"
},
"keywords": [
"origami",
"design",
"geometry",
"paper",
"fold",
"folding",
"foldability",
"generative",
"parametric",
"diagram",
"architecture",
"creative",
"art"
],
"repository": {
"type": "git",
"url": "git://github.com/rabbit-ear/rabbit-ear.git"
},
"homepage": "https://rabbitear.org",
"bugs": {
"url": "https://github.com/rabbit-ear/rabbit-ear/issues"
},
"devDependencies": {
"@rollup/plugin-terser": "^0.4.3",
"@xmldom/xmldom": "^0.8.10",
"earcut": "^2.2.4",
"eslint": "^8.47.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-import": "^2.28.1",
"rollup": "^3.28.1",
"rollup-plugin-cleanup": "^3.2.1",
"typedoc": "^0.25.13",
"typedoc-github-wiki-theme": "^1.1.0",
"typedoc-plugin-markdown": "^3.17.1",
"typescript": "^5.2.2",
"vitest": "^0.34.6"
}
}
================================================
FILE: rabbit-ear.js
================================================
/* Rabbit Ear 0.9.4 alpha 2024-04-20 (c) Kraft, GNU GPLv3 License */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).ear=t()}(this,(function(){"use strict";const e="object"==typeof window&&"object"==typeof window.document,t="object"==typeof process&&"object"==typeof process.versions&&(null!=process.versions.node||null!=process.versions.bun),r="object"==typeof window&&"Deno"in window&&"object"==typeof window.Deno,s=t||r;var a="valid manifold required",o="cycle not allowed",c="replace() generated undefined",n="foldAngles cannot be determined from flat-folded faces without an assignment",i="WebGl not Supported",l="only convex faces are supported",d="window not set; if using node/deno include package @xmldom/xmldom and set ear.window = xmldom",_="non-convex triangulation requires vertices_coords",m="svgToFold found
================================================
FILE: tests/layer.constraints3DEdges.edgesFaces.test.js
================================================
import fs from "fs";
import { expect, test } from "vitest";
import ear from "../src/index.js";
const solveOverlapFacesWith3DEdge = (graph, epsilon) => {
const {
faces_plane,
faces_winding,
clusters_graph,
} = ear.layer.constraints3DFaceClusters(graph, epsilon);
return ear.layer.solveOverlapFacesWith3DEdge(
graph,
ear.layer.getOverlapFacesWith3DEdge(
graph,
{ clusters_graph, faces_plane },
epsilon,
),
faces_winding,
);
};
test("getOverlapFacesWith3DEdge, layers edge-face", () => {
const foldfile = fs.readFileSync(
"./tests/files/fold/layers-3d-edge-face.fold",
"utf-8",
);
const fold = JSON.parse(foldfile);
const frames = ear.graph.getFileFramesAsArray(fold);
const foldedForms = frames.map(frame => ({
...frame,
vertices_coords: ear.graph.makeVerticesCoordsFolded(frame),
}));
foldedForms.forEach(folded => ear.graph.populate(folded));
const graphsEdgeFace3DOverlaps = foldedForms
.map(folded => ear.layer.getOverlapFacesWith3DEdge(
folded,
ear.layer.constraints3DFaceClusters(folded),
));
const orders = foldedForms
.map(folded => solveOverlapFacesWith3DEdge(folded));
expect(graphsEdgeFace3DOverlaps).toMatchObject([
[{ edge: 6, tortilla: 1, coplanar: 3, angled: 2 }],
[{ edge: 6, tortilla: 1, coplanar: 3, angled: 2 }],
[],
[{ edge: 11, tortilla: 0, coplanar: 3, angled: 2 }],
[{ edge: 11, tortilla: 0, coplanar: 3, angled: 2 }],
[{ edge: 11, tortilla: 0, coplanar: 3, angled: 2 }],
]);
expect(orders).toMatchObject([
{ "1 3": 2 },
{ "1 3": 2 },
{},
// in each of these next cases, face 0 is below face 3, locally,
// and because the plane normal is [0, 0, 1], globally as well.
{ "0 3": 2 },
{ "0 3": 2 },
{ "0 3": 2 },
]);
});
test("getOverlapFacesWith3DEdge, layers edge-edge", () => {
const foldfile = fs.readFileSync(
"./tests/files/fold/layers-3d-edge-edge.fold",
"utf-8",
);
const fold = JSON.parse(foldfile);
const frames = ear.graph.getFileFramesAsArray(fold);
const foldedForms = frames.map(frame => ({
...frame,
vertices_coords: ear.graph.makeVerticesCoordsFolded(frame),
}));
foldedForms.forEach(folded => ear.graph.populate(folded));
const graphsEdgeFace3DOverlaps = foldedForms
.map(folded => ear.layer.getOverlapFacesWith3DEdge(
folded,
ear.layer.constraints3DFaceClusters(folded),
));
// all frames overlap edges at edges, none will have a result
expect(graphsEdgeFace3DOverlaps).toMatchObject([
[], [], [], [], [], [], [], [], [], [], [],
]);
});
test("getOverlapFacesWith3DEdge, cube-octagon", () => {
const foldfile = fs.readFileSync(
"./tests/files/fold/cube-octagon.fold",
"utf-8",
);
const fold = JSON.parse(foldfile);
// the second folded frame is the one without the flat assignments
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[1];
ear.graph.populate(folded);
const {
planes,
// planes_faces,
// planes_transform,
// planes_clusters,
faces_winding,
faces_plane,
// faces_cluster,
// clusters_plane,
// clusters_faces,
} = ear.graph.getCoplanarAdjacentOverlappingFaces(folded);
const edgeFace3DOverlaps = ear.layer.getOverlapFacesWith3DEdge(
folded,
ear.layer.constraints3DFaceClusters(folded),
);
const orders = solveOverlapFacesWith3DEdge(folded);
expect(edgeFace3DOverlaps).toHaveLength(20);
expect(Object.keys(orders)).toHaveLength(20);
// inside tortillas: 18, 23, 24, 26
// these all have only one 3D tortilla constraint, with
// 18: (19-23), 23: (34-26) ...
// then four tortillas: 3, 11, 17, 28 all have four instances
// three of which are bundled up in the corner, 3 non flat edges,
// and the last is the big face from the neighboring counter-clockwise group
// everything here checks out.
expect(edgeFace3DOverlaps).toMatchObject([
{ edge: 32, tortilla: 26, coplanar: 25, angled: 24 },
{ edge: 42, tortilla: 18, coplanar: 19, angled: 23 },
{ edge: 24, tortilla: 3, coplanar: 35, angled: 34 },
{ edge: 25, tortilla: 3, coplanar: 36, angled: 7 },
{ edge: 51, tortilla: 3, coplanar: 28, angled: 23 },
{ edge: 52, tortilla: 3, coplanar: 6, angled: 5 },
{ edge: 20, tortilla: 11, coplanar: 27, angled: 25 },
{ edge: 21, tortilla: 11, coplanar: 2, angled: 0 },
{ edge: 22, tortilla: 11, coplanar: 13, angled: 1 },
{ edge: 23, tortilla: 11, coplanar: 3, angled: 26 },
{ edge: 18, tortilla: 17, coplanar: 30, angled: 9 },
{ edge: 19, tortilla: 17, coplanar: 11, angled: 24 },
{ edge: 53, tortilla: 17, coplanar: 10, angled: 8 },
{ edge: 54, tortilla: 17, coplanar: 32, angled: 33 },
{ edge: 49, tortilla: 28, coplanar: 16, angled: 14 },
{ edge: 50, tortilla: 28, coplanar: 20, angled: 19 },
{ edge: 55, tortilla: 28, coplanar: 17, angled: 18 },
{ edge: 56, tortilla: 28, coplanar: 21, angled: 15 },
{ edge: 30, tortilla: 24, coplanar: 33, angled: 18 },
{ edge: 44, tortilla: 23, coplanar: 34, angled: 26 },
]);
expect(planes).toMatchObject([
{ normal: [0, 1, 0], origin: [0, 2, 0] },
{ normal: [0, 1, 0], origin: [0, 3, 0] },
{ normal: [0, 0, -1], origin: [0, 0, -0] },
{ normal: [0, 0, -1], origin: [0, 0, -1] },
{ normal: [1, 0, 0], origin: [2, 0, 0] },
{ normal: [1, 0, 0], origin: [3, 0, 0] },
]);
expect(faces_plane[3]).toBe(3);
expect(faces_plane[11]).toBe(3);
expect(faces_plane[17]).toBe(3);
expect(faces_plane[28]).toBe(3);
// to ensure that the orders (1, 2) are correct.
expect(faces_winding[3]).toBe(false);
expect(faces_winding[11]).toBe(false);
expect(faces_winding[17]).toBe(false);
expect(faces_winding[28]).toBe(false);
expect(orders).toMatchObject({
// the four inner most layer orders
"25 26": 1,
"18 19": 1,
"24 33": 2,
"23 34": 1,
// the four tortillas (3, 11, 17, 28) paired with themselves
// apparently, 3 appears to be below 28 and both have "true" winding
// however, the plane's normal is [0, 0, -1], all data is flipped, so,
// in reality, 3 is above 28, and both have "false" winding
"3 28": 1, // 3 is above 28, even though from above, 3 appears to be below 28
"17 28": 2, // 17 is below 28
"11 17": 2, // 11 is below 17
"3 11": 2, // 3 is below 11
// tortilla 3
"3 35": 1,
"3 36": 1,
"3 6": 1,
// tortilla 11
"11 27": 1,
"2 11": 2,
"11 13": 1,
// tortilla 17
"17 30": 1,
"10 17": 2,
"17 32": 1,
// tortilla 28
"16 28": 2,
"20 28": 2,
"21 28": 2,
});
});
test("getOverlapFacesWith3DEdge, maze-u", () => {
const foldfile = fs.readFileSync(
"./tests/files/fold/maze-u.fold",
"utf-8",
);
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const edgeFace3DOverlaps = ear.layer.getOverlapFacesWith3DEdge(
folded,
ear.layer.constraints3DFaceClusters(folded),
);
const orders = solveOverlapFacesWith3DEdge(folded);
expect(edgeFace3DOverlaps).toHaveLength(64);
expect(Object.keys(orders)).toHaveLength(60);
expect(edgeFace3DOverlaps).toMatchObject([
{ edge: 39, tortilla: 17, coplanar: 6, angled: 10 }, // dup A
{ edge: 58, tortilla: 17, coplanar: 4, angled: 31 },
{ edge: 59, tortilla: 17, coplanar: 5, angled: 12 },
{ edge: 60, tortilla: 17, coplanar: 11, angled: 13 },
{ edge: 61, tortilla: 17, coplanar: 16, angled: 14 },
{ edge: 62, tortilla: 17, coplanar: 18, angled: 15 },
{ edge: 67, tortilla: 17, coplanar: 18, angled: 21 },
{ edge: 68, tortilla: 17, coplanar: 22, angled: 23 },
{ edge: 69, tortilla: 17, coplanar: 26, angled: 28 },
{ edge: 70, tortilla: 17, coplanar: 30, angled: 29 },
{ edge: 71, tortilla: 17, coplanar: 35, angled: 33 },
{ edge: 72, tortilla: 17, coplanar: 6, angled: 7 }, // dup A
{ edge: 91, tortilla: 42, coplanar: 40, angled: 47 },
{ edge: 92, tortilla: 42, coplanar: 39, angled: 46 },
{ edge: 93, tortilla: 42, coplanar: 48, angled: 49 },
{ edge: 94, tortilla: 42, coplanar: 4, angled: 31 },
{ edge: 108, tortilla: 42, coplanar: 57, angled: 60 },
{ edge: 109, tortilla: 42, coplanar: 58, angled: 61 },
{ edge: 110, tortilla: 42, coplanar: 62, angled: 50 },
{ edge: 111, tortilla: 42, coplanar: 6, angled: 7 },
{ edge: 123, tortilla: 42, coplanar: 43, angled: 44 },
{ edge: 124, tortilla: 42, coplanar: 41, angled: 45 },
{ edge: 91, tortilla: 51, coplanar: 40, angled: 47 },
{ edge: 92, tortilla: 51, coplanar: 39, angled: 46 },
{ edge: 93, tortilla: 51, coplanar: 48, angled: 49 },
{ edge: 94, tortilla: 51, coplanar: 4, angled: 31 },
{ edge: 108, tortilla: 51, coplanar: 57, angled: 60 },
{ edge: 109, tortilla: 51, coplanar: 58, angled: 61 },
{ edge: 110, tortilla: 51, coplanar: 62, angled: 50 },
{ edge: 111, tortilla: 51, coplanar: 6, angled: 7 },
{ edge: 123, tortilla: 51, coplanar: 43, angled: 44 },
{ edge: 124, tortilla: 51, coplanar: 41, angled: 45 },
{ edge: 134, tortilla: 74, coplanar: 6, angled: 64 }, // dup B
{ edge: 153, tortilla: 74, coplanar: 35, angled: 33 },
{ edge: 154, tortilla: 74, coplanar: 63, angled: 69 },
{ edge: 155, tortilla: 74, coplanar: 67, angled: 70 },
{ edge: 156, tortilla: 74, coplanar: 73, angled: 71 },
{ edge: 157, tortilla: 74, coplanar: 72, angled: 68 },
{ edge: 162, tortilla: 74, coplanar: 72, angled: 78 },
{ edge: 163, tortilla: 74, coplanar: 79, angled: 77 },
{ edge: 164, tortilla: 74, coplanar: 82, angled: 85 },
{ edge: 165, tortilla: 74, coplanar: 86, angled: 84 },
{ edge: 166, tortilla: 74, coplanar: 90, angled: 87 },
{ edge: 167, tortilla: 74, coplanar: 6, angled: 10 }, // dup B
{ edge: 186, tortilla: 93, coplanar: 59, angled: 98 },
{ edge: 187, tortilla: 93, coplanar: 58, angled: 97 },
{ edge: 188, tortilla: 93, coplanar: 62, angled: 99 },
{ edge: 189, tortilla: 93, coplanar: 6, angled: 64 },
{ edge: 203, tortilla: 93, coplanar: 105, angled: 107 },
{ edge: 204, tortilla: 93, coplanar: 106, angled: 108 },
{ edge: 205, tortilla: 93, coplanar: 109, angled: 100 },
{ edge: 206, tortilla: 93, coplanar: 90, angled: 87 },
{ edge: 218, tortilla: 93, coplanar: 94, angled: 95 },
{ edge: 219, tortilla: 93, coplanar: 92, angled: 96 },
{ edge: 186, tortilla: 101, coplanar: 59, angled: 98 },
{ edge: 187, tortilla: 101, coplanar: 58, angled: 97 },
{ edge: 188, tortilla: 101, coplanar: 62, angled: 99 },
{ edge: 189, tortilla: 101, coplanar: 6, angled: 64 },
{ edge: 203, tortilla: 101, coplanar: 105, angled: 107 },
{ edge: 204, tortilla: 101, coplanar: 106, angled: 108 },
{ edge: 205, tortilla: 101, coplanar: 109, angled: 100 },
{ edge: 206, tortilla: 101, coplanar: 90, angled: 87 },
{ edge: 218, tortilla: 101, coplanar: 94, angled: 95 },
{ edge: 219, tortilla: 101, coplanar: 92, angled: 96 },
]);
expect(orders).toMatchObject({
"6 17":1,"4 17":1,"5 17":1,"11 17":1,"16 17":1,"17 18":2,"17 22":2,"17 26":2,"17 30":2,"17 35":2,"40 42":1,"39 42":1,"42 48":2,"4 42":1,"42 57":2,"42 58":2,"42 62":2,"6 42":1,"42 43":2,"41 42":1,"40 51":1,"39 51":1,"48 51":1,"4 51":1,"51 57":2,"51 58":2,"51 62":2,"6 51":1,"43 51":1,"41 51":1,"6 74":1,"35 74":1,"63 74":1,"67 74":1,"73 74":1,"72 74":1,"74 79":2,"74 82":2,"74 86":2,"74 90":2,"59 93":1,"58 93":1,"62 93":1,"6 93":1,"93 105":2,"93 106":2,"93 109":2,"90 93":1,"93 94":2,"92 93":1,"59 101":1,"58 101":1,"62 101":1,"6 101":1,"101 105":2,"101 106":2,"101 109":2,"90 101":1,"94 101":1,"92 101":1
});
});
test("getOverlapFacesWith3DEdge, Mooser's train", () => {
const FOLD = fs.readFileSync("./tests/files/fold/moosers-train.fold", "utf-8");
const folded = JSON.parse(FOLD);
ear.graph.populate(folded);
const epsilon = 1e-3;
const facesEdges3D = ear.layer.getOverlapFacesWith3DEdge(
folded,
ear.layer.constraints3DFaceClusters(folded, epsilon),
epsilon,
);
const orders = solveOverlapFacesWith3DEdge(folded, epsilon);
expect(facesEdges3D).toHaveLength(677);
expect(Object.keys(orders)).toHaveLength(665);
});
================================================
FILE: tests/layer.constraints3DEdges.test.js
================================================
import fs from "fs";
import { expect, test } from "vitest";
import ear from "../src/index.js";
// call ear.layer.getSolvable3DEdgePairs. prepare all necessary data to do so
const getSolvable3DEdgePairs = (graph) => {
const {
faces_plane,
facesFacesOverlap,
} = ear.layer.constraints3DFaceClusters(graph);
const edges_vertices2 = graph.edges_vertices.slice();
graph.edges_faces
.map((_, e) => e)
.filter(e => graph.edges_faces[e].length !== 2)
.forEach(e => delete edges_vertices2[e]);
const edgesEdgesOverlap = ear.graph.getEdgesEdgesCollinearOverlap({
vertices_coords: graph.vertices_coords, edges_vertices: edges_vertices2,
});
const edgePairs = ear.graph.connectedComponentsPairs(edgesEdgesOverlap);
const facesFacesLookup = ear.general.arrayArrayToLookupArray(facesFacesOverlap);
const {
tJunctions,
yJunctions,
bentFlatTortillas,
bentTortillas,
bentTortillasFlatTaco,
} = ear.layer.getSolvable3DEdgePairs({
edges_faces: graph.edges_faces,
faces_plane,
edgePairs,
facesFacesLookup,
});
return {
tJunctions: tJunctions.map(i => edgePairs[i]),
yJunctions: yJunctions.map(i => edgePairs[i]),
bentFlatTortillas: bentFlatTortillas.map(i => edgePairs[i]),
bentTortillas: bentTortillas.map(i => edgePairs[i]),
bentTortillasFlatTaco: bentTortillasFlatTaco.map(i => edgePairs[i]),
};
};
// call ear.layer.constraints3DEdges. prepare all necessary data to do so
const constraints3DEdges = (graph) => {
try {
const faceClusters = ear.layer.constraints3DFaceClusters(graph);
return {
...faceClusters,
...ear.layer.constraints3DEdges(graph, {
...faceClusters,
edgesEdgesOverlap: ear.graph.getEdgesEdgesCollinearOverlap(graph),
}),
};
} catch (error) {
return "error";
}
};
test("getSolvable3DEdgePairs, layer 3D special cases", () => {
const foldfile = fs.readFileSync("./tests/files/fold/layers-3d-edge-edge.fold", "utf-8");
const fold = JSON.parse(foldfile);
const frames = ear.graph.getFileFramesAsArray(fold);
const foldedForms = frames.map(frame => ({
...frame,
vertices_coords: ear.graph.makeVerticesCoordsFolded(frame),
}));
foldedForms.forEach(folded => ear.graph.populate(folded));
const results = foldedForms.map(getSolvable3DEdgePairs);
expect(results[0]).toMatchObject({
tJunctions: [],
yJunctions: [],
bentFlatTortillas: [[11, 14]],
bentTortillas: [],
bentTortillasFlatTaco: [],
});
expect(results[1]).toMatchObject({
tJunctions: [[13, 17]],
yJunctions: [],
bentFlatTortillas: [],
bentTortillas: [],
bentTortillasFlatTaco: [],
});
expect(results[2]).toMatchObject({
tJunctions: [],
yJunctions: [[13, 17]],
bentFlatTortillas: [],
bentTortillas: [],
bentTortillasFlatTaco: [],
});
expect(results[3]).toMatchObject({
tJunctions: [],
yJunctions: [],
bentFlatTortillas: [],
bentTortillas: [[13, 17]],
bentTortillasFlatTaco: [],
});
expect(results[4]).toMatchObject({
tJunctions: [],
yJunctions: [],
bentFlatTortillas: [],
bentTortillas: [],
bentTortillasFlatTaco: [[13, 17]],
});
expect(results[5]).toMatchObject({
tJunctions: [[23, 32]],
yJunctions: [],
bentFlatTortillas: [[26, 29]],
bentTortillas: [],
bentTortillasFlatTaco: [],
});
expect(results[6]).toMatchObject({
tJunctions: [],
yJunctions: [[25, 35]],
bentFlatTortillas: [],
bentTortillas: [[27, 33]],
bentTortillasFlatTaco: [],
});
expect(results[7]).toMatchObject({
tJunctions: [],
yJunctions: [],
bentFlatTortillas: [[15, 20], [16, 19]],
bentTortillas: [],
bentTortillasFlatTaco: [],
});
expect(results[8]).toMatchObject({
tJunctions: [],
yJunctions: [],
bentFlatTortillas: [],
bentTortillas: [],
bentTortillasFlatTaco: [],
});
expect(results[9]).toMatchObject({
tJunctions: [[13, 17]],
yJunctions: [],
bentFlatTortillas: [],
bentTortillas: [],
bentTortillasFlatTaco: [],
});
expect(results[10]).toMatchObject({
tJunctions: [],
yJunctions: [[13, 17]],
bentFlatTortillas: [],
bentTortillas: [],
bentTortillasFlatTaco: [],
});
});
test("constraints3DEdges, layer 3D special cases", () => {
const foldfile = fs.readFileSync("./tests/files/fold/layers-3d-edge-edge.fold", "utf-8");
const fold = JSON.parse(foldfile);
const frames = ear.graph.getFileFramesAsArray(fold);
const foldedForms = frames.map(frame => ({
...frame,
vertices_coords: ear.graph.makeVerticesCoordsFolded(frame),
}));
foldedForms.forEach(folded => ear.graph.populate(folded));
const results = foldedForms.map(constraints3DEdges);
// one flat tortilla-tortilla on top of a bent tortilla-tortilla
// this solves faces 0-4
expect(results[0]).toMatchObject({
faces_winding: [true, true, true, true, false],
facesFacesOverlap: [[4], [], [], [], [0]],
facePairs: ["0 4"],
orders: { "0 4": 2 }, // 1 or 2?
tortilla_tortilla: [],
taco_tortilla: [],
});
// a T-junction where the top T faces are coplanar
// this solves faces 1-4
expect(results[1]).toMatchObject({
faces_winding: [true, true, true, false, false, true],
facesFacesOverlap: [[], [4], [3], [2], [1], []],
facePairs: ["1 4", "2 3"],
orders: { "1 4": 2 },
tortilla_tortilla: [],
taco_tortilla: [],
});
// an Y-junction where the top two faces are not coplanar
// this solves faces 1-4
expect(results[2]).toMatchObject({
faces_winding: [true, true, true, false, false, true],
facesFacesOverlap: [[], [4], [3], [2], [1], []],
facePairs: ["1 4", "2 3"],
orders: { "1 4": 2 },
tortilla_tortilla: [],
taco_tortilla: [],
});
// a bent-tortilla-tortilla (next to a flat tortilla-tortilla)
// no orders are solved, but bentTortillaTortillas condition is generated.
expect(results[3]).toMatchObject({
faces_winding: [true, true, true, false, false, false],
facesFacesOverlap: [[5], [4], [3], [2], [1], [0]],
facePairs: ["0 5", "1 4", "2 3"],
orders: {},
tortilla_tortilla: [[0, 1, 5, 4]],
taco_tortilla: [],
});
expect(results[4]).toMatchObject({
faces_winding: [
true, false, false, true, true, true,
],
facesFacesOverlap: [
[4, 1], [0, 4], [3], [2], [0, 1], [],
],
facePairs: ["0 4", "0 1", "1 4", "2 3"],
orders: {},
tortilla_tortilla: [],
taco_tortilla: [[0, 4, 1]],
});
// contains two: an bent-tortilla-tortilla and a T-junction.
expect(results[5]).toMatchObject({
faces_winding: [
true, true, true, true, true, true, true, false, false, false, true,
],
facesFacesOverlap: [
[], [9], [8], [7], [], [], [], [3], [2], [1], [],
],
facePairs: ["1 9", "2 8", "3 7"],
orders: { "1 9": 1, "3 7": 1 },
tortilla_tortilla: [],
taco_tortilla: [],
});
// contains two: a bent-flat-tortilla and an Y-junction
expect(results[6]).toMatchObject({
faces_winding: [
true, true, true, true, true, false, true, false, false, false, false, true,
],
facesFacesOverlap: [
[], [10], [9], [8], [7, 5, 6], [4, 7, 6], [4, 5, 7], [4, 5, 6], [3], [2], [1], [],
],
facePairs: ["1 10", "2 9", "3 8", "4 7", "4 5", "4 6", "5 7", "5 6", "6 7"],
orders: { "1 10": 1 },
tortilla_tortilla: [[2, 3, 9, 8]],
taco_tortilla: [],
});
expect(results[7]).toMatchObject("error");
// expect(results[8]).toMatchObject("error");
expect(results[8]).toMatchObject({
faces_winding: [
true, true, true, true, true,
],
facesFacesOverlap: [
[], [], [], [], [],
],
facePairs: [],
orders: {},
tortilla_tortilla: [],
taco_tortilla: [],
});
// expect(results[9]).toMatchObject("error");
expect(results[9]).toMatchObject({
faces_winding: [
true, true, true, false, false, true,
],
facesFacesOverlap: [
[], [4], [3], [2], [1], [],
],
facePairs: ["1 4", "2 3"],
orders: { "1 4": 1 },
tortilla_tortilla: [],
taco_tortilla: [],
});
// expect(results[10]).toMatchObject("error");
expect(results[10]).toMatchObject({
faces_winding: [
true, true, true, false, false, true,
],
facesFacesOverlap: [
[], [4], [3], [2], [1], [],
],
facePairs: ["1 4", "2 3"],
orders: { "1 4": 1 },
tortilla_tortilla: [],
taco_tortilla: [],
});
});
test("constraints3DEdges, maze-u", () => {
const foldfile = fs.readFileSync("./tests/files/fold/maze-u.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const {
// planes_transform,
// faces_plane,
// faces_cluster,
// faces_winding,
// faces_polygon,
// faces_center,
clusters_faces,
clusters_graph,
clusters_transform,
// facesFacesOverlap,
facePairs,
orders,
tortilla_tortilla,
taco_tortilla,
} = constraints3DEdges(folded);
const {
tJunctions,
yJunctions,
bentFlatTortillas,
bentTortillas,
bentTortillasFlatTaco,
} = getSolvable3DEdgePairs(folded);
expect(facePairs).toHaveLength(467);
// expect(pairs_data).toHaveLength(152);
expect(clusters_faces).toHaveLength(4);
expect(clusters_graph).toHaveLength(4);
expect(clusters_transform).toHaveLength(4);
expect(yJunctions).toHaveLength(0);
expect(tJunctions).toHaveLength(82);
expect(bentFlatTortillas).toHaveLength(0);
expect(bentTortillas).toHaveLength(70);
expect(bentTortillasFlatTaco).toHaveLength(16);
expect(yJunctions).toMatchObject([]);
expect(tJunctions).toMatchObject([
[39, 68], [39, 69], [39, 70], [39, 71], [58, 62], [58, 72], [59, 62], [59, 72], [60, 62], [60, 72], [61, 62], [61, 72], [67, 68], [67, 69], [67, 70], [67, 71], [91, 108], [91, 109], [91, 110], [91, 111], [91, 124], [92, 108], [92, 109], [92, 110], [92, 111], [92, 124], [93, 108], [93, 109], [93, 110], [93, 111], [93, 124], [94, 108], [94, 109], [94, 110], [94, 111], [94, 124], [108, 123], [109, 123], [110, 123], [111, 123], [123, 124], [134, 163], [134, 164], [134, 165], [134, 166], [153, 157], [153, 167], [154, 157], [154, 167], [155, 157], [155, 167], [156, 157], [156, 167], [162, 163], [162, 164], [162, 165], [162, 166], [186, 203], [186, 204], [186, 205], [186, 206], [186, 219], [187, 203], [187, 204], [187, 205], [187, 206], [187, 219], [188, 203], [188, 204], [188, 205], [188, 206], [188, 219], [189, 203], [189, 204], [189, 205], [189, 206], [189, 219], [203, 218], [204, 218], [205, 218], [206, 218], [218, 219],
]);
expect(bentTortillas).toMatchObject([
[39, 67], [58, 59], [58, 60], [58, 61], [59, 60], [59, 61], [60, 61], [62, 72], [63, 73], [68, 69], [68, 70], [68, 71], [69, 70], [69, 71], [70, 71], [91, 92], [91, 93], [91, 94], [91, 123], [92, 93], [92, 94], [92, 123], [93, 94], [93, 123], [94, 123], [108, 109], [108, 110], [108, 111], [108, 124], [109, 110], [109, 111], [109, 124], [110, 111], [110, 124], [111, 124], [134, 162], [153, 154], [153, 155], [153, 156], [154, 155], [154, 156], [155, 156], [157, 167], [158, 168], [163, 164], [163, 165], [163, 166], [164, 165], [164, 166], [165, 166], [186, 187], [186, 188], [186, 189], [186, 218], [187, 188], [187, 189], [187, 218], [188, 189], [188, 218], [189, 218], [203, 204], [203, 205], [203, 206], [203, 219], [204, 205], [204, 206], [204, 219], [205, 206], [205, 219], [206, 219],
]);
expect(orders).toMatchObject({
"10 23": 1, "10 28": 1, "10 29": 1, "10 33": 1, "15 31": 1, "7 31": 1,
"12 15": 2, "7 12": 1, "13 15": 2, "7 13": 1, "14 15": 2, "7 14": 1,
"21 23": 1, "21 28": 1, "21 29": 1, "21 33": 1, "47 60": 2, "47 61": 2,
"47 50": 2, "7 47": 1, "45 47": 1, "46 60": 2, "46 61": 2, "46 50": 2,
"7 46": 1, "45 46": 1, "49 60": 2, "49 61": 2, "49 50": 2, "7 49": 1,
"45 49": 1, "31 60": 2, "31 61": 2, "31 50": 2, "31 45": 2, "44 60": 2,
"44 61": 2, "44 50": 2, "7 44": 1, "44 45": 2, "64 77": 2, "64 85": 2,
"64 84": 2, "64 87": 2, "33 68": 2, "68 69": 1, "10 69": 1, "68 70": 1,
"10 70": 1, "68 71": 1, "10 71": 1, "77 78": 1, "78 85": 2, "78 84": 2,
"78 87": 2, "98 107": 2, "98 108": 2, "98 100": 2, "87 98": 1, "96 98": 1,
"97 107": 2, "97 108": 2, "97 100": 2, "87 97": 1, "96 97": 1, "99 107": 2,
"99 108": 2, "99 100": 2, "87 99": 1, "96 99": 1, "64 107": 2, "64 108": 2,
"64 100": 2, "64 96": 2, "95 107": 2, "95 108": 2, "95 100": 2, "87 95": 1,
"95 96": 2,
});
expect(tortilla_tortilla).toMatchObject([
[6,10,18,21],[4,12,5,31],[4,13,11,31],[4,14,16,31],[5,13,11,12],[5,14,16,12],[11,14,16,13],[15,18,7,6],[21,32,10,9],[22,28,26,23],[22,29,30,23],[22,33,35,23],[26,29,30,28],[26,33,35,28],[29,35,33,30],[40,46,39,47],[40,49,48,47],[40,31,4,47],[40,44,43,47],[39,49,48,46],[39,31,4,46],[39,44,43,46],[48,31,4,49],[48,44,43,49],[4,44,43,31],[57,60,58,61],[57,60,62,50],[57,60,6,7],[57,60,41,45],[58,61,62,50],[58,61,6,7],[58,61,41,45],[50,62,7,6],[50,62,45,41],[6,7,41,45],[6,78,72,64],[33,63,69,35],[33,67,70,35],[33,73,71,35],[63,70,67,69],[63,71,73,69],[67,71,73,70],[68,72,10,6],[78,66,64,88],[77,79,85,82],[77,79,84,86],[77,79,87,90],[82,85,86,84],[82,85,90,87],[84,86,87,90],[59,97,58,98],[59,99,62,98],[59,64,6,98],[59,95,94,98],[58,99,62,97],[58,64,6,97],[58,95,94,97],[62,64,6,99],[62,95,94,99],[6,95,94,64],[105,107,106,108],[105,107,109,100],[105,107,90,87],[105,107,92,96],[106,108,109,100],[106,108,90,87],[106,108,92,96],[100,109,87,90],[100,109,96,92],[87,90,96,92]
]);
expect(taco_tortilla).toMatchObject([
[12, 32, 31], [12, 9, 31], [7, 32, 8], [7, 9, 8], [15, 32, 34],
[29, 21, 33], [15, 9, 34], [29, 10, 33], [33, 88, 69],
[33, 66, 69], [10, 88, 65], [10, 66, 65], [68, 88, 89],
[84, 78, 87], [68, 66, 89], [84, 64, 87],
]);
});
test("constraints3DEdges, Mooser's train, carriage only", () => {
const FOLD = fs.readFileSync(
"./tests/files/fold/moosers-train-carriage.fold",
"utf-8",
);
const graph = JSON.parse(FOLD);
const folded = {
...graph,
vertices_coords: ear.graph.makeVerticesCoordsFolded(graph),
};
ear.graph.populate(folded);
// face cluster stuff is test in other files: graph.faces.planes
const {
// planes_transform,
// faces_plane,
// faces_cluster,
// faces_winding,
// faces_polygon,
// faces_center,
// clusters_faces,
// clusters_graph,
// clusters_transform,
// facesFacesOverlap,
facePairs,
orders,
tortilla_tortilla,
taco_tortilla,
} = constraints3DEdges(folded);
const {
tJunctions,
yJunctions,
bentFlatTortillas,
bentTortillas,
bentTortillasFlatTaco,
} = getSolvable3DEdgePairs(folded);
expect(facePairs).toHaveLength(440);
expect(yJunctions).toHaveLength(0);
expect(tJunctions).toHaveLength(40);
expect(bentFlatTortillas).toHaveLength(0);
expect(bentTortillas).toHaveLength(80);
expect(bentTortillasFlatTaco).toHaveLength(68);
expect(tortilla_tortilla).toHaveLength(80);
expect(taco_tortilla).toHaveLength(68);
expect(Object.keys(orders)).toHaveLength(40);
expect(tJunctions).toMatchObject([
[32, 35], [32, 36], [33, 35], [33, 36], [34, 35], [34, 36], [35, 37],
[35, 38], [36, 37], [36, 38], [38, 40], [38, 41], [39, 40], [39, 41],
[40, 42], [40, 43], [40, 44], [41, 42], [41, 43], [41, 44], [244, 247],
[244, 248], [245, 247], [245, 248], [246, 247], [246, 248], [247, 249],
[247, 250], [248, 249], [248, 250], [250, 252], [250, 253], [251, 252],
[251, 253], [252, 254], [252, 255], [252, 256], [253, 254], [253, 255],
[253, 256],
]);
expect(bentTortillas).toMatchObject([
[32, 33], [32, 34], [32, 37], [32, 38], [33, 34], [33, 37], [33, 38],
[34, 37], [34, 38], [35, 36], [37, 38], [38, 39], [38, 42], [38, 43],
[38, 44], [39, 42], [39, 43], [39, 44], [40, 41], [42, 43], [42, 44],
[43, 44], [49, 196], [51, 169], [52, 134], [54, 101], [55, 56], [57, 58],
[57, 162], [58, 162], [60, 61], [60, 138], [61, 138], [62, 63], [79, 80],
[79, 81], [80, 81], [81, 82], [81, 83], [82, 83], [102, 243], [135, 241],
[140, 222], [140, 223], [164, 219], [164, 220], [170, 240], [197, 238],
[202, 203], [202, 204], [203, 204], [204, 205], [204, 206], [205, 206],
[217, 218], [219, 220], [222, 223], [224, 225], [244, 245], [244, 246],
[244, 249], [244, 250], [245, 246], [245, 249], [245, 250], [246, 249],
[246, 250], [247, 248], [249, 250], [250, 251], [250, 254], [250, 255],
[250, 256], [251, 254], [251, 255], [251, 256], [252, 253], [254, 255],
[254, 256], [255, 256],
]);
expect(bentTortillasFlatTaco).toMatchObject([
[55, 59], [56, 59], [57, 118], [57, 161], [57, 183], [57, 207], [58, 118],
[58, 161], [58, 183], [58, 207], [59, 62], [59, 63], [60, 84], [60, 115],
[60, 120], [60, 137], [61, 84], [61, 115], [61, 120], [61, 137], [78, 140],
[78, 222], [78, 223], [79, 189], [80, 189], [81, 121], [81, 189], [82, 121],
[83, 121], [84, 138], [112, 140], [112, 222], [112, 223], [115, 138],
[117, 204], [117, 205], [117, 206], [118, 162], [120, 138], [137, 138],
[140, 141], [140, 188], [141, 222], [141, 223], [161, 162], [162, 183],
[162, 207], [164, 165], [164, 180], [164, 186], [164, 201], [165, 219],
[165, 220], [180, 219], [180, 220], [185, 202], [185, 203], [185, 204],
[186, 219], [186, 220], [188, 222], [188, 223], [201, 219], [201, 220],
[217, 221], [218, 221], [221, 224], [221, 225],
]);
expect(orders).toMatchObject({
"16 19": 2, "16 20": 2, "17 19": 2, "17 20": 2, "18 19": 2, "18 20": 2, "19 21": 1, "19 22": 1, "20 21": 1, "20 22": 1, "22 24": 2, "22 25": 2, "23 24": 2, "23 25": 2, "24 26": 1, "24 27": 1, "24 28": 1, "25 26": 1, "25 27": 1, "25 28": 1, "0 123": 2, "0 128": 2, "91 123": 2, "91 128": 2, "102 123": 2, "102 128": 2, "123 136": 1, "123 139": 1, "128 136": 1, "128 139": 1, "112 139": 1, "101 139": 1, "112 114": 1, "101 114": 1, "99 112": 2, "112 141": 1, "112 144": 1, "99 101": 2, "101 141": 1, "101 144": 1,
});
});
test("constraints3DEdges, mooser's train", () => {
const foldfile = fs.readFileSync("./tests/files/fold/moosers-train.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const {
// planes_transform,
// faces_plane,
// faces_cluster,
// faces_winding,
// faces_polygon,
// faces_center,
clusters_faces,
clusters_graph,
clusters_transform,
// facesFacesOverlap,
facePairs,
orders,
tortilla_tortilla,
taco_tortilla,
} = constraints3DEdges(folded);
const {
tJunctions,
yJunctions,
bentFlatTortillas,
bentTortillas,
bentTortillasFlatTaco,
} = getSolvable3DEdgePairs(folded);
expect(facePairs).toHaveLength(1721);
expect(clusters_faces).toHaveLength(87);
expect(clusters_graph).toHaveLength(87);
expect(clusters_transform).toHaveLength(87);
expect(yJunctions).toHaveLength(52);
expect(tJunctions).toHaveLength(100);
expect(bentFlatTortillas).toHaveLength(0);
expect(bentTortillas).toHaveLength(234);
expect(bentTortillasFlatTaco).toHaveLength(208);
expect(tortilla_tortilla).toHaveLength(234);
expect(taco_tortilla).toHaveLength(208);
expect(Object.keys(orders)).toHaveLength(112);
});
test("constraints3DEdges and getSolvable3DEdgePairs, cube octagon", () => {
const foldfile = fs.readFileSync("./tests/files/fold/cube-octagon.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const {
// planes_transform,
// faces_plane,
// faces_cluster,
// faces_winding,
// faces_polygon,
// faces_center,
clusters_faces,
clusters_graph,
clusters_transform,
// facesFacesOverlap,
facePairs,
orders,
tortilla_tortilla,
taco_tortilla,
} = constraints3DEdges(folded);
const {
tJunctions,
yJunctions,
bentFlatTortillas,
bentTortillas,
bentTortillasFlatTaco,
} = getSolvable3DEdgePairs(folded);
expect(facePairs).toHaveLength(84);
expect(clusters_faces).toHaveLength(6);
expect(clusters_graph).toHaveLength(6);
expect(clusters_transform).toHaveLength(6);
expect(tJunctions).toMatchObject([]);
expect(yJunctions).toMatchObject([]);
expect(bentFlatTortillas).toMatchObject([
[18, 35], [19, 35], [21, 40], [22, 40], [23, 40], [24, 40], [26, 58],
[27, 58], [32, 39], [34, 50], [35, 68], [35, 69], [37, 57], [52, 55],
[53, 63], [53, 64], [53, 71], [53, 72], [58, 66], [58, 67],
]);
expect(bentTortillas).toMatchObject([
[18, 19], [18, 68], [18, 69], [19, 68], [19, 69], [21, 22],
[21, 23], [21, 24], [22, 23], [22, 24], [23, 24], [26, 27],
[26, 66], [26, 67], [27, 66], [27, 67], [63, 64], [63, 71],
[63, 72], [64, 71], [64, 72], [66, 67], [68, 69], [71, 72],
]);
expect(bentTortillasFlatTaco).toMatchObject([]);
expect(tortilla_tortilla).toMatchObject([
[11, 37, 40, 13], [11, 37, 10, 12], [11, 37, 41, 39], [13, 40, 12, 10],
[13, 40, 39, 41], [30, 33, 0, 2], [30, 33, 1, 17], [30, 33, 31, 4],
[0, 2, 1, 17], [0, 2, 31, 4], [1, 17, 31, 4], [42, 44, 9, 43],
[42, 45, 46, 43], [42, 8, 7, 43], [9, 45, 46, 44], [9, 8, 7, 44],
[18, 24, 23, 20], [18, 21, 22, 20], [18, 25, 19, 20], [23, 21, 22, 24],
[23, 25, 19, 24], [45, 7, 8, 46], [10, 12, 41, 39], [21, 19, 25, 22],
]);
expect(taco_tortilla).toMatchObject([]);
expect(Object.keys(orders)).toHaveLength(20);
});
test("constraints3DEdges and getSolvable3DEdgePairs, coplanar angles", () => {
const foldfile = fs.readFileSync("./tests/files/fold/layers-3d-edge-face.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = {
...fold,
vertices_coords: ear.graph.makeVerticesCoordsFolded(fold),
};
ear.graph.populate(folded);
const {
// planes_transform,
// faces_plane,
// faces_cluster,
// faces_winding,
// faces_polygon,
// faces_center,
// clusters_faces,
// clusters_graph,
// clusters_transform,
facesFacesOverlap,
facePairs,
orders,
tortilla_tortilla,
taco_tortilla,
} = constraints3DEdges(folded);
const {
tJunctions,
yJunctions,
bentFlatTortillas,
bentTortillas,
bentTortillasFlatTaco,
} = getSolvable3DEdgePairs(folded);
expect(facePairs).toMatchObject(["1 3", "1 4", "1 5", "3 4", "3 5", "4 5"]);
expect(facesFacesOverlap).toMatchObject([
[], [3, 4, 5], [], [1, 4, 5], [1, 3, 5], [1, 3, 4],
]);
expect(yJunctions).toHaveLength(0);
expect(tJunctions).toHaveLength(0);
expect(bentFlatTortillas).toHaveLength(0);
expect(bentTortillas).toHaveLength(0);
expect(bentTortillasFlatTaco).toHaveLength(0);
expect(tortilla_tortilla).toHaveLength(0);
expect(taco_tortilla).toHaveLength(0);
expect(Object.keys(orders)).toHaveLength(0);
});
test("constraints3DEdges and getSolvable3DEdgePairs, square tube", () => {
const foldfile = fs.readFileSync(
"./tests/files/fold/square-tube-with-overlap.fold",
"utf-8",
);
const fold = JSON.parse(foldfile);
const folded = {
...fold,
vertices_coords: ear.graph.makeVerticesCoordsFolded(fold),
};
ear.graph.populate(folded);
expect(getSolvable3DEdgePairs(folded)).toMatchObject({
tJunctions: [],
yJunctions: [],
bentFlatTortillas: [],
// four bent-tortillas
bentTortillas: [[12, 13], [14, 15], [21, 22], [23, 24]],
bentTortillasFlatTaco: [],
});
// console.log(JSON.stringify(constraints3DEdges(folded)));
const {
// planes_transform,
// faces_plane,
// faces_cluster,
// faces_winding,
// faces_polygon,
// faces_center,
// clusters_faces,
// clusters_graph,
// clusters_transform,
facesFacesOverlap,
facePairs,
orders,
tortilla_tortilla,
taco_tortilla,
} = constraints3DEdges(folded);
});
================================================
FILE: tests/layer.constraints3DFaces.test.js
================================================
import { expect, test } from "vitest";
import fs from "fs";
import ear from "../src/index.js";
test("makeSolverConstraints3D, subgraph components", () => {
const foldfile = fs.readFileSync(
"./tests/files/fold/layers-3d-edge-face.fold",
"utf-8",
);
const fold = JSON.parse(foldfile);
const frames = ear.graph.getFileFramesAsArray(fold);
const foldedForms = frames.map(frame => ({
...frame,
vertices_coords: ear.graph.makeVerticesCoordsFolded(frame),
}));
foldedForms.forEach(folded => ear.graph.populate(folded));
const results = foldedForms
.map(folded => ear.layer.constraints3DFaceClusters(folded));
expect(results[3].clusters_graph).toMatchObject([{
// vertices 0, 1, 5, 9 and 3, 4, 6, 7
// vertices_coords: [[0, 0], [2, 0],, [1, 0], [0, 0], [0, 1], [0, 1], [1, 1],, [2, 1]],
// edges 0, 4, 8, 9 and 3, 5, 11, 12
edges_vertices: [[0, 1],,, [3, 4], [5, 0], [6, 7],,, [9, 5], [9, 1],, [7, 3], [4, 6]],
edges_faces: [[0],,, [3], [0], [3],,, [0], [0],, [3], [3]],
edges_assignment: ["B",,, "B", "B", "B",,, "B", "V",, "M", "B"],
edges_foldAngle: [0,,, 0, 0, 0,,, 0, 120,, -60, 0],
// faces 0, 3
faces_vertices: [[0, 1, 9, 5],,, [3, 4, 6, 7]],
faces_edges: [[0, 9, 8, 4],,, [3, 12, 5, 11]],
faces_faces: [[],,, []],
// faces_center: [[1, 0.5],,, [0.5, 0.5]],
}, {
// vertices_coords: [, [-1, 0], [0, 0],,,,,, [0, 1], [-1, 1]],
// edges 1, 7, 9, 10
edges_vertices: [, [1, 2],,,,,, [8, 9],, [9, 1], [8, 2]],
edges_faces: [, [1],,,,,, [1],, [1], [1]],
edges_assignment: [, "B",,,,,, "B",, "V", "V"],
edges_foldAngle: [, 0,,,,,, 0,, 120, 120],
// faces 1
faces_vertices: [, [1, 2, 8, 9]],
faces_edges: [, [1, 10, 7, 9]],
faces_faces: [, []],
// faces_center: [, [-0.5, 0.5]],
}, {
// vertices_coords: [,, [-1.5, 0], [-0.5, 0],,,, [-0.5, 1] [-1.5, 1]],
// edges 2, 6, 10, 11
edges_vertices: [,, [2, 3],,,, [7, 8],,,, [8, 2], [7, 3]],
edges_faces: [,, [2],,,, [2],,,, [2], [2]],
edges_assignment: [,, "B",,,, "B",,,, "V", "M"],
edges_foldAngle: [,, 0,,,, 0,,,, 120, -60],
// faces 2
faces_vertices: [,, [2, 3, 7, 8]],
faces_edges: [,, [2, 11, 6, 10]],
faces_faces: [,, []],
// faces_center: [,, [-1, 0.5]],
}]);
});
test("makeSolverConstraints3D, Mooser's train, one fourth of carriage only", () => {
const FOLD = fs.readFileSync(
"./tests/files/fold/moosers-train-carriage-fourth.fold",
"utf-8",
);
const graph = JSON.parse(FOLD);
const folded = {
...graph,
vertices_coords: ear.graph.makeVerticesCoordsFolded(graph),
};
ear.graph.populate(folded);
// face cluster stuff is test in other files: graph.faces.planes
const {
// planes_transform,
// faces_plane,
// faces_cluster,
// faces_winding,
// faces_polygon,
// faces_center,
clusters_faces,
// clusters_graph,
// clusters_transform,
// facesFacesOverlap,
facePairs,
} = ear.layer.constraints3DFaceClusters(folded);
expect(facePairs).toMatchObject([
// bottom carriage, in front of wheel
"0 1", "0 37", "0 38", "0 39", "1 37", "1 38", "1 39",
// front of wheel
"2 15",
// back of wheel
"4 17",
// bottom carriage, all over
"5 36", "5 39", "5 6", "5 33", "5 34", "5 35", "5 37", "5 38", "6 33", "6 34", "6 37", "6 38", "6 35", "6 36", "6 39",
// back of carriage, mostly below hitch plane
"7 18", "7 25", "7 23", "7 24", "7 31", "7 19", "7 21",
// hitch joint plane
"8 9", "8 10", "8 11", "8 12", "8 13", "8 14", "9 10", "9 11", "9 12", "9 13", "9 14", "10 11", "10 12", "10 13", "10 14", "11 12", "11 13", "11 14", "12 13", "12 14", "13 14",
// back of carriage
"18 25", "18 23", "18 24", "18 31", "18 19", "18 21", "19 25", "19 23", "19 24", "19 31", "19 21", "20 22", "20 21", "20 24", "20 31", "21 25", "21 23", "21 24", "21 31", "21 22", "22 24", "22 31", "23 25", "23 24", "23 31", "24 25", "24 31", "25 31",
// large side of carriage
"26 29", "26 32", "26 27", "26 28", "27 29", "27 32", "27 28", "28 29", "28 32", "29 32",
// bottom of carriage
"33 34", "33 37", "33 38", "33 35", "33 36", "33 39", "34 37", "34 38", "34 35", "34 36", "34 39", "35 37", "35 38", "35 36", "35 39", "36 39", "36 37", "36 38", "37 38", "37 39", "38 39"
]);
expect(clusters_faces).toMatchObject([
// bottom of wheel
[3],
// bottom of carriage
[0, 1, 5, 6, 33, 34, 35, 36, 37, 38, 39],
// hitch joint plane
[8, 9, 10, 11, 12, 13, 14],
// top of carriage
[30],
// front side of wheel
[2, 15],
// back side of wheel
[4, 17],
// back of carriage
[7, 18, 19, 20, 21, 22, 23, 24, 25, 31],
// back of wheel
[16],
// big side of carriage
[26, 27, 28, 29, 32],
]);
});
================================================
FILE: tests/layer.constraints3d.test.js
================================================
import fs from "fs";
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("makeSolverConstraints, 2D and 3D comparison, crane", () => {
const foldfile = fs.readFileSync("./tests/files/fold/crane.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const flat = ear.layer.makeSolverConstraintsFlat(folded);
const three = ear.layer.makeSolverConstraints3D(folded);
expect(flat.constraints).toMatchObject(three.constraints);
expect(flat.facePairs).toMatchObject(three.facePairs);
expect(flat.faces_winding).toMatchObject(three.faces_winding);
expect(flat.orders).toMatchObject(three.orders);
});
test("makeSolverConstraints, 2D and 3D comparison, kabuto", () => {
const foldfile = fs.readFileSync("./tests/files/fold/kabuto.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const flat = ear.layer.makeSolverConstraintsFlat(folded);
const three = ear.layer.makeSolverConstraints3D(folded);
expect(flat.constraints).toMatchObject(three.constraints);
expect(flat.facePairs).toMatchObject(three.facePairs);
expect(flat.faces_winding).toMatchObject(three.faces_winding);
expect(flat.orders).toMatchObject(three.orders);
});
test("makeSolverConstraints, 2D and 3D comparison, kraft bird", () => {
const foldfile = fs.readFileSync("./tests/files/fold/kraft-bird-base.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = {
...fold,
vertices_coords: ear.graph.makeVerticesCoordsFlatFolded(fold),
};
ear.graph.populate(folded);
const flat = ear.layer.makeSolverConstraintsFlat(folded);
const three = ear.layer.makeSolverConstraints3D(folded);
expect(flat.constraints).toMatchObject(three.constraints);
expect(flat.facePairs).toMatchObject(three.facePairs);
expect(flat.faces_winding).toMatchObject(three.faces_winding);
expect(flat.orders).toMatchObject(three.orders);
});
test("makeSolverConstraints3D cube octagon", () => {
const foldfile = fs.readFileSync("./tests/files/fold/cube-octagon.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const expectedJSON = fs.readFileSync("./tests/files/json/cube-octagon-constraints.json", "utf-8");
const expected = JSON.parse(expectedJSON);
const solverConstraints = ear.layer.makeSolverConstraints3D(folded);
expect(solverConstraints).toMatchObject(expected);
});
// this tests all of the cases which were built on top of the 2D solver,
// things which examine the overlapping geometry in 3D and generate
// either additional solutions (orders) or conditions (tacos/tortillas/transitivity)
test("makeSolverConstraints3D layer 3D test cases", () => {
const foldfile = fs.readFileSync("./tests/files/fold/layers-3d-edge-edge.fold", "utf-8");
const fold = JSON.parse(foldfile);
const frames = ear.graph.getFileFramesAsArray(fold);
const foldedForms = frames.map(frame => ({
...frame,
vertices_coords: ear.graph.makeVerticesCoordsFolded(frame),
}));
foldedForms.forEach(folded => ear.graph.populate(folded));
const results = foldedForms.map(folded => {
try {
return ear.layer.makeSolverConstraints3D(folded);
} catch (error) {
return "error";
}
});
expect(results[0].constraints).toMatchObject({
taco_taco: [], taco_tortilla: [], tortilla_tortilla: [], transitivity: [],
});
expect(results[0].facePairs).toMatchObject(["0 4"]);
expect(results[0].orders).toMatchObject({ "0 4": 2 });
// face 0 is below face 4,
expect(results[0].faces_winding[0]).toBe(true);
expect(results[0].faces_winding[4]).toBe(false);
expect(results[1].constraints).toMatchObject({
taco_taco: [],
taco_tortilla: [],
tortilla_tortilla: [[1, 2, 4, 3]],
transitivity: [],
});
expect(results[1].facePairs).toMatchObject(["1 4", "2 3"]);
expect(results[1].orders).toMatchObject({ "1 4": 2, "2 3": 2 });
expect(results[2].constraints).toMatchObject({
taco_taco: [],
taco_tortilla: [],
tortilla_tortilla: [[1, 2, 4, 3]],
transitivity: [],
});
expect(results[2].facePairs).toMatchObject(["1 4", "2 3"]);
expect(results[2].orders).toMatchObject({ "1 4": 2, "2 3": 2 });
expect(results[3].constraints).toMatchObject({
taco_taco: [],
taco_tortilla: [],
tortilla_tortilla: [[1, 2, 4, 3], [0, 1, 5, 4]],
transitivity: [],
});
expect(results[3].facePairs).toMatchObject(["0 5", "1 4", "2 3"]);
expect(results[3].orders).toMatchObject({ "2 3": 2 });
// only 3 pairs of faces overlap each other: 1-9, 2-8, 3-7
// - 2 tortilla_tortilla between the overlapping 3 sets.
expect(results[5].constraints).toMatchObject({
taco_taco: [],
taco_tortilla: [],
tortilla_tortilla: [[1, 2, 9, 8], [2, 3, 8, 7]],
transitivity: [],
});
expect(results[5].facePairs).toMatchObject(["1 9", "2 8", "3 7"]);
// 1-9 via the 3d overlapping edges algorithm
// 3-7 via the 3d overlapping edges algorithm
expect(results[5].orders).toMatchObject({ "1 9": 1, "3 7": 1 });
// 3 pairs of faces overlap each other: 1-10, 2-9, 3-8
// then another group of 4 faces all overlap each other: 4, 5, 6, 7
// - 1 taco_taco in the group of overlapping 4 faces
// - 2 taco_tortilla faces 4 and 7 have a "F" edge
// - 3 tortilla_tortilla where 1-2-10-9 and 3-4-8-7 are "F" tortillas
// and 2-3-9-8 is a 3D-bent-tortilla at 90 degrees
expect(results[6].constraints).toMatchObject({
taco_taco: [[4, 6, 5, 7]],
taco_tortilla: [[5, 4, 6], [5, 7, 6]],
tortilla_tortilla: [[1, 2, 10, 9], [3, 4, 8, 7], [2, 3, 9, 8]],
transitivity: [],
});
expect(results[6].facePairs).toMatchObject([
"1 10", "2 9", "3 8", "4 7", "4 5", "4 6", "5 7", "5 6", "6 7",
]);
// 1-10 is known via the 3d overlapping edges algorithm
// 4-5, 5-6, 6-7 are simply flat adjacent faces
expect(results[6].orders).toMatchObject({
"1 10": 1, "4 5": 2, "5 6": 2, "6 7": 1,
});
});
test("makeSolverConstraints3D coplanar angles 3D", () => {
const foldfile = fs.readFileSync("./tests/files/fold/layers-3d-edge-face.fold", "utf-8");
const fold = JSON.parse(foldfile);
const frame2 = ear.graph.flattenFrame(fold, 1);
const folded1 = {
...fold,
vertices_coords: ear.graph.makeVerticesCoordsFolded(fold),
};
ear.graph.populate(folded1);
const folded2 = {
...frame2,
vertices_coords: ear.graph.makeVerticesCoordsFolded(frame2),
};
ear.graph.populate(folded1);
ear.graph.populate(folded2);
// frame 2 has a longer side length that crosses one of the faces,
// but everything should remain consistent
expect(ear.layer.makeSolverConstraints3D(folded1))
.toMatchObject(ear.layer.makeSolverConstraints3D(folded2));
const {
constraints: { taco_taco, taco_tortilla, tortilla_tortilla, transitivity },
facePairs,
faces_winding,
orders,
} = ear.layer.makeSolverConstraints3D(folded1);
// faces 1, 3, 4, 5 are all coplanar.
// face 0 is base plane
// face 1 is angled plane
expect(facePairs).toMatchObject(["1 3", "1 4", "1 5", "3 4", "3 5", "4 5"]);
expect(faces_winding).toMatchObject([true, true, true, false, true, false]);
expect(orders).toMatchObject({ "3 4": 1, "4 5": 2, "1 5": 1 });
expect(taco_taco).toMatchObject([[3, 1, 4, 5]]);
expect(taco_tortilla).toMatchObject([[4, 1, 5], [4, 3, 5]]);
expect(tortilla_tortilla).toMatchObject([]);
expect(transitivity).toMatchObject([]);
// const result = ear.layer.getOverlappingParallelEdgePairs()
});
test("makeSolverConstraints3D panels 6x2", () => {
const foldfile = fs.readFileSync("./tests/files/fold/panels-6x2-90deg.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const {
constraints: { taco_taco, taco_tortilla, tortilla_tortilla, transitivity },
facePairs,
faces_winding,
orders,
} = ear.layer.makeSolverConstraints3D(folded);
[
// every permutation of pairs of these:
// 0, 1, 2, 3, 4, 5
"0 1", "0 2", "0 3", "0 4", "0 5", "1 2", "1 3", "1 4", "1 5",
"2 3", "2 4", "2 5", "3 4", "3 5", "4 5",
// every permutation of pairs of these:
// 6, 7, 8, 9, 10, 11
"6 7", "6 8", "6 9", "6 10", "6 11", "7 8", "7 9", "7 10", "7 11",
"8 9", "8 10", "8 11", "9 10", "9 11", "10 11",
].forEach(key => expect(facePairs).toContain(key));
expect(faces_winding).toMatchObject([
true, false, true, false, true, false, true, false, true, false, true, false,
]);
expect(orders).toMatchObject({
"0 1": 2, "1 2": 2, "2 3": 2, "3 4": 1, "4 5": 1, "6 7": 2, "7 8": 2, "8 9": 2, "9 10": 1, "10 11": 1,
});
expect(taco_taco).toMatchObject([
[0, 2, 1, 3],
[0, 4, 1, 5],
[1, 3, 2, 4],
[2, 4, 3, 5],
[6, 8, 7, 9],
[6, 10, 7, 11],
[7, 9, 8, 10],
[8, 10, 9, 11],
]);
expect(taco_tortilla).toMatchObject([]);
expect(tortilla_tortilla).toMatchObject([
[0, 6, 1, 7],
[0, 6, 2, 8],
[0, 6, 3, 9],
[0, 6, 4, 10],
[0, 6, 5, 11],
[1, 7, 2, 8],
[1, 7, 3, 9],
[1, 7, 4, 10],
[1, 7, 5, 11],
[2, 8, 3, 9],
[2, 8, 4, 10],
[2, 8, 5, 11],
[3, 9, 4, 10],
[3, 9, 5, 11],
[4, 10, 5, 11],
]);
expect(transitivity).toMatchObject([
[0, 2, 4],
[0, 2, 5],
[0, 3, 4],
[0, 3, 5],
[1, 2, 5],
[1, 3, 5],
[6, 8, 10],
[6, 8, 11],
[6, 9, 10],
[6, 9, 11],
[7, 8, 11],
[7, 9, 11],
]);
});
test("makeSolverConstraints3D maze-u", () => {
const foldfile = fs.readFileSync("./tests/files/fold/maze-u.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const expectedJSON = fs.readFileSync("./tests/files/json/maze-u-constraints.json", "utf-8");
const expected = JSON.parse(expectedJSON);
const solverConstraints = ear.layer.makeSolverConstraints3D(folded);
expect(solverConstraints).toMatchObject(expected);
});
================================================
FILE: tests/layer.constraintsFlat.test.js
================================================
import fs from "fs";
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("makeSolverConstraintsFlat, four panel square", () => {
const foldfile = fs.readFileSync("./tests/files/fold/panels-4x2.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const {
constraints: {
taco_taco,
taco_tortilla,
tortilla_tortilla,
transitivity,
},
} = ear.layer.makeSolverConstraintsFlat(folded);
// only two taco-tacos, one on the top and one bottom
expect(taco_taco).toMatchObject([
[0, 2, 1, 3],
[4, 6, 5, 7],
]);
expect(taco_tortilla).toMatchObject([
[1, 3, 2],
[5, 7, 6],
]);
// tortilla-tortilla between 4 sets of pairs, 0-4, 1-5, 2-6, 3-7
expect(tortilla_tortilla).toMatchObject([
[0, 4, 1, 5],
[0, 4, 2, 6],
[0, 4, 3, 7],
[1, 5, 2, 6],
[1, 5, 3, 7],
[2, 6, 3, 7],
]);
expect(transitivity).toMatchObject([]);
});
test("makeSolverConstraintsFlat, strip weave", () => {
const foldfile = fs.readFileSync("./tests/files/fold/strip-weave.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const {
constraints: {
taco_taco,
taco_tortilla,
tortilla_tortilla,
transitivity,
},
faces_winding,
} = ear.layer.makeSolverConstraintsFlat(folded);
// interestingly, this model, which obviously has various different layer
// solutions, results in no information for the solver.
expect(taco_taco).toMatchObject([]);
expect(taco_tortilla).toMatchObject([]);
expect(tortilla_tortilla).toMatchObject([]);
expect(transitivity).toMatchObject([[0, 1, 4]]);
expect(faces_winding).toMatchObject([true, false, true, false, false, true, false]);
});
test("makeSolverConstraintsFlat, zig-zag panels", () => {
const foldfile = fs.readFileSync("./tests/files/fold/panels-zig-zag.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const {
constraints: {
taco_taco,
taco_tortilla,
tortilla_tortilla,
transitivity,
},
} = ear.layer.makeSolverConstraintsFlat(folded);
expect(taco_taco).toMatchObject([
[0, 2, 4, 3],
[3, 1, 4, 2],
]);
expect(taco_tortilla).toMatchObject([
[0, 1, 4],
[3, 0, 4],
[2, 1, 3],
[1, 0, 2],
]);
expect(tortilla_tortilla).toMatchObject([]);
expect(transitivity).toMatchObject([[0, 1, 3]]);
});
// test("makeSolverConstraintsFlat, flat grid", () => {
// const foldfile = fs.readFileSync("./tests/files/fold/layers-flat-grid.fold", "utf-8");
// const fold = JSON.parse(foldfile);
// const folded = {
// ...fold,
// vertices_coords: ear.graph.makeVerticesCoordsFlatFolded(fold),
// }
// ear.graph.populate(folded);
// const result = ear.layer.makeSolverConstraintsFlat(folded);
// expect(result.constraints.taco_taco).toHaveLength(0);
// expect(result.constraints.taco_tortilla).toHaveLength(0);
// expect(result.constraints.tortilla_tortilla).toHaveLength(30);
// expect(result.constraints.transitivity).toHaveLength(0);
// expect(result).toMatchObject({
// facePairs: [
// "2 3", "4 23", "5 51", "6 50", "7 49", "8 48", "24 25", "26 32", "27 54", "28 55", "29 56", "30 31", "33 34", "35 36", "37 38", "39 40", "41 42", "43 44", "52 63", "53 62", "59 66",
// ],
// orders: {
// "2 3": 1, "24 25": 1, "30 31": 1, "33 34": 1, "37 38": 1, "41 42": 1,
// }
// });
// });
test("makeSolverConstraintsFlat, triangle strip", () => {
const fileStrip1 = fs.readFileSync("./tests/files/fold/triangle-strip.fold", "utf-8");
const fileStrip2 = fs.readFileSync("./tests/files/fold/triangle-strip-2.fold", "utf-8");
const foldStrip1 = JSON.parse(fileStrip1);
const foldStrip2 = JSON.parse(fileStrip2);
const folded1 = ear.graph.getFramesByClassName(foldStrip1, "foldedForm")[0];
const folded2 = ear.graph.getFramesByClassName(foldStrip2, "foldedForm")[0];
ear.graph.populate(folded1);
ear.graph.populate(folded2);
const res1 = ear.layer.makeSolverConstraintsFlat(folded1);
expect(res1.constraints.taco_taco.length).toBe(0);
expect(res1.constraints.taco_tortilla.length).toBe(0);
expect(res1.constraints.tortilla_tortilla.length).toBe(0);
expect(res1.constraints.transitivity.length).toBe(0);
const {
constraints: {
taco_taco,
taco_tortilla,
tortilla_tortilla,
transitivity,
},
} = ear.layer.makeSolverConstraintsFlat(folded2);
expect(taco_taco).toMatchObject([
[15, 4, 16, 5],
[17, 6, 27, 7],
[25, 8, 26, 9],
[23, 10, 24, 11],
[21, 12, 22, 13],
]);
expect(taco_tortilla.length).toBe(0);
expect(tortilla_tortilla).toMatchObject([
[13, 19, 21, 20],
[11, 21, 23, 22],
[11, 21, 10, 13],
[9, 23, 25, 24],
[9, 23, 8, 11],
[7, 25, 27, 26],
[7, 25, 6, 9],
[5, 27, 16, 17],
[5, 27, 4, 7],
[3, 16, 14, 15],
[3, 16, 2, 5],
[1, 14, 0, 3],
[14, 15, 2, 5],
[16, 17, 4, 7],
[26, 27, 9, 6],
[24, 25, 11, 8],
[22, 23, 13, 10],
]);
expect(transitivity).toMatchObject([[2, 3, 14], [18, 19, 20]]);
});
test("makeSolverConstraintsFlat, bird base", () => {
const cp = ear.graph.bird();
const folded = {
...cp,
vertices_coords: ear.graph.makeVerticesCoordsFlatFolded(cp),
};
ear.graph.populate(folded);
expect(ear.graph.getEdgesEdgesCollinearOverlap(folded).flat().length).toBe(194);
expect(ear.graph.getEdgesFacesOverlap(folded).flat().length).toBe(16);
const {
constraints: {
taco_taco,
taco_tortilla,
tortilla_tortilla,
transitivity,
},
} = ear.layer.makeSolverConstraintsFlat(folded);
expect(taco_taco).toMatchObject([
// long 22.5 edges, one side, 8 faces
// faces: 0-1, 5-6, 4-7, 8-11
[0, 4, 1, 7],
[0, 5, 1, 6],
[0, 8, 1, 11],
[4, 5, 7, 6],
[4, 8, 7, 11],
[5, 8, 6, 11],
// long 22.5 edges, the other side, 8 faces
// faces: 2-3, 13-14, 9-10, 12-15
[9, 12, 10, 15],
[9, 13, 10, 14],
[9, 2, 10, 3],
[12, 13, 15, 14],
[12, 2, 15, 3],
[13, 2, 14, 3],
// inside reverse fold (under armpit), one side: 0-4, 5-8
[0, 5, 4, 8],
// top 45 triangle hypotenuse, one side: 6-16, 7-19
[7, 6, 19, 16],
// inside reverse fold (under armpit), the other side: 3-13, 9-12
[9, 3, 12, 13],
// top 45 triangle hypotenuse, the other side: 14-18, 15-17
[15, 14, 17, 18],
]);
expect(taco_tortilla).toMatchObject([
[0, 1, 4],
[0, 11, 4],
[5, 1, 8],
[5, 11, 8],
[9, 2, 12],
[9, 10, 12],
[3, 2, 13],
[3, 10, 13],
[6, 1, 7],
[6, 19, 7],
[6, 11, 7],
[6, 16, 7],
[14, 2, 15],
[14, 18, 15],
[14, 10, 15],
[14, 17, 15],
[0, 6, 4],
[0, 7, 4],
[5, 6, 8],
[5, 7, 8],
[9, 14, 12],
[9, 15, 12],
[3, 14, 13],
[3, 15, 13],
]);
expect(tortilla_tortilla).toMatchObject([
[1, 2, 11, 10],
[18, 19, 17, 16],
[1, 19, 11, 16],
[2, 18, 10, 17],
[1, 19, 6, 6],
[1, 19, 7, 7],
[2, 18, 14, 14],
[2, 18, 15, 15],
[11, 16, 6, 6],
[11, 16, 7, 7],
[10, 17, 14, 14],
[10, 17, 15, 15],
]);
expect(transitivity).toMatchObject([
[0, 5, 7], [0, 5, 11], [0, 6, 7], [0, 6, 8], [0, 6, 11], [0, 7, 8],
[0, 7, 11], [1, 4, 5], [1, 4, 6], [1, 4, 8], [1, 4, 11], [1, 5, 7],
[1, 5, 11], [1, 6, 8], [1, 6, 11], [1, 7, 8], [1, 7, 11], [2, 9, 13],
[2, 9, 14], [2, 9, 15], [2, 10, 12], [2, 10, 13], [2, 10, 14], [2, 10, 15],
[2, 12, 13], [2, 12, 14], [2, 13, 15], [3, 9, 14], [3, 9, 15], [3, 10, 12],
[3, 10, 14], [3, 10, 15], [3, 12, 14], [3, 14, 15], [4, 5, 11], [4, 6, 8],
[4, 6, 11], [5, 7, 11], [6, 7, 8], [9, 13, 15], [9, 14, 15], [10, 12, 13],
[10, 12, 14], [10, 13, 15],
]);
});
test("makeSolverConstraintsFlat, kabuto", () => {
const foldfile = fs.readFileSync("./tests/files/fold/kabuto.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const {
constraints,
facePairs,
orders,
} = ear.layer.makeSolverConstraintsFlat(folded);
const expectedJSON = fs.readFileSync(
"./tests/files/json/kabuto-constraints.json",
"utf-8",
);
const expected = JSON.parse(expectedJSON);
expect(constraints).toMatchObject(expected);
expect(ear.graph.getEdgesEdgesCollinearOverlap(folded).flat().length).toBe(104);
expect(ear.graph.getEdgesFacesOverlap(folded).flat().length).toBe(138);
expect(constraints.taco_taco.length).toMatchObject(21);
expect(constraints.taco_tortilla.length).toMatchObject(88);
expect(constraints.tortilla_tortilla.length).toMatchObject(0);
expect(constraints.transitivity.length).toMatchObject(258);
expect(Object.keys(facePairs).length).toBe(117);
expect(Object.keys(orders).length).toBe(20);
});
test("makeSolverConstraintsFlat, crane", () => {
const foldfile = fs.readFileSync("./tests/files/fold/crane.fold", "utf-8");
const fold = JSON.parse(foldfile);
// const cp = ear.graph.getFramesByClassName(fold, "creasePattern")[0];
// console.log(JSON.stringify(cp));
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const epsilon = 1e-4;
const {
constraints: {
taco_taco,
taco_tortilla,
tortilla_tortilla,
transitivity,
},
facePairs,
orders,
} = ear.layer.makeSolverConstraintsFlat(folded, epsilon);
expect(ear.graph.getEdgesEdgesCollinearOverlap(folded, epsilon).flat().length).toBe(554);
expect(ear.graph.getFacesEdgesOverlap(folded, epsilon).flat().length).toBe(1167);
expect(taco_taco.length).toMatchObject(196);
expect(taco_tortilla.length).toMatchObject(1049);
expect(tortilla_tortilla.length).toMatchObject(0);
expect(transitivity.length).toMatchObject(5328);
expect(Object.keys(facePairs).length).toBe(838);
expect(Object.keys(orders).length).toBe(102);
});
test("makeSolverConstraintsFlat, flapping bird", () => {
const foldfile = fs.readFileSync("./tests/files/fold/randlett-flapping-bird.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
expect(ear.graph.getEdgesEdgesCollinearOverlap(folded).flat().length).toBe(114);
expect(ear.graph.getEdgesFacesOverlap(folded).flat().length).toBe(110);
const {
constraints: {
taco_taco,
taco_tortilla,
tortilla_tortilla,
transitivity,
},
facePairs,
orders,
} = ear.layer.makeSolverConstraintsFlat(folded);
expect(taco_taco.length).toMatchObject(27);
expect(taco_tortilla.length).toMatchObject(82);
expect(tortilla_tortilla.length).toMatchObject(15);
expect(transitivity.length).toMatchObject(168);
expect(Object.keys(facePairs).length).toBe(125);
expect(Object.keys(orders).length).toBe(30);
});
test("layer bird", () => {
const foldfile = fs.readFileSync("./tests/files/fold/kraft-bird-base.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = {
...fold,
vertices_coords: ear.graph.makeVerticesCoordsFlatFolded(fold, [6]),
};
ear.graph.populate(folded);
expect(ear.graph.getEdgesEdgesCollinearOverlap(folded).flat().length).toBe(3404);
expect(ear.graph.getEdgesFacesOverlap(folded).flat().length).toBe(7544);
const {
constraints: {
taco_taco,
taco_tortilla,
tortilla_tortilla,
transitivity,
},
facePairs,
orders,
} = ear.layer.makeSolverConstraintsFlat(folded, 1e-6);
expect(taco_taco.length).toBe(764);
expect(taco_tortilla.length).toBe(4860);
expect(tortilla_tortilla.length).toBe(2613);
expect(transitivity.length).toBe(54856);
expect(Object.keys(facePairs).length).toBe(5848);
expect(Object.keys(orders).length).toBe(338);
});
================================================
FILE: tests/layer.facesSide.test.js
================================================
import { expect, test } from "vitest";
import fs from "fs";
import ear from "../src/index.js";
test("overlappingParallelEdgePairs panel 4x2", () => {
const foldfile = fs.readFileSync("./tests/files/fold/panels-4x2.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const edgePairs = ear.graph.connectedComponentsPairs(
ear.graph.getEdgesEdgesCollinearOverlap(folded),
).filter(pair => pair.every(edge => folded.edges_faces[edge].length === 2));
// 8, 9, 10, 11 all overlap each other
// 6 and 14, and 7 and 15 overlap each other
expect(edgePairs).toMatchObject([
[6, 14], [7, 15],
[8, 9], [8, 10],
[8, 11], [9, 10],
[9, 11], [10, 11],
]);
});
test("overlappingParallelEdgePairs strip weave", () => {
const foldfile = fs.readFileSync("./tests/files/fold/strip-weave.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const edgePairs = ear.graph.connectedComponentsPairs(
ear.graph.getEdgesEdgesCollinearOverlap(folded),
).filter(pair => pair.every(edge => folded.edges_faces[edge].length === 2));
expect(edgePairs.length).toBe(0);
});
test("overlappingParallelEdgePairs triangle strip", () => {
const foldfile = fs.readFileSync("./tests/files/fold/triangle-strip.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const edgePairs = ear.graph.connectedComponentsPairs(
ear.graph.getEdgesEdgesCollinearOverlap(folded),
).filter(pair => pair.every(edge => folded.edges_faces[edge].length === 2));
expect(edgePairs.length).toBe(0);
});
test("overlappingParallelEdgePairs triangle strip-2", () => {
const foldfile = fs.readFileSync("./tests/files/fold/triangle-strip-2.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const edgePairs = ear.graph.connectedComponentsPairs(
ear.graph.getEdgesEdgesCollinearOverlap(folded),
).filter(pair => pair.every(edge => folded.edges_faces[edge].length === 2));
expect(edgePairs).toMatchObject([
[10, 29], [11, 45],
[12, 41], [12, 46],
[13, 38], [13, 42],
[14, 35], [14, 37],
[15, 31], [15, 36],
[16, 20], [16, 32],
[17, 21], [19, 33],
[20, 32], [30, 39],
[31, 36], [34, 43],
[35, 37], [38, 42],
[40, 47], [41, 46],
]);
});
test("edgesFacesSide 2D and 3D", () => {
const {
vertices_coords,
edges_vertices,
} = ear.graph.square();
const graph1 = ear.graph.populate({
vertices_coords,
edges_vertices: [...edges_vertices, [0, 2]],
faces_vertices: [[0, 1, 2], [2, 3, 0]],
});
const graph2 = ear.graph.populate({
vertices_coords,
edges_vertices: [[1, 0], [2, 1], [3, 2], [0, 3], [2, 0]],
faces_vertices: [[0, 1, 2], [2, 3, 0]],
});
graph1.faces_center = ear.graph.makeFacesCenterQuick(graph1);
graph2.faces_center = ear.graph.makeFacesCenterQuick(graph2);
expect(ear.layer.makeEdgesFacesSide(graph1))
.toMatchObject([[-1], [-1], [-1], [-1], [1, -1]]);
expect(ear.layer.makeEdgesFacesSide(graph2))
.toMatchObject([[1], [1], [1], [1], [-1, 1]]);
expect(ear.layer.makeEdgesFacesSide3D(graph1, {
...ear.graph.getEdgesLine(graph1),
...ear.graph.getFacesPlane(graph1),
})).toMatchObject([[-1], [-1], [-1], [-1], [1, -1]]);
expect(ear.layer.makeEdgesFacesSide3D(graph2, {
...ear.graph.getEdgesLine(graph2),
...ear.graph.getFacesPlane(graph2),
})).toMatchObject([[1], [1], [1], [1], [-1, 1]]);
});
test("edgesFacesSide strip weave", () => {
const foldfile = fs.readFileSync("./tests/files/fold/strip-weave.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
folded.faces_center = ear.graph.makeFacesCenterQuick(folded);
// all non boundary are taco-taco (same side)
expect(ear.layer.makeEdgesFacesSide(folded)).toMatchObject([
[1], [-1], [1], [-1], [-1], [1], [-1], [1], [-1, -1], [1, 1], [1], [-1],
[1], [-1], [1], [-1], [1, 1], [-1, -1], [1], [1, 1], [-1, -1], [-1], [-1],
]);
});
test("facesSide panels zig zag", () => {
const foldfile = fs.readFileSync("./tests/files/fold/panels-zig-zag.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
folded.faces_center = ear.graph.makeFacesCenterQuick(folded);
// only valley/mountains are 11, 12, 13, 14, all are tacos (same sign)
const edgesFacesSide = ear.layer.makeEdgesFacesSide(folded);
expect(edgesFacesSide).toMatchObject([
[1], [1], [-1], [1], [-1], [1], [1], [-1], [1], [-1], [1],
[1, 1], [-1, -1], [1, 1], [-1, -1],
[1],
]);
const edgePairs = ear.graph.connectedComponentsPairs(
ear.graph.getEdgesEdgesCollinearOverlap(folded),
).filter(pair => pair.every(edge => folded.edges_faces[edge].length === 2));
expect(edgePairs).toMatchObject([
[11, 13], [12, 14],
]);
// const tacos_faces = edgePairs.map(pair => pair.map(edge => folded.edges_faces[edge]));
const tacosFacesSide = ear.layer.makeEdgePairsFacesSide(folded, edgePairs);
expect(tacosFacesSide).toMatchObject([
[[1, 1], [1, 1]], [[-1, -1], [-1, -1]],
]);
});
test("facesSide panel 4x2", () => {
const foldfile = fs.readFileSync("./tests/files/fold/panels-4x2.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
folded.faces_center = ear.graph.makeFacesCenterQuick(folded);
const edgesFacesSide2D = ear.layer.makeEdgesFacesSide(folded);
const edgesFacesSide3D = ear.layer.makeEdgesFacesSide3D(folded, {
...ear.graph.getEdgesLine(folded),
...ear.graph.getFacesPlane(folded),
});
expect(folded.edges_assignment)
.toMatchObject([
"B", "B", "B", "B", "B", "B", "V", "V",
"F", "F", "F", "F", "V", "V", "M", "M",
"B", "B", "B", "B", "B", "B",
]);
expect(edgesFacesSide2D).toMatchObject([
// 6 boundary
[-1], [1], [-1], [1], [-1], [-1],
// 2 valley
[-1, -1], [-1, -1],
// 4 flat
[1, -1], [-1, 1], [1, -1], [-1, 1],
// 2 valley 2 mountain
[1, 1], [1, 1], [-1, -1], [-1, -1],
// 5 boundary
[1], [1], [1], [-1], [1], [-1],
]);
expect(edgesFacesSide3D).toMatchObject([
// 6 boundary
[-1], [-1], [-1], [-1], [-1], [-1],
// 2 valley
[-1, -1], [-1, -1],
// 4 flat
[1, -1], [1, -1], [1, -1], [1, -1],
// 2 valley 2 mountain
[-1, -1], [-1, -1], [-1, -1], [-1, -1],
// 5 boundary
[1], [1], [1], [1], [1], [1],
]);
const edgePairs = ear.graph.connectedComponentsPairs(
ear.graph.getEdgesEdgesCollinearOverlap(folded),
).filter(pair => pair.every(edge => folded.edges_faces[edge].length === 2));
const tacos_faces = edgePairs.map(pair => pair.map(edge => folded.edges_faces[edge]));
const tacosFacesSide = ear.layer.makeEdgePairsFacesSide(folded, edgePairs, tacos_faces);
expect(tacosFacesSide).toMatchObject([
[[-1, -1], [-1, -1]],
[[-1, -1], [-1, -1]],
[[1, -1], [1, -1]],
[[1, -1], [1, -1]],
[[1, -1], [1, -1]],
[[-1, 1], [-1, 1]],
[[-1, 1], [-1, 1]],
[[1, -1], [1, -1]],
]);
});
test("makeEdgesFacesSide3D, layer 3D cases", () => {
const foldfile = fs.readFileSync("./tests/files/fold/layers-3d-edge-edge.fold", "utf-8");
const fold = JSON.parse(foldfile);
const frames = ear.graph.getFileFramesAsArray(fold);
const foldedForms = frames.map(frame => ({
...frame,
vertices_coords: ear.graph.makeVerticesCoordsFolded(frame),
}));
foldedForms.forEach(folded => ear.graph.populate(folded));
const folded = foldedForms[1];
// const ignore = ear.layer.constraints3DFaceClusters(folded);
const edges_facesSides = ear.layer.makeEdgesFacesSide3D(folded, {
...ear.graph.getEdgesLine(folded),
...ear.graph.getFacesPlane(folded),
});
expect(edges_facesSides).toMatchObject([
[-1], [-1], [-1], [-1], [-1], [-1], [-1], [-1], [1], [1], [1], [1], [-1],
[1, -1],
[1, -1],
[1, 1],
[-1, 1],
[-1, -1],
[-1],
]);
});
================================================
FILE: tests/layer.general.test.js
================================================
import { expect, test } from "vitest";
import fs from "fs";
import ear from "../src/index.js";
test("overlappingParallelEdgePairs", () => {});
test("constraintToFacePairs", () => {});
test("constraintToFacePairsStrings", () => {});
test("solverSolutionToFaceOrders", () => {});
================================================
FILE: tests/layer.initialSolution.test.js
================================================
import { expect, test } from "vitest";
import fs from "fs";
import ear from "../src/index.js";
test("solveFlatAdjacentEdges, different axes", () => {
// shortcut methods
const solveFlatAdjacentEdges = (graph) => (
ear.layer.solveFlatAdjacentEdges(
graph,
ear.graph.makeFacesWinding(graph),
));
const solverSolutionToFaceOrders = (graph) => (
ear.layer.solverSolutionToFaceOrders(
ear.layer.solveFlatAdjacentEdges(
graph,
ear.graph.makeFacesWinding(graph),
),
ear.graph.makeFacesWinding(graph),
)
);
// two squares joined at an edge, folded to lie exactly on top of each other
// A: 0, 1, 2, 3 (counter)
// B: 5, 4, 1, 0 (clock)
const base = {
edges_vertices: [[0, 1], [1, 2], [2, 3], [3, 0], [1, 4], [4, 5], [5, 0]],
edges_assignment: ["V", "B", "B", "B", "B", "B", "B"],
faces_vertices: [[0, 1, 2, 3], [5, 4, 1, 0]],
}
const graphXYUp = ear.graph.populate({
...base,
vertices_coords: [[0, 0], [1, 0], [1, 1], [0, 1], [1, 1], [0, 1]],
});
const graphXYDown = ear.graph.populate({
...base,
vertices_coords: [[0, 0], [0, 1], [1, 1], [1, 0], [1, 1], [1, 0]],
});
// XY up
// face 0 is upright, plane normal will be [0, 0, 1]
expect(ear.graph.makeFacesWinding(graphXYUp)).toMatchObject([true, false]);
// in plane [0, 0, 1], face 0 is below face 1
expect(solveFlatAdjacentEdges(graphXYUp)).toMatchObject({ "0 1": 2 });
// face 0 is above face 1's normal
expect(solverSolutionToFaceOrders(graphXYUp)).toMatchObject([[0, 1, 1]]);
// face 0 is flipped, plane normal will be [0, 0, -1]
expect(ear.graph.makeFacesWinding(graphXYDown)).toMatchObject([false, true]);
// in plane [0, 0, -1], face 0 is above face 1
expect(solveFlatAdjacentEdges(graphXYDown)).toMatchObject({ "0 1": 1 });
// face 0 is above face 1's normal
expect(solverSolutionToFaceOrders(graphXYDown)).toMatchObject([[0, 1, 1]]);
});
test("solveFlatAdjacentEdges, four panel square", () => {
const foldfile = fs.readFileSync("./tests/files/fold/panels-4x2.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const faces_winding = ear.graph.makeFacesWinding(folded);
const adjacentOrders = ear.layer.solveFlatAdjacentEdges(folded, faces_winding);
// only two taco-tacos, one on the top and one bottom
expect(faces_winding).toMatchObject([
true, false, true, false, true, false, true, false,
]);
// 0 is below 1 (V)
// 1 is above 2 (V)
// 2 is above 3 (M)
// same with every face N+4
expect(adjacentOrders).toMatchObject({
"0 1": 2, "1 2": 1, "2 3": 1, "4 5": 2, "5 6": 1, "6 7": 1,
});
});
test("solveFlatAdjacentEdges, strip weave", () => {
const foldfile = fs.readFileSync("./tests/files/fold/strip-weave.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const faces_winding = ear.graph.makeFacesWinding(folded);
const adjacentOrders = ear.layer.solveFlatAdjacentEdges(folded, faces_winding);
expect(faces_winding).toMatchObject([
true, false, true, false, false, true, false,
]);
expect(adjacentOrders).toMatchObject({
"0 1": 2, "0 4": 2, "1 2": 1, "2 3": 2, "4 5": 1, "5 6": 2,
});
});
test("solveFlatAdjacentEdges, zig-zag panels", () => {
const foldfile = fs.readFileSync("./tests/files/fold/panels-zig-zag.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const faces_winding = ear.graph.makeFacesWinding(folded);
const adjacentOrders = ear.layer.solveFlatAdjacentEdges(folded, faces_winding);
expect(faces_winding).toMatchObject([true, true, false, true, false]);
expect(adjacentOrders).toMatchObject({
"0 4": 2, "1 2": 1, "2 3": 1, "3 4": 1,
});
});
test("solveFlatAdjacentEdges, triangle strip", () => {
const fileStrip1 = fs.readFileSync("./tests/files/fold/triangle-strip.fold", "utf-8");
const fileStrip2 = fs.readFileSync("./tests/files/fold/triangle-strip-2.fold", "utf-8");
const foldStrip1 = JSON.parse(fileStrip1);
const foldStrip2 = JSON.parse(fileStrip2);
const folded1 = ear.graph.getFramesByClassName(foldStrip1, "foldedForm")[0];
const folded2 = ear.graph.getFramesByClassName(foldStrip2, "foldedForm")[0];
ear.graph.populate(folded1);
ear.graph.populate(folded2);
const faces_winding1 = ear.graph.makeFacesWinding(folded1);
const adjacentOrders1 = ear.layer.solveFlatAdjacentEdges(folded1, faces_winding1);
const faces_winding2 = ear.graph.makeFacesWinding(folded2);
const adjacentOrders2 = ear.layer.solveFlatAdjacentEdges(folded2, faces_winding2);
expect(faces_winding1).toMatchObject([
true, false, false, true, true, false, false, true, true, false, false, true, true, false,
]);
expect(adjacentOrders1).toMatchObject({
"0 1": 2, "10 11": 2, "12 13": 2, "2 3": 2, "4 5": 2, "6 7": 2, "8 9": 2,
});
expect(faces_winding2).toMatchObject([
true, false, false, true, true, false, false, true, true, false,
false, true, true, false, false, false, true, true, true, false,
true, true, false, false, true, true, false, false,
]);
expect(adjacentOrders2).toMatchObject({
"0 1": 2, "10 11": 2, "12 13": 2, "15 16": 1, "17 27": 1, "18 19": 2, "19 20": 2, "2 3": 2, "21 22": 2, "23 24": 2, "25 26": 2, "4 5": 2, "6 7": 2, "8 9": 2,
});
});
test("solveFlatAdjacentEdges, bird base", () => {
const cp = ear.graph.bird();
const folded = {
...cp,
vertices_coords: ear.graph.makeVerticesCoordsFlatFolded(cp),
};
ear.graph.populate(folded);
const faces_winding = ear.graph.makeFacesWinding(folded);
const adjacentOrders = ear.layer.solveFlatAdjacentEdges(folded, faces_winding);
expect(faces_winding).toMatchObject([
true, false, false, true, false, true, false, true, false, false,
true, true, true, false, true, false, true, true, false, false,
]);
expect(adjacentOrders).toMatchObject({
"0 1": 2, "0 4": 1, "12 15": 2, "13 14": 1, "14 15": 1, "14 18": 2, "15 17": 1, "2 3": 1, "3 13": 1, "4 7": 1, "5 6": 2, "5 8": 1, "6 16": 1, "6 7": 2, "7 19": 2, "8 11": 1, "9 10": 1, "9 12": 2,
});
});
test("solveFlatAdjacentEdges, kabuto", () => {
const foldfile = fs.readFileSync("./tests/files/fold/kabuto.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const faces_winding = ear.graph.makeFacesWinding(folded);
const adjacentOrders = ear.layer.solveFlatAdjacentEdges(folded, faces_winding);
expect(faces_winding).toMatchObject([
true, false, true, false, true, false, true, true, false,
false, true, true, false, false, true, true, false, false,
]);
expect(adjacentOrders).toMatchObject({
"0 3": 2,
"0 8": 2,
"0 9": 2,
"1 10": 2,
"1 11": 2,
"1 2": 1,
"10 12": 2,
"11 13": 2,
"12 14": 2,
"13 15": 2,
"14 16": 1,
"15 17": 1,
"3 4": 1,
"4 5": 1,
"6 16": 2,
"6 8": 1,
"7 17": 2,
"7 9": 1,
"8 10": 2,
"9 11": 2,
});
});
test("solveFlatAdjacentEdges, crane", () => {
const foldfile = fs.readFileSync("./tests/files/fold/crane.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const faces_winding = ear.graph.makeFacesWinding(folded);
const adjacentOrders = ear.layer.solveFlatAdjacentEdges(folded, faces_winding);
expect(faces_winding[0]).toBe(true);
expect(Object.keys(adjacentOrders)).toHaveLength(102);
});
test("solveFlatAdjacentEdges, flapping bird", () => {
const foldfile = fs.readFileSync("./tests/files/fold/randlett-flapping-bird.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const faces_winding = ear.graph.makeFacesWinding(folded);
const adjacentOrders = ear.layer.solveFlatAdjacentEdges(folded, faces_winding);
expect(faces_winding[0]).toBe(true);
expect(Object.keys(adjacentOrders)).toHaveLength(30);
});
test("solveFlatAdjacentEdges, bird", () => {
const foldfile = fs.readFileSync("./tests/files/fold/kraft-bird-base.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = {
...fold,
vertices_coords: ear.graph.makeVerticesCoordsFlatFolded(fold, [6]),
};
ear.graph.populate(folded);
const faces_winding = ear.graph.makeFacesWinding(folded);
const adjacentOrders = ear.layer.solveFlatAdjacentEdges(folded, faces_winding);
expect(faces_winding[6]).toBe(true);
expect(Object.keys(adjacentOrders)).toHaveLength(338);
});
test("solveFlatAdjacentEdges, 3D cube-octagon", () => {
const foldfile = fs.readFileSync(
"./tests/files/fold/cube-octagon.fold",
"utf-8",
);
const fold = JSON.parse(foldfile);
// the second folded frame is the one without the flat assignments
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[1];
ear.graph.populate(folded);
const {
planes,
planes_faces,
// planes_transform,
// planes_clusters,
faces_winding,
faces_plane,
// faces_cluster,
// clusters_plane,
// clusters_faces,
} = ear.graph.getCoplanarAdjacentOverlappingFaces(folded);
const {
// planes_transform,
// faces_plane,
faces_cluster,
faces_winding: faces_winding2,
// faces_polygon,
// faces_center,
// clusters_faces,
clusters_graph,
// clusters_transform,
// facesFacesOverlap,
// facePairs,
} = ear.layer.constraints3DFaceClusters(folded);
expect(planes).toMatchObject([
{ normal: [0, 1, 0], origin: [0, 2, 0] },
{ normal: [0, 1, 0], origin: [0, 3, 0] },
{ normal: [0, 0, -1], origin: [0, 0, -0] },
{ normal: [0, 0, -1], origin: [0, 0, -1] },
{ normal: [1, 0, 0], origin: [2, 0, 0] },
{ normal: [1, 0, 0], origin: [3, 0, 0] },
]);
// ensure faces_winding is correct within its plane.
// noTransformWinding is performed on the input folded form which appears
// to have a flat plane in the XY, which when done proper is given the
// normal (0, 0, -1), so, when done proper, all windings will be flipped
// at least from the faces in planes_faces[3] (other planes will be corrupt
// as we are simply projecting 3D down into 2D creating degenerate faces)
expect(faces_winding).toMatchObject(faces_winding2);
const noTransformWinding = ear.graph.makeFacesWinding(folded);
planes_faces[3]
.forEach(f => expect(faces_winding[f]).not.toEqual(noTransformWinding[f]));
// it just so happens that in this example all planes match clusters
// making planes and clusters synonymous
expect(faces_plane).toMatchObject(faces_cluster);
// the vertices coords of the folded form
expect(folded.vertices_coords).toMatchObject([
[2, 2, 0], [2, 2, -1], [2, 1, -1], [3, 1, -1], [3, 2, -1], [3, 2, 0],
[2, 3, 0], [2, 3, -1], [1, 3, -1], [1, 2, -1], [2, 2, -1], [3, 3, 0],
[4, 3, -1], [3, 3, 0], [2, 2, 0], [1, 2, -1], [2, 2, -1], [1.5, 1.5, -1],
[3, 3, -1], [3.5, 3.5, -1], [3, 3, -1], [2, 3, -1], [2, 4, -1], [3, 2, -1],
[3, 1, -1], [3, 2, -1], [2, 3, 0], [2, 3, -1], [3, 2, 0], [1.5, 3.5, -1],
[2, 4, -1], [4, 2, -1], [3.5, 1.5, -1], [3, 3, -1], [4, 3, -1], [3, 4, -1],
]);
// the vertices coords from the big flat plane (3), this plane has been flipped,
// the normal is [0, 0, -1] so we should see the vertices appearing flipped.
expect(clusters_graph[3].vertices_coords).toMatchObject([
, [2, -2], [2, -1], [3, -1], [3, -2], ,
, [2, -3], [1, -3], [1, -2], [2, -2], ,
[4, -3], , , [1, -2], [2, -2], [1.5, -1.5],
[3, -3], [3.5, -3.5], [3, -3], [2, -3], [2, -4], [3, -2],
[3, -1], [3, -2], , [2, -3], , [1.5, -3.5],
[2, -4], [4, -2], [3.5, -1.5], [3, -3], [4, -3], [3, -4],
]);
// four tortillas in the big flat plane (#3): 3, 11, 17, 28
// have 1 instace each of overlaping one of the others
// plane #3 normal is [0, 0, -1], so looking at the folded form from above,
// all layer results should be sorted in flipped order.
expect(faces_plane[3]).toBe(3);
expect(faces_plane[11]).toBe(3);
expect(faces_plane[17]).toBe(3);
expect(faces_plane[28]).toBe(3);
// let's focus on the relationship between faces 2 and 3 for a moment
// cluster 3, faces 2 and 3 as polygons
const foldedPolygon2 = folded.faces_vertices[2]
.map(v => folded.vertices_coords[v]);
const foldedPolygon3 = folded.faces_vertices[3]
.map(v => folded.vertices_coords[v]);
const clusterGraphPolygon2 = clusters_graph[3].faces_vertices[2]
.map(v => clusters_graph[3].vertices_coords[v]);
const clusterGraphPolygon3 = clusters_graph[3].faces_vertices[3]
.map(v => clusters_graph[3].vertices_coords[v]);
// folded face 2 appears to wind clockwise
expect(foldedPolygon2).toMatchObject([[2, 2, -1], [2, 1, -1], [1, 2, -1]]);
// folded face 3 appears to wind counter-clockwise
expect(foldedPolygon3)
.toMatchObject([[2, 1, -1], [3, 1, -1], [3.5, 1.5, -1], [3, 2, -1], [1, 2, -1]]);
// folded face 2 appears to wind counter-clockwise
expect(clusterGraphPolygon2).toMatchObject([[2, -2], [2, -1], [1, -2]]);
// folded face 3 appears to wind clockwise
expect(clusterGraphPolygon3)
.toMatchObject([[2, -1], [3, -1], [3.5, -1.5], [3, -2], [1, -2]]);
// the cluster graph's winding direction is the one reflected
// in the faces_winding array.
// face 3 is flipped because, despite it appearing to wind counter-clockwise,
// the faces_winding is taken with respect to the plane's normal, [0, 0, -1],
// creating a winding which will appear flipped from the apparent view.
expect(faces_winding[2]).toBe(true);
expect(faces_winding[3]).toBe(false);
// solveFlatAdjacentEdges does not bother with vertices_coords, these two graphs
// will have the same result
expect(ear.layer.solveFlatAdjacentEdges(folded, faces_winding))
.toMatchObject(ear.layer.solveFlatAdjacentEdges(clusters_graph[3], faces_winding));
// face 2 is upright, face 3 is flipped
// if faces 3 is flipped, a valley fold from face 3 to 2 places 2 BELOW face 3
// note: this is just a subset of the total result.
expect(ear.layer.solveFlatAdjacentEdges(folded, faces_winding)).toMatchObject({
"2 3": 2, // 2 is below 3, even though from above, 2 appears to be above 3
"10 11": 2, // 10 is below 11
"16 17": 2, // 16 is below 17
"28 36": 1, // 28 is above 36
});
// here's the rest
expect(ear.layer.solveFlatAdjacentEdges(folded, faces_winding)).toMatchObject({
"14 15": 2,
"18 19": 1,
"25 26": 1,
"0 1": 1,
"11 27": 1,
"12 13": 2,
"20 28": 2,
"21 29": 1,
"9 30": 1,
"11 24": 1,
"25 27": 1,
"0 2": 1,
"1 13": 1,
"3 26": 1,
"34 35": 2,
"7 36": 2,
"11 12": 1,
"13 27": 2,
"22 24": 2,
"18 33": 2,
"22 26": 2,
"24 25": 1,
"30 32": 2,
"17 31": 1,
"6 35": 2,
"3 4": 1,
"3 35": 1,
"4 6": 2,
"18 22": 1,
"19 23": 1,
"22 23": 2,
"26 34": 1,
"5 7": 1,
"23 34": 1,
"24 33": 2,
"8 9": 1,
"14 16": 2,
"19 20": 2,
"23 28": 2,
"5 6": 2,
"8 10": 1,
"32 33": 1,
"17 18": 1,
"15 21": 2,
"17 32": 1,
"30 31": 1,
"20 21": 1,
"28 29": 1,
});
});
================================================
FILE: tests/layer.layer.solveLayerOrders.test.js
================================================
import { expect, test } from "vitest";
import fs from "fs";
import ear from "../src/index.js";
test("layer strip weave", () => {
const foldfile = fs.readFileSync("./tests/files/fold/strip-weave.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
const {
orders,
branches,
} = ear.layer.solveLayerOrders(folded);
// these are all adjacent faces
// the first call to propagate() resulted in nothing
expect(orders).toMatchObject({
"0 1": 2,
"4 5": 1,
"1 2": 1,
"2 3": 2,
"5 6": 2,
});
// three branches, only one pair in each
expect(branches).toMatchObject([
[{ orders: { "1 4": 1 } }, { orders: { "1 4": 2 } }],
[{ orders: { "2 5": 1 } }, { orders: { "2 5": 2 } }],
[{ orders: { "3 6": 1 } }, { orders: { "3 6": 2 } }],
]);
});
test("layer panels 4x2", () => {
const foldfile = fs.readFileSync("./tests/files/fold/panels-4x2.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
const {
orders,
branches,
} = ear.layer.solveLayerOrders(folded);
expect(orders).toMatchObject({
"0 1": 2,
"4 5": 2,
"1 2": 1,
"5 6": 1,
"2 3": 1,
"6 7": 1,
"1 3": 1,
"5 7": 1,
});
// only one branch
// the one branch has two solutions
expect(branches).toMatchObject([[
{ orders: { "0 3": 1, "4 6": 1, "4 7": 1, "0 2": 1 } },
{ orders: { "0 3": 2, "4 6": 2, "4 7": 2, "0 2": 2 } },
]]);
});
test("layer panels 3x3", () => {
const foldfile = fs.readFileSync("./tests/files/fold/panels-3x3.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
const expectedJSON = fs.readFileSync(
"./tests/files/json/panels-3x3-layer-solver.json",
"utf-8",
);
const expected = JSON.parse(expectedJSON);
delete expected.faces_winding;
const {
faces_winding,
...solution
} = ear.layer.solveLayerOrders(folded);
expect(solution).toMatchObject(expected);
});
test("layer panels 3x3 no solution", () => {
const foldfile = fs.readFileSync("./tests/files/fold/panels-3x3-invalid.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
try {
ear.layer.solveLayerOrders(folded);
} catch (error) {
expect(error).not.toBe(undefined);
}
});
test("layer panels 5", () => {
const foldfile = fs.readFileSync("./tests/files/fold/panels-5.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
const {
orders,
branches,
} = ear.layer.solveLayerOrders(folded);
expect(orders).toMatchObject({
"3 4": 1,
"2 3": 1,
"1 2": 1,
"0 1": 2,
"1 4": 1,
"1 3": 1,
"2 4": 1,
});
// two top-level possibilities
// - one complete solution
// - another with branches
expect(branches).toMatchObject([[
{ orders: { "0 3": 1, "0 4": 1, "0 2": 1 } },
{
orders: { "0 3": 2, "0 2": 2 },
branches: [[
{ orders: { "0 4": 1 } },
{ orders: { "0 4": 2 } },
]],
},
]]);
});
test("layer windmill faces with a cycle", () => {
const foldfile = fs.readFileSync("./tests/files/fold/windmill.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
const {
orders,
branches,
} = ear.layer.solveLayerOrders(folded);
expect(orders).toMatchObject({
"0 1": 1,
"7 8": 1,
"4 6": 1,
"0 6": 1,
"5 7": 1,
"0 2": 2,
"1 4": 1,
"4 5": 1,
"2 3": 2,
"3 6": 1,
"6 7": 2,
"3 8": 2,
"0 4": 1,
"3 7": 2,
"1 6": 1,
"4 7": 1,
"2 6": 1,
"0 3": 2,
"5 6": 1,
"6 8": 2,
});
expect(branches).toBe(undefined);
});
test("layer panels zig-zag", () => {
const foldfile = fs.readFileSync("./tests/files/fold/panels-zig-zag.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
const {
orders,
branches,
} = ear.layer.solveLayerOrders(folded);
expect(orders).toMatchObject({
"0 4": 2,
"3 4": 1,
"2 3": 1,
"1 2": 1,
"2 4": 1,
"1 4": 1,
"0 1": 2,
"0 3": 2,
"1 3": 1,
"0 2": 2,
});
expect(branches).toBe(undefined);
});
test("layer four flaps", () => {
const foldfile = fs.readFileSync("./tests/files/fold/layer-4-flaps.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
const {
orders,
branches,
} = ear.layer.solveLayerOrders(folded);
expect(orders).toMatchObject({
"0 1": 2,
"1 2": 1,
"1 3": 1,
"1 4": 1,
});
// four branches, each branch has 2 solutions
expect(branches.length).toBe(4);
expect(branches).toMatchObject([
[{ orders: { "0 4": 1 } }, { orders: { "0 4": 2 } }],
[{ orders: { "0 3": 1 } }, { orders: { "0 3": 2 } }],
[{ orders: { "2 3": 1 } }, { orders: { "2 3": 2 } }],
[{ orders: { "2 4": 1 } }, { orders: { "2 4": 2 } }],
]);
});
test("layer Kabuto", () => {
const foldfile = fs.readFileSync("./tests/files/fold/kabuto.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
const solution = ear.layer.solveLayerOrders(folded);
const expectedJSON = fs.readFileSync(
"./tests/files/json/kabuto-layer-solver.json",
"utf-8",
);
const expected = JSON.parse(expectedJSON);
delete expected.faces_winding;
expect(solution).toMatchObject(expected)
});
test("layer Randlett flapping bird", () => {
const foldfile = fs.readFileSync("./tests/files/fold/randlett-flapping-bird.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
const solution = ear.layer.solveLayerOrders(folded);
const expectedJSON = fs.readFileSync(
"./tests/files/json/randlett-flapping-bird-layer-solver.json",
"utf-8",
);
const expected = JSON.parse(expectedJSON);
delete expected.faces_winding;
expect(solution).toMatchObject(expected);
});
test("layer crane", () => {
const foldfile = fs.readFileSync("./tests/files/fold/crane.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
const solution = ear.layer.solveLayerOrders(folded);
const expectedJSON = fs.readFileSync(
"./tests/files/json/crane-layer-solver.json",
"utf-8",
);
const expected = JSON.parse(expectedJSON);
expect(solution).toMatchObject(expected);
});
// test("layer bird", () => {
// const foldfile = fs.readFileSync("./tests/files/fold/kraft-bird-base.fold", "utf-8");
// const fold = JSON.parse(foldfile);
// const folded = {
// ...fold,
// vertices_coords: ear.graph.makeVerticesCoordsFlatFolded(fold),
// }
// const solution = ear.layer.solveLayerOrders(folded);
// // const expectedJSON = fs.readFileSync(
// // "./tests/files/json/crane-layer-solver.json",
// // "utf-8",
// // );
// // const expected = JSON.parse(expectedJSON);
// // expect(solution).toMatchObject(expected);
// });
================================================
FILE: tests/layer.layer.solveLayerOrders3D.test.js
================================================
import { expect, test } from "vitest";
import fs from "fs";
import ear from "../src/index.js";
test("makeSolverConstraints3D panels 6x2", () => {
const foldfile = fs.readFileSync("./tests/files/fold/panels-6x2-90deg.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
ear.graph.populate(folded);
const {
orders,
branches,
} = ear.layer.solveLayerOrders3D(folded);
expect(orders).toMatchObject({
"0 1": 2, "1 2": 2, "2 3": 2, "3 4": 1, "4 5": 1, "6 7": 2, "7 8": 2, "8 9": 2, "9 10": 1, "10 11": 1, "0 3": 2, "1 3": 2, "3 5": 1, "6 9": 2, "7 9": 2, "9 11": 1, "0 2": 2, "6 8": 2,
})
expect(branches).toMatchObject([
[
{
orders: { "1 4": 1, "6 10": 1, "2 4": 1, "0 5": 1, "7 10": 1, "2 5": 1, "8 10": 1, "1 5": 1, "6 11": 1, "8 11": 1, "7 11": 1, "0 4": 1 },
},
{
orders: { "6 10": 2, "0 5": 2, "6 11": 2, "0 4": 2 },
// interesting that "0 5": 2, and "6 11": 2, aren't inside the "orders" section.
// is this okay?
branches: [
[
{
orders: { "1 4": 1, "2 5": 1, "8 10": 1, "7 10": 1, "8 11": 1, "1 5": 1, "7 11": 1, "2 4": 1 },
},
{
orders: { "1 4": 2, "2 5": 2, "8 10": 2, "7 10": 2, "8 11": 2, "1 5": 2, "7 11": 2, "2 4": 2 },
},
]
]
},
]
]);
});
================================================
FILE: tests/layer.propagate.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("propagate", () => {});
================================================
FILE: tests/layer.prototype.test.js
================================================
import fs from "fs";
import { expect, test } from "vitest";
import ear from "../src/index.js";
// ear.layer.faceOrdersToMatrix()
// ear.layer.facesLayerToEdgesAssignments()
// ear.layer.flipFacesLayer()
// ear.layer.makeEpsilon()
// ear.layer.constraintToFacePairs()
// ear.layer.constraintToFacePairsStrings()
test("no depth", () => {
const layerSolution = {
orders: { "1 2": 1 },
};
const result = ear.layer.gatherAll(layerSolution);
// only one solution
expect(result.length).toBe(1);
// the one solution only has one object
expect(result[0].length).toBe(1);
expect(result).toMatchObject([[{ "1 2": 1 }]]);
});
test("one depth with one 'and' and two 'or' branches", () => {
const layerSolution = {
orders: { "1 2": 1 },
branches: [
[
{
orders: { "3 4": 1 }
},
{
orders: { "3 4": 2 }
}
]
]
};
const result = ear.layer.gatherAll(layerSolution);
// two solutions
expect(result.length).toBe(2);
// each of the two solutions contains two objects
expect(result[0].length).toBe(2);
expect(result[1].length).toBe(2);
expect(result).toMatchObject([
[{ "1 2": 1 }, { "3 4": 1 }],
[{ "1 2": 1 }, { "3 4": 2 }],
]);
});
test("one depth with two 'and' and two 'or' branches", () => {
const layerSolution = {
orders: { "1 2": 1 },
branches: [
[
{
orders: { "3 4": 1 }
},
{
orders: { "3 4": 2 }
}
],
[
{
orders: { "5 6": 1 }
},
{
orders: { "5 6": 2 }
}
]
]
};
const result = ear.layer.gatherAll(layerSolution);
expect(result.length).toBe(4);
expect(result[0].length).toBe(3);
expect(result[1].length).toBe(3);
expect(result[2].length).toBe(3);
expect(result[3].length).toBe(3);
expect(result).toMatchObject([
[{ "1 2": 1 }, { "3 4": 1 }, { "5 6": 1 }],
[{ "1 2": 1 }, { "3 4": 1 }, { "5 6": 2 }],
[{ "1 2": 1 }, { "3 4": 2 }, { "5 6": 1 }],
[{ "1 2": 1 }, { "3 4": 2 }, { "5 6": 2 }],
]);
});
test("single-entry structure that mimics the Kabuto result", () => {
const layerSolution = {
orders: { "1 2": 1 },
branches: [
[
{
orders: { "3 4": 1 },
branches: [
[
{
orders: { "5 6": 1 }
},
{
orders: { "5 6": 2 }
}
]
]
},
{
orders: { "3 4": 2, "5 6": 1 }
}
],
[
{
orders: { "7 8": 1 },
branches: [
[
{
orders: { "9 10": 1 }
},
{
orders: { "9 10": 2 }
}
]
]
},
{
orders: { "7 8": 2, "9 10": 1 }
}
]
]
};
const result = ear.layer.gatherAll(layerSolution);
expect(result).toMatchObject([
[{ "1 2": 1 }, { "3 4": 1 }, { "5 6": 1 }, { "7 8": 1 }, { "9 10": 1 }],
[{ "1 2": 1 }, { "3 4": 1 }, { "5 6": 1 }, { "7 8": 1 }, { "9 10": 2 }],
[{ "1 2": 1 }, { "3 4": 1 }, { "5 6": 1 }, { "7 8": 2, "9 10": 1 }],
[{ "1 2": 1 }, { "3 4": 1 }, { "5 6": 2 }, { "7 8": 1 }, { "9 10": 1 }],
[{ "1 2": 1 }, { "3 4": 1 }, { "5 6": 2 }, { "7 8": 1 }, { "9 10": 2 }],
[{ "1 2": 1 }, { "3 4": 1 }, { "5 6": 2 }, { "7 8": 2, "9 10": 1 }],
[{ "1 2": 1 }, { "3 4": 2, "5 6": 1 }, { "7 8": 1 }, { "9 10": 1 }],
[{ "1 2": 1 }, { "3 4": 2, "5 6": 1 }, { "7 8": 1 }, { "9 10": 2 }],
[{ "1 2": 1 }, { "3 4": 2, "5 6": 1 }, { "7 8": 2, "9 10": 1 }],
]);
});
================================================
FILE: tests/layer.solver.2D.test.js
================================================
import fs from "fs";
import { expect, test } from "vitest";
import ear from "../src/index.js";
// mostly 2D.
// there is some overlap between 2D and 3D, for comparison sake.
test("2D layer solver, Randlett flapping bird", () => {
const foldfile = fs.readFileSync("./tests/files/fold/randlett-flapping-bird.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
const {
orders,
branches,
} = ear.layer(folded);
expect(orders).toMatchObject(folded.faceOrders);
expect(branches).toBe(undefined);
});
test("2D layer solver, preliminary fold", () => {
const FOLD = fs.readFileSync("./tests/files/fold/preliminary-offset-cp.fold", "utf-8");
const graph = JSON.parse(FOLD);
const vertices_coords = ear.graph.makeVerticesCoordsFlatFolded(graph);
const folded = { ...graph, vertices_coords };
const solution = ear.layer(folded);
const faceOrders = solution.faceOrders();
// going bottom up, two paths on either side
// 0 to 2 to 4 to 5
// 0 to 1 to 3 to 5
const faceOrdersStrings = faceOrders.map(order => JSON.stringify(order));
// 0 and 5, both facing each other
expect(faceOrdersStrings.includes(JSON.stringify([0, 5, 1]))
|| faceOrdersStrings.includes(JSON.stringify([5, 0, 1]))).toBe(true);
// 0 and 1, both facing each other
expect(faceOrdersStrings.includes(JSON.stringify([0, 1, 1]))
|| faceOrdersStrings.includes(JSON.stringify([1, 0, 1]))).toBe(true);
// 0 and 3, both facing same direction, 3 on top
expect(faceOrdersStrings.includes(JSON.stringify([0, 3, -1]))
|| faceOrdersStrings.includes(JSON.stringify([3, 0, 1]))).toBe(true);
// 1 and 3, both facing away from each other
expect(faceOrdersStrings.includes(JSON.stringify([1, 3, -1]))
|| faceOrdersStrings.includes(JSON.stringify([3, 1, -1]))).toBe(true);
// 1 and 5, both facing same direction, 1 on top
expect(faceOrdersStrings.includes(JSON.stringify([1, 5, 1]))
|| faceOrdersStrings.includes(JSON.stringify([5, 1, -1]))).toBe(true);
// 3 and 5, both facing each other
expect(faceOrdersStrings.includes(JSON.stringify([3, 5, 1]))
|| faceOrdersStrings.includes(JSON.stringify([5, 3, 1]))).toBe(true);
// 0 and 2, both facing each other
expect(faceOrdersStrings.includes(JSON.stringify([0, 2, 1]))
|| faceOrdersStrings.includes(JSON.stringify([2, 0, 1]))).toBe(true);
// 0 and 4, both facing same direction, 3 on top
expect(faceOrdersStrings.includes(JSON.stringify([0, 4, -1]))
|| faceOrdersStrings.includes(JSON.stringify([4, 0, 1]))).toBe(true);
// 2 and 4, both facing away from each other
expect(faceOrdersStrings.includes(JSON.stringify([2, 4, -1]))
|| faceOrdersStrings.includes(JSON.stringify([4, 2, -1]))).toBe(true);
// 2 and 5, both facing same direction, 1 on top
expect(faceOrdersStrings.includes(JSON.stringify([2, 5, 1]))
|| faceOrdersStrings.includes(JSON.stringify([5, 2, -1]))).toBe(true);
// 4 and 5, both facing each other
expect(faceOrdersStrings.includes(JSON.stringify([4, 5, 1]))
|| faceOrdersStrings.includes(JSON.stringify([5, 4, 1]))).toBe(true);
});
test("3D layer solver, preliminary fold", () => {
const FOLD = fs.readFileSync("./tests/files/fold/preliminary-offset-cp.fold", "utf-8");
const graph = JSON.parse(FOLD);
const vertices_coords = ear.graph.makeVerticesCoordsFlatFolded(graph);
const folded = { ...graph, vertices_coords };
const solution = ear.layer.layer3D(folded);
const faceOrders = solution.faceOrders();
// going bottom up, two paths on either side
// 0 to 2 to 4 to 5
// 0 to 1 to 3 to 5
const faceOrdersStrings = faceOrders.map(order => JSON.stringify(order));
// 0 and 5, both facing each other
expect(faceOrdersStrings.includes(JSON.stringify([0, 5, 1]))
|| faceOrdersStrings.includes(JSON.stringify([5, 0, 1]))).toBe(true);
// 0 and 1, both facing each other
expect(faceOrdersStrings.includes(JSON.stringify([0, 1, 1]))
|| faceOrdersStrings.includes(JSON.stringify([1, 0, 1]))).toBe(true);
// 0 and 3, both facing same direction, 3 on top
expect(faceOrdersStrings.includes(JSON.stringify([0, 3, -1]))
|| faceOrdersStrings.includes(JSON.stringify([3, 0, 1]))).toBe(true);
// 1 and 3, both facing away from each other
expect(faceOrdersStrings.includes(JSON.stringify([1, 3, -1]))
|| faceOrdersStrings.includes(JSON.stringify([3, 1, -1]))).toBe(true);
// 1 and 5, both facing same direction, 1 on top
expect(faceOrdersStrings.includes(JSON.stringify([1, 5, 1]))
|| faceOrdersStrings.includes(JSON.stringify([5, 1, -1]))).toBe(true);
// 3 and 5, both facing each other
expect(faceOrdersStrings.includes(JSON.stringify([3, 5, 1]))
|| faceOrdersStrings.includes(JSON.stringify([5, 3, 1]))).toBe(true);
// 0 and 2, both facing each other
expect(faceOrdersStrings.includes(JSON.stringify([0, 2, 1]))
|| faceOrdersStrings.includes(JSON.stringify([2, 0, 1]))).toBe(true);
// 0 and 4, both facing same direction, 3 on top
expect(faceOrdersStrings.includes(JSON.stringify([0, 4, -1]))
|| faceOrdersStrings.includes(JSON.stringify([4, 0, 1]))).toBe(true);
// 2 and 4, both facing away from each other
expect(faceOrdersStrings.includes(JSON.stringify([2, 4, -1]))
|| faceOrdersStrings.includes(JSON.stringify([4, 2, -1]))).toBe(true);
// 2 and 5, both facing same direction, 1 on top
expect(faceOrdersStrings.includes(JSON.stringify([2, 5, 1]))
|| faceOrdersStrings.includes(JSON.stringify([5, 2, -1]))).toBe(true);
// 4 and 5, both facing each other
expect(faceOrdersStrings.includes(JSON.stringify([4, 5, 1]))
|| faceOrdersStrings.includes(JSON.stringify([5, 4, 1]))).toBe(true);
});
test("2D layer solver, preliminary fold, layers linearized", () => {
const FOLD = fs.readFileSync("./tests/files/fold/preliminary-offset-cp.fold", "utf-8");
const graph = JSON.parse(FOLD);
const vertices_coords = ear.graph.makeVerticesCoordsFlatFolded(graph);
const folded = { ...graph, vertices_coords };
const solution = ear.layer(folded);
const faceOrders = solution.faceOrders();
// going bottom up, two paths on either side
// 0 to 2 to 4 to 5
// 0 to 1 to 3 to 5
// this just happens to generate 0, 1, 2, 3, 4, 5
// but a few others would still be valid.
const linearize = ear.graph.linearize2DFaces({ ...folded, faceOrders });
expect(linearize).toMatchObject([0, 1, 2, 3, 4, 5]);
});
test("2D layer solver, kabuto", () => {
const foldfile = fs.readFileSync("./tests/files/fold/kabuto.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
const solution = ear.layer(folded);
expect(solution.structure()).toMatchObject([
[[[[], []]], []],
[[[[], []]], []],
]);
const layerSolutions = solution.compileAll();
expect(layerSolutions).toHaveLength(9);
layerSolutions.forEach(orders => expect(orders).toHaveLength(117));
});
test("2D layer solver, kraft-bird", () => {
const foldfile = fs.readFileSync("./tests/files/fold/kraft-bird-base.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded = {
...fold,
vertices_coords: ear.graph.makeVerticesCoordsFlatFolded(fold),
};
const faceOrders = ear.layer(folded).faceOrders();
expect(faceOrders).toHaveLength(5848);
fs.writeFileSync(`./tests/tmp/kraft-bird-base-solved.fold`, JSON.stringify({
...folded,
faceOrders,
}));
});
// // takes about 2 seconds
// test("2D layer solver, zipper", () => {
// const foldfile = fs.readFileSync("./tests/files/fold/layers-zipper.fold", "utf-8");
// const fold = JSON.parse(foldfile);
// const folded = {
// ...fold,
// vertices_coords: ear.graph.makeVerticesCoordsFlatFolded(fold),
// }
// const result = ear.layer(folded);
// fs.writeFileSync(
// `./tests/tmp/layers-zipper-solution.fold`,
// JSON.stringify(result),
// );
// const {
// faces_winding,
// ...resultFlat
// } = ear.layer.solveLayerOrdersSingleBranches(folded);
// fs.writeFileSync(
// `./tests/tmp/layers-zipper-solution-flat.fold`,
// JSON.stringify(resultFlat),
// );
// });
================================================
FILE: tests/layer.solver.3D.test.js
================================================
import fs from "fs";
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("3D layer solver, all 3D special cases", () => {
const foldfile = fs.readFileSync("./tests/files/fold/layers-3d-edge-edge.fold", "utf-8");
const fold = JSON.parse(foldfile);
const frames = ear.graph.getFileFramesAsArray(fold);
const foldedForms = frames.map(frame => ({
...frame,
vertices_coords: ear.graph.makeVerticesCoordsFolded(frame),
}));
foldedForms.forEach(folded => ear.graph.populate(folded));
// the final
const results = foldedForms.map(graph => {
try {
return ear.layer.layer3D(graph);
} catch (error) {
return "error";
}
});
expect(results).toMatchObject([
// 0 and 4 face each other's normals
{ orders: [[0, 4, 1]] },
// both pairs of faces face each other's normals
{ orders: [[1, 4, 1], [2, 3, 1]] },
// same as above
{ orders: [[1, 4, 1], [2, 3, 1]] },
// all 3 pairs face into each other's normals
{ orders: [[2, 3, 1], [1, 4, 1], [0, 5, 1]] },
// 0-1 normals point away from each other
// 2-3 normals point towards each other
// 1-4 normals point towards each other
// 0-4 0 is above 4's normal
{ orders: [[0, 1, -1], [2, 3, 1], [1, 4, 1], [0, 4, 1]] },
// todo
{ orders: [[1, 9, -1], [3, 7, -1], [2, 8, -1]] },
// todo
{ orders: [
[1, 10, -1], [4, 5, 1], [5, 6, -1], [6, 7, -1], [4, 6, -1],
[5, 7, -1], [2, 9, -1], [4, 7, -1], [3, 8, -1]
] },
"error",
{ orders: [] }, // this is a layer-crossing error. undetected for now
"error",
"error",
]);
});
test("3D layer solver, cube octagon", () => {
const foldfile = fs.readFileSync("./tests/files/fold/cube-octagon.fold", "utf-8");
const fold = JSON.parse(foldfile);
const folded0 = ear.graph.getFramesByClassName(fold, "foldedForm")[0];
const folded1 = ear.graph.getFramesByClassName(fold, "foldedForm")[1];
const result0 = ear.layer.layer3D(folded0);
const result1 = ear.layer.layer3D(folded1);
expect(result0.orders).toMatchObject(folded0.faceOrders);
expect(result1.orders).toMatchObject(folded1.faceOrders);
expect(result0.branches).toBe(undefined);
expect(result1.branches).toBe(undefined);
});
test("3D layer solver, square-fish base", () => {
const FOLD = fs.readFileSync("./tests/files/fold/square-fish-3d.fold", "utf-8");
const graph = JSON.parse(FOLD);
const vertices_coords = ear.graph.makeVerticesCoordsFolded(graph);
const folded = { ...graph, vertices_coords };
const solution = ear.layer.layer3D(folded);
const faceOrders = solution.faceOrders();
const faceOrdersStrings = faceOrders.map(order => JSON.stringify(order));
expect(faceOrders.length).toBe(10);
// 0 and 1, adjacent, facing each other
expect(faceOrdersStrings.includes(JSON.stringify([0, 1, 1]))
|| faceOrdersStrings.includes(JSON.stringify([1, 0, 1]))).toBe(true);
// 2 and 3, adjacent, facing each other
expect(faceOrdersStrings.includes(JSON.stringify([2, 3, 1]))
|| faceOrdersStrings.includes(JSON.stringify([3, 2, 1]))).toBe(true);
// 4 and 5, adjacent, facing each other
expect(faceOrdersStrings.includes(JSON.stringify([4, 5, 1]))
|| faceOrdersStrings.includes(JSON.stringify([5, 4, 1]))).toBe(true);
// 6 and 7, adjacent, facing each other
expect(faceOrdersStrings.includes(JSON.stringify([6, 7, 1]))
|| faceOrdersStrings.includes(JSON.stringify([7, 6, 1]))).toBe(true);
// 10 and 11, adjacent, facing each other
expect(faceOrdersStrings.includes(JSON.stringify([10, 11, 1]))
|| faceOrdersStrings.includes(JSON.stringify([11, 10, 1]))).toBe(true);
// 2 and 13, adjacent, facing each other
expect(faceOrdersStrings.includes(JSON.stringify([2, 13, 1]))
|| faceOrdersStrings.includes(JSON.stringify([13, 2, 1]))).toBe(true);
// 8 and 13, adjacent, facing each other
expect(faceOrdersStrings.includes(JSON.stringify([8, 13, 1]))
|| faceOrdersStrings.includes(JSON.stringify([13, 8, 1]))).toBe(true);
// 9 and 14, adjacent, facing each other
expect(faceOrdersStrings.includes(JSON.stringify([9, 14, 1]))
|| faceOrdersStrings.includes(JSON.stringify([14, 9, 1]))).toBe(true);
// 1 and 14, adjacent, facing each other
expect(faceOrdersStrings.includes(JSON.stringify([1, 14, 1]))
|| faceOrdersStrings.includes(JSON.stringify([14, 1, 1]))).toBe(true);
// 12 and 15, facing each other
expect(faceOrdersStrings.includes(JSON.stringify([12, 15, 1]))
|| faceOrdersStrings.includes(JSON.stringify([15, 12, 1]))).toBe(true);
});
test("3D layer solver, square-fish base, faces sets", () => {
const FOLD = fs.readFileSync("./tests/files/fold/square-fish-3d.fold", "utf-8");
const graph = JSON.parse(FOLD);
const vertices_coords = ear.graph.makeVerticesCoordsFolded(graph);
const folded = { ...graph, vertices_coords };
const faceOrders = [
[0, 1, 1], [2, 3, 1], [4, 5, 1], [6, 7, 1], [10, 11, 1],
[2, 13, 1], [8, 13, 1], [9, 14, 1], [1, 14, 1], [12, 15, 1],
];
const nudge = ear.graph.nudgeFacesWithFaceOrders({ ...folded, faceOrders });
// faces
[0, 14, 1, 9].forEach(f => nudge[f].vector
.forEach((n, i) => expect(n).toBeCloseTo([0, 0, 1][i])));
[2, 3, 8, 13].forEach(f => nudge[f].vector
.forEach((n, i) => expect(n).toBeCloseTo([0, 0, -1][i])));
[4, 5].forEach(f => nudge[f].vector
.forEach((n, i) => expect(n)
.toBeCloseTo([0.9238795325112866, -0.38268343236509034, 0][i])));
[6, 7].forEach(f => nudge[f].vector
.forEach((n, i) => expect(n)
.toBeCloseTo([0.9238795325112863, 0.3826834323650909, 0][i])));
[10, 11].forEach(f => nudge[f].vector
.forEach((n, i) => expect(n).toBeCloseTo([0, -1, 0][i])));
[12, 15].forEach(f => nudge[f].vector
.forEach((n, i) => expect(n).toBeCloseTo([0, 1, 0][i])));
[0, 14, 1, 9].forEach((f, i) => expect(nudge[f].layer).toBe(i));
[2, 3, 8, 13].forEach((f, i) => expect(nudge[f].layer).toBe(i));
[4, 5].forEach((f, i) => expect(nudge[f].layer).toBe(i));
[6, 7].forEach((f, i) => expect(nudge[f].layer).toBe(i));
[10, 11].forEach((f, i) => expect(nudge[f].layer).toBe(i));
[12, 15].forEach((f, i) => expect(nudge[f].layer).toBe(i));
});
test("3D layer solver, Mooser's train", () => {
const FOLD = fs.readFileSync("./tests/files/fold/moosers-train.fold", "utf-8");
const folded = JSON.parse(FOLD);
const {
orders,
branches,
} = ear.layer.layer3D(folded);
// something so confusing.
// in the source code for "getEdgesLine", the line:
// const edgesLine = edgesToLines3({ vertices_coords, edges_vertices });
// switch it out for "edgesToLines" and 1633 becomes 1581.
expect(JSON.stringify(folded.vertices_coords.map(ear.math.resize3)))
.toMatchObject(JSON.stringify(folded.vertices_coords));
expect(JSON.stringify(ear.graph.edgesToLines(folded)))
.toMatchObject(JSON.stringify(ear.graph.edgesToLines3(folded)));
// expect(Object.keys(orders).length).toBe(1713);
expect(Object.keys(orders).length).toBe(1633);
// expect(Object.keys(orders).length).toBe(1581);
expect(ear.layer.getBranchStructure({ branches })).toMatchObject([
[[], []], [[], []],
[[], []], [[], []],
[[], []], [[], []],
[[], []], [[], []],
[[], []], [[], []],
[[], []], [[], []],
// [[], []], [[], []],
// [[], []], [[], []],
// [[], []], [[], []],
]);
// expect(branches).toMatchObject([
// [
// { orders: [[52, 115, 1], [52, 131, 1], [52, 128, -1], [52, 113, -1]]},
// { orders: [[52, 115, -1], [52, 131, -1], [52, 128, 1], [52, 113, 1]]},
// ], [
// { orders: [[108, 114, -1], [108, 136, -1], [108, 137, 1], [108, 116, 1]]},
// { orders: [[108, 114, 1], [108, 136, 1], [108, 137, -1], [108, 116, -1]]},
// ]
// ]);
folded.faceOrders = ear.layer.compile({ orders, branches });
fs.writeFileSync(`./tests/tmp/moosers-train-layer-solved.fold`, JSON.stringify(folded));
});
test("3D layer solver, maze-u", () => {
const FOLD = fs.readFileSync("./tests/files/fold/maze-u.fold", "utf-8");
const graph = JSON.parse(FOLD);
const foldedFrame = ear.graph.getFramesByClassName(graph, "foldedForm")[0];
foldedFrame.faceOrders = ear.layer.layer3D(foldedFrame).faceOrders();
fs.writeFileSync(`./tests/tmp/maze-u-layer-solved.fold`, JSON.stringify(foldedFrame));
// every face has some order associated with it
const facesFound = [];
foldedFrame.faceOrders.forEach(order => {
facesFound[order[0]] = true;
facesFound[order[1]] = true;
});
expect(facesFound.filter(a => a !== undefined).length)
.toBe(foldedFrame.faces_vertices.length);
});
test("3D layer solver, maze-s", () => {
const FOLD = fs.readFileSync("./tests/files/fold/maze-s.fold", "utf-8");
const graph = JSON.parse(FOLD);
const foldedFrame = ear.graph.getFramesByClassName(graph, "foldedForm")[0];
const solution = ear.layer.layer3D(foldedFrame);
const solutionCounts = solution.count();
foldedFrame.faceOrders = solution.faceOrders();
foldedFrame.file_frames = solutionCounts
.flatMap((count, i) => Array.from(Array(count))
.map((_, j) => {
const solutionIndices = solutionCounts.map(() => 0);
solutionIndices[i] = j;
return solutionIndices;
})
.map(solutionIndices => ({
frame_parent: 0,
frame_inherit: true,
faceOrders: solution.faceOrders(...solutionIndices),
})));
fs.writeFileSync(`./tests/tmp/maze-s-layer-solved.fold`, JSON.stringify(foldedFrame));
expect(true).toBe(true);
});
// test("3D layer solver, 8x8 maze", () => {
// const FOLD = fs.readFileSync("./tests/files/fold/maze-8x8.fold", "utf-8");
// const graph = JSON.parse(FOLD);
// const foldedFrame = ear.graph.getFramesByClassName(graph, "foldedForm")[0];
// foldedFrame.faceOrders = ear.layer.layer3D(foldedFrame).faceOrders();
// fs.writeFileSync(`./tests/tmp/maze-8x8-layer-solved.fold`, JSON.stringify(foldedFrame));
// expect(true).toBe(true);
// });
================================================
FILE: tests/layer.table.test.js
================================================
import { expect, test } from "vitest";
import fs from "fs";
import ear from "../src/index.js";
test("layer table", () => {
const layerTableJSON = fs.readFileSync(
"./tests/files/json/layer-table.json",
"utf-8",
);
const table = JSON.parse(layerTableJSON);
expect(ear.layer.table).toMatchObject(table);
});
test("immutability test", () => {
// taco_taco at 000011 is a const array entry,
// attempt to overwrite one of its values.
try {
ear.layer.table.taco_taco["000011"][0] = 99;
} catch (error) {
expect(error).not.toBe(undefined);
}
// the object should have been recursively frozen,
// it should not be possible to change a value even inside an array.
expect(ear.layer.table.taco_taco["000011"][0]).not.toBe(99);
expect(ear.layer.table.taco_taco["000011"][0]).toBe(2);
});
test("layer table structure", () => {
const keys = ["taco_taco", "taco_tortilla", "tortilla_tortilla", "transitivity"];
Object.keys(ear.layer.table)
.forEach((key, i) => expect(key).toBe(keys[i]));
keys.forEach(key => expect(typeof ear.layer.table[key]).toBe("object"));
const keysLength = [729, 27, 9, 27];
keys.forEach((key, i) => expect(Object.keys(ear.layer.table[key]).length).toBe(keysLength[i]));
});
test("layer table elements", () => {
expect(ear.layer.table.taco_taco["000000"]).toBe(true);
expect(ear.layer.table.taco_taco["000122"]).toBe(false);
expect(JSON.stringify(ear.layer.table.taco_taco["000011"]))
.toBe(JSON.stringify([2, 2]));
expect(ear.layer.table.taco_tortilla["000"]).toBe(true);
expect(ear.layer.table.taco_tortilla["011"]).toBe(false);
expect(JSON.stringify(ear.layer.table.taco_tortilla["110"]))
.toBe(JSON.stringify([2, 2]));
expect(ear.layer.table.tortilla_tortilla["00"]).toBe(true);
expect(ear.layer.table.tortilla_tortilla["12"]).toBe(false);
expect(JSON.stringify(ear.layer.table.tortilla_tortilla["10"]))
.toBe(JSON.stringify([1, 1]));
expect(ear.layer.table.transitivity["000"]).toBe(true);
expect(ear.layer.table.transitivity["111"]).toBe(false);
expect(JSON.stringify(ear.layer.table.transitivity["110"]))
.toBe(JSON.stringify([2, 2]));
});
================================================
FILE: tests/layer.transitivity.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("makeTransitivity", () => {});
test("getTransitivityTriosFromTacos", () => {});
================================================
FILE: tests/lineno.js
================================================
import fs from "fs";
const repoName = "Origami";
const regex = /\*(\s*)\@linkcode.*/g;
const processFile = (path) => {
// console.log("checking file", path);
const contents = fs.readFileSync(path, "utf8");
const matches = contents.match(regex);
if (!matches) { return; }
const lineNumbers = contents
.split(/\r?\n/)
.map((line, i) => (line.match(regex) !== null ? i : undefined))
.filter(a => a !== undefined)
.map(num => num + 1); // line numbers start with 1
if (matches.length !== lineNumbers.length) {
console.log("unexpected error! the lengths of matches don't equal"); return;
}
const values = lineNumbers.map(num => `${repoName} ${path} ${num}`);
const lines = values.map(value => `* @linkcode ${value}`);
let count = 0;
const fn = () => lines[count++];
const modified = contents.replace(regex, fn);
fs.writeFileSync(path, modified);
// console.log(`modified ${path} with ${matches.length} line number entries`);
};
const searchDir = (path) => {
const contents = fs.readdirSync(path, { withFileTypes: true });
const files = contents.filter(el => el.isFile());
const directories = contents.filter(el => el.isDirectory());
// console.log("checking dir", path);
// console.log("files", files);
// console.log("directories", directories);
files.forEach(el => processFile(`${path}/${el.name}`));
directories.forEach(el => searchDir(`${path}/${el.name}`));
};
searchDir("./src");
================================================
FILE: tests/math.algebra.matrix2.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
const testEqualVectors = function (...args) {
expect(ear.math.epsilonEqualVectors(...args)).toBe(true);
};
test("matrix 2 core", () => {
expect(ear.math.invertMatrix2([1, 0, 0, 1, 0, 0])).not.toBe(undefined);
const r1 = ear.math.makeMatrix2Translate();
expect(r1[0]).toBe(1);
expect(r1[4]).toBe(0);
expect(r1[5]).toBe(0);
const r2 = ear.math.makeMatrix2Scale([2, -1]);
expect(r2[0]).toBe(2);
expect(r2[3]).toBe(-1);
});
test("matrix 2 transform line", () => {
const result = ear.math.multiplyMatrix2Line2(
ear.math.makeMatrix2Scale([0.5, 0.5, 0.5]),
{ vector: [1, 1], origin: [1, 0] },
);
expect(result.vector[0]).toBeCloseTo(0.5);
expect(result.vector[1]).toBeCloseTo(0.5);
expect(result.origin[0]).toBeCloseTo(0.5);
expect(result.origin[1]).toBeCloseTo(0);
});
test("makeMatrix2Scale", () => {
testEqualVectors(
ear.math.makeMatrix2Scale(),
[1, 0, 0, 1, 0, 0],
);
testEqualVectors(
ear.math.makeMatrix2Scale([0.5, 0.5]),
[0.5, 0, 0, 0.5, 0, 0],
);
testEqualVectors(
ear.math.makeMatrix2UniformScale(),
[1, 0, 0, 1, 0, 0],
);
testEqualVectors(
ear.math.makeMatrix2UniformScale(0.5),
[0.5, 0, 0, 0.5, 0, 0],
);
});
test("matrix 2", () => {
// top level types
testEqualVectors([1, 0, 0, 1, 6, 7], ear.math.makeMatrix2Translate(6, 7));
testEqualVectors([3, 0, 0, 3, -2, 0], ear.math.makeMatrix2Scale([3, 3], [1, 0]));
testEqualVectors([0, 1, 1, -0, -8, 8], ear.math.makeMatrix2Reflect([1, 1], [-5, 3]));
testEqualVectors(
[Math.SQRT1_2, Math.SQRT1_2, -Math.SQRT1_2, Math.SQRT1_2, 1, 1],
ear.math.makeMatrix2Rotate(Math.PI / 4, [1, 1]),
);
testEqualVectors(
[Math.SQRT1_2, -Math.SQRT1_2, Math.SQRT1_2,
Math.SQRT1_2, -Math.SQRT1_2, Math.SQRT1_2],
ear.math.invertMatrix2([Math.SQRT1_2, Math.SQRT1_2, -Math.SQRT1_2, Math.SQRT1_2, 1, 0]),
);
testEqualVectors(
[Math.sqrt(4.5), Math.SQRT1_2, -Math.SQRT1_2, Math.sqrt(4.5), Math.sqrt(4.5), Math.SQRT1_2],
ear.math.multiplyMatrices2(
[Math.SQRT1_2, -Math.SQRT1_2, Math.SQRT1_2, Math.SQRT1_2, 0, 0],
[1, 2, -2, 1, 1, 2],
),
);
testEqualVectors(
[0, 3],
ear.math.multiplyMatrix2Vector2([2, 1, -1, 2, -1, 0], [1, 1]),
);
testEqualVectors(
[-2, 3],
ear.math.multiplyMatrix2Vector2(
ear.math.makeMatrix2Scale([3, 3], [1, 0]),
[0, 1],
),
);
testEqualVectors(
[-1, 2],
ear.math.multiplyMatrix2Vector2(
ear.math.makeMatrix2Scale([3, 3], [0.5, 0.5]),
[0, 1],
),
);
testEqualVectors(
[1, 1],
ear.math.multiplyMatrix2Vector2(
ear.math.makeMatrix2Scale([0.5, 0.5], [1, 1]),
[1, 1],
),
);
testEqualVectors(
[0.75, 0.75],
ear.math.multiplyMatrix2Vector2(
ear.math.makeMatrix2Scale([0.5, 0.5], [0.5, 0.5]),
[1, 1],
),
);
});
================================================
FILE: tests/math.algebra.matrix3.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
const testEqualVectors = function (...args) {
expect(ear.math.epsilonEqualVectors(...args)).toBe(true);
};
test("isIdentity", () => {
expect(ear.math.isIdentity3x4([1, 2, 3, 4, 5, 6, 7, 8, 9])).toBe(false);
expect(ear.math.isIdentity3x4([1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 5, 6])).toBe(false);
expect(ear.math.isIdentity3x4([1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0])).toBe(true);
});
test("multiply", () => {
const m = ear.math.multiplyMatrices3(
ear.math.makeMatrix3RotateX(Math.PI / 4),
ear.math.makeMatrix3RotateZ(Math.PI / 4),
);
const sq = Math.SQRT1_2;
[sq, 0.5, 0.5, -sq, 0.5, 0.5, 0, -sq, sq, 0, 0, 0]
.forEach((a, i) => expect(a).toBeCloseTo(m[i]));
});
test("determinant", () => {
// randomly made matrices, made using these affine transforms,
// even their inverted forms, should all have a determinant of 1
expect(ear.math.determinant3([...ear.math.identity3x4])).toBeCloseTo(1);
expect(ear.math.determinant3(ear.math.makeMatrix3RotateX(Math.random() * Math.PI * 2)))
.toBeCloseTo(1);
expect(ear.math.determinant3(ear.math.makeMatrix3RotateZ(Math.random() * Math.PI * 2)))
.toBeCloseTo(1);
expect(ear.math.determinant3(ear.math.makeMatrix3Translate(1, 2, 3)))
.toBeCloseTo(1);
expect(ear.math.determinant3(ear.math.invertMatrix3(
ear.math.makeMatrix3Rotate(Math.random() * Math.PI * 2, [1, 5, 8]),
))).toBeCloseTo(1);
});
test("inverse", () => {
const m = ear.math.invertMatrix3([0, -1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0]);
[0, 1, -0, -1, 0, 0, 0, -0, 1, 0, 0, 0]
.forEach((a, i) => expect(a).toBeCloseTo(m[i]));
});
test("translate", () => {
const m = ear.math.makeMatrix3Translate(4, 5, 6);
expect(m[9]).toBe(4);
expect(m[10]).toBe(5);
expect(m[11]).toBe(6);
});
test("rotateX", () => {
const sq = Math.SQRT1_2;
const m = ear.math.makeMatrix3RotateX(Math.PI / 4);
[1, 0, 0, 0, sq, sq, 0, -sq, sq, 0, 0, 0].forEach((a, i) => expect(a).toBeCloseTo(m[i]));
});
test("rotateY", () => {
const sq = Math.SQRT1_2;
const m = ear.math.makeMatrix3RotateY(Math.PI / 4);
[sq, 0, -sq, 0, 1, 0, sq, 0, sq, 0, 0, 0].forEach((a, i) => expect(a).toBeCloseTo(m[i]));
});
test("rotateZ", () => {
const sq = Math.SQRT1_2;
const m = ear.math.makeMatrix3RotateZ(Math.PI / 4);
[sq, sq, 0, -sq, sq, 0, 0, 0, 1, 0, 0, 0].forEach((a, i) => expect(a).toBeCloseTo(m[i]));
});
test("rotate", () => {
const m = ear.math.makeMatrix3Rotate(Math.PI / 2, [1, 1, 1], [0, 0, 0]);
expect(m[2]).toBeCloseTo(m[3]);
expect(m[0]).toBeCloseTo(m[4]);
expect(m[1]).toBeCloseTo(m[5]);
});
test("scale", () => {
const m = ear.math.makeMatrix3Scale([0.5, 0.5, 0.5]);
[0.5, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 0, 0, 0]
.forEach((a, i) => expect(a).toBeCloseTo(m[i]));
});
test("makeMatrix3Scale", () => {
testEqualVectors(
ear.math.makeMatrix3Scale(),
[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
);
testEqualVectors(
ear.math.makeMatrix3Scale([0.5, 0.5, 0.5]),
[0.5, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 0, 0, 0],
);
testEqualVectors(
ear.math.makeMatrix3UniformScale(),
[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
);
testEqualVectors(
ear.math.makeMatrix3UniformScale(0.5),
[0.5, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 0, 0, 0],
);
});
test("combine operations", () => {
const result = ear.math.multiplyMatrices3(
ear.math.makeMatrix3RotateX(Math.PI / 2),
ear.math.makeMatrix3Translate(40, 20, 10),
);
[1, 0, 0, 0, 0, 1, 0, -1, 0, 40, -10, 20]
.forEach((n, i) => expect(n).toBeCloseTo(result[i]));
});
test("reflectZ", () => {
const m = ear.math.makeMatrix3ReflectZ([1, 1, 1], [0, 0, 0]);
expect(m[1]).toBeCloseTo(m[3]);
expect(m[0]).toBeCloseTo(m[4]);
expect(m[2]).toBeCloseTo(m[5]);
expect(m[5]).toBeCloseTo(m[6]);
});
test("transform", () => {
const matrix = ear.math.multiplyMatrices3(
ear.math.makeMatrix3RotateZ(Math.PI / 2),
ear.math.makeMatrix3Translate(4, 5, 6),
);
const segment = [[-1, 0, 0], [1, 0, 0]];
const result = segment
.map(p => ear.math.multiplyMatrix3Vector3(matrix, p));
[[-5, 3, 6], [-5, 5, 6]]
.forEach((p, i) => p
.forEach((n, j) => expect(n).toBe(result[i][j])));
});
test("transformVector", () => {
const vector = [1, 2, 3];
const result = ear.math.multiplyMatrix3Vector3(
ear.math.makeMatrix3Scale([0.5, 0.5, 0.5]),
vector,
);
expect(result[0]).toBeCloseTo(0.5);
expect(result[1]).toBeCloseTo(1);
expect(result[2]).toBeCloseTo(1.5);
});
test("transformLine", () => {
const result = ear.math.multiplyMatrix3Line3(
ear.math.makeMatrix3Scale([0.5, 0.5, 0.5]),
[0.707, 0.707, 0],
[1, 0, 0],
);
expect(result.vector[0]).toBeCloseTo(0.3535);
expect(result.vector[1]).toBeCloseTo(0.3535);
expect(result.vector[2]).toBeCloseTo(0);
expect(result.origin[0]).toBeCloseTo(0.5);
expect(result.origin[1]).toBeCloseTo(0);
expect(result.origin[2]).toBeCloseTo(0);
});
test("matrix core invert", () => {
expect(ear.math.invertMatrix2([1, 0, 0, 1, 0, 0])).not.toBe(undefined);
expect(ear.math.invertMatrix3([1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0])).not.toBe(undefined);
expect(ear.math.invertMatrix2([5, 5, 4, 4, 3, 3])).toBe(undefined);
expect(ear.math.invertMatrix3([0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1])).toBe(undefined);
});
// todo: test matrix3 methods (invert) with the translation component to make sure it carries over
test("matrix 3 core, transforms", () => {
const result1 = ear.math.makeMatrix3Translate();
[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0].forEach((n, i) => expect(n).toBe(result1[i]));
// rotate 360 degrees about an arbitrary axis and origin
testEqualVectors(
[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
ear.math.makeMatrix3Rotate(
Math.PI * 2,
[Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5],
[Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5],
),
);
testEqualVectors(
ear.math.makeMatrix3RotateX(Math.PI / 6),
ear.math.makeMatrix3Rotate(Math.PI / 6, [1, 0, 0]),
);
testEqualVectors(
ear.math.makeMatrix3RotateY(Math.PI / 6),
ear.math.makeMatrix3Rotate(Math.PI / 6, [0, 1, 0]),
);
testEqualVectors(
ear.math.makeMatrix3RotateZ(Math.PI / 6),
ear.math.makeMatrix3Rotate(Math.PI / 6, [0, 0, 1]),
);
// source wikipedia https://en.wikipedia.org/wiki/Rotation_matrix#Examples
const exampleMat = [
0.35612209405955486, -0.8018106071106572, 0.47987165414043453,
0.47987165414043464, 0.5975763087872217, 0.6423595182829954,
-0.8018106071106572, 0.0015183876574496047, 0.5975763087872216,
0, 0, 0,
];
testEqualVectors(
exampleMat,
ear.math.makeMatrix3Rotate((-74 / 180) * Math.PI, [-1 / 3, 2 / 3, 2 / 3]),
);
testEqualVectors(
exampleMat,
ear.math.makeMatrix3Rotate((-74 / 180) * Math.PI, [-0.5, 1, 1]),
);
testEqualVectors(
[1, 0, 0, 0, 0.8660254, 0.5, 0, -0.5, 0.8660254, 0, 0, 0],
ear.math.makeMatrix3Rotate(Math.PI / 6, [1, 0, 0]),
);
});
test("matrix 3 core", () => {
expect(ear.math.determinant3([1, 2, 3, 2, 4, 8, 7, 8, 9])).toBe(12);
expect(ear.math.determinant3([3, 2, 0, 0, 0, 1, 2, -2, 1, 0, 0, 0])).toBe(10);
testEqualVectors(
[4, 5, -8, -5, -6, 9, -2, -2, 3, 0, 0, 0],
ear.math.invertMatrix3([0, 1, -3, -3, -4, 4, -2, -2, 1, 0, 0, 0]),
);
testEqualVectors(
[0.2, -0.2, 0.2, 0.2, 0.3, -0.3, 0, 1, 0, 0, 0, 0],
ear.math.invertMatrix3([3, 2, 0, 0, 0, 1, 2, -2, 1, 0, 0, 0]),
);
const mat_3d_ref = ear.math.makeMatrix3ReflectZ([1, -2], [12, 13]);
testEqualVectors(
ear.math.makeMatrix2Reflect([1, -2], [12, 13]),
[mat_3d_ref[0], mat_3d_ref[1], mat_3d_ref[3], mat_3d_ref[4], mat_3d_ref[9], mat_3d_ref[10]],
);
// source wolfram alpha
testEqualVectors(
[-682, 3737, -5545, 2154, -549, -1951, 953, -3256, 4401, 0, 0, 0],
ear.math.multiplyMatrices3(
[5, -52, 85, 15, -9, -2, 32, 2, -50, 0, 0, 0],
[-77, 25, -21, 3, 53, 42, 63, 2, 19, 0, 0, 0],
),
);
});
================================================
FILE: tests/math.algebra.matrix4.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("isIdentity", () => {
expect(ear.math.isIdentity4x4([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]))
.toBe(false);
expect(ear.math.isIdentity4x4([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 4, 5, 6, 1]))
.toBe(false);
expect(ear.math.isIdentity4x4([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]))
.toBe(true);
});
test("multiply", () => {
const m = ear.math.multiplyMatrices4(
ear.math.makeMatrix4RotateX(Math.PI / 4),
ear.math.makeMatrix4RotateZ(Math.PI / 4),
);
const sq = Math.SQRT1_2;
[sq, 0.5, 0.5, 0, -sq, 0.5, 0.5, 0, 0, -sq, sq, 0, 0, 0, 0, 1]
.forEach((a, i) => expect(a).toBeCloseTo(m[i]));
});
test("determinant", () => {
// randomly made matrices, made using these affine transforms,
// even their inverted forms, should all have a determinant of 1
expect(ear.math.determinant4([...ear.math.identity4x4])).toBeCloseTo(1);
expect(ear.math.determinant4(ear.math.makeMatrix4RotateX(Math.random() * Math.PI * 2)))
.toBeCloseTo(1);
expect(ear.math.determinant4(ear.math.makeMatrix4RotateZ(Math.random() * Math.PI * 2)))
.toBeCloseTo(1);
expect(ear.math.determinant4(ear.math.makeMatrix4Translate(1, 2, 3)))
.toBeCloseTo(1);
expect(ear.math.determinant4(ear.math.invertMatrix4(
ear.math.makeMatrix4Rotate(Math.random() * Math.PI * 2, [1, 5, 8]),
))).toBeCloseTo(1);
});
test("inverse", () => {
const m = ear.math.invertMatrix4([0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
[0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
.forEach((a, i) => expect(a).toBeCloseTo(m[i]));
const bad = ear.math.invertMatrix4([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, Infinity, 0, 1]);
expect(bad).toBe(undefined);
});
test("translate", () => {
const m = ear.math.makeMatrix4Translate(4, 5, 6);
expect(m[12]).toBe(4);
expect(m[13]).toBe(5);
expect(m[14]).toBe(6);
});
test("rotateX", () => {
const sq = Math.SQRT1_2;
const m = ear.math.makeMatrix4RotateX(Math.PI / 4);
[1, 0, 0, 0, 0, sq, sq, 0, 0, -sq, sq, 0, 0, 0, 0, 1]
.forEach((a, i) => expect(a).toBeCloseTo(m[i]));
});
test("rotateY", () => {
const sq = Math.SQRT1_2;
const m = ear.math.makeMatrix4RotateY(Math.PI / 4);
[sq, 0, -sq, 0, 0, 1, 0, 0, sq, 0, sq, 0, 0, 0, 0, 1]
.forEach((a, i) => expect(a).toBeCloseTo(m[i]));
});
test("rotateZ", () => {
const sq = Math.SQRT1_2;
const m = ear.math.makeMatrix4RotateZ(Math.PI / 4);
[sq, sq, 0, 0, -sq, sq, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
.forEach((a, i) => expect(a).toBeCloseTo(m[i]));
});
test("rotate", () => {
const m = ear.math.makeMatrix4Rotate(Math.PI / 2, [1, 1, 1], [0, 0, 0]);
expect(m[2]).toBeCloseTo(m[4]);
expect(m[4]).toBeCloseTo(m[9]);
expect(m[0]).toBeCloseTo(m[5]);
expect(m[5]).toBeCloseTo(m[10]);
expect(m[1]).toBeCloseTo(m[6]);
expect(m[6]).toBeCloseTo(m[8]);
});
test("scale", () => {
const m = ear.math.makeMatrix4Scale([0.5, 0.5, 0.5]);
[0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 1]
.forEach((a, i) => expect(a).toBeCloseTo(m[i]));
});
test("makeMatrix4Scale", () => {
const m0 = ear.math.makeMatrix4Scale();
[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
.forEach((n, i) => expect(n).toBeCloseTo(m0[i]));
const m1 = ear.math.makeMatrix4Scale([0.5, 0.5, 0.5]);
[0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 1]
.forEach((n, i) => expect(n).toBeCloseTo(m1[i]));
const m2 = ear.math.makeMatrix4UniformScale();
[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
.forEach((n, i) => expect(n).toBeCloseTo(m2[i]));
const m3 = ear.math.makeMatrix4UniformScale(0.5);
[0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 1]
.forEach((n, i) => expect(n).toBeCloseTo(m3[i]));
});
test("combine operations", () => {
const result = ear.math.multiplyMatrices4(
ear.math.makeMatrix4RotateX(Math.PI / 2),
ear.math.makeMatrix4Translate(40, 20, 10),
);
[1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 40, -10, 20, 1]
.forEach((n, i) => expect(n).toBeCloseTo(result[i]));
});
test("reflectZ", () => {
const m = ear.math.makeMatrix4ReflectZ([1, 1, 1], [0, 0, 0]);
[0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
.forEach((n, i) => expect(n).toBeCloseTo(m[i]));
});
test("transform", () => {
const matrix = ear.math.multiplyMatrices4(
ear.math.makeMatrix4RotateZ(Math.PI / 2),
ear.math.makeMatrix4Translate(4, 5, 6),
);
const segment = [[-1, 0, 0], [1, 0, 0]];
const result = segment
.map(p => ear.math.multiplyMatrix4Vector3(matrix, p));
[[-5, 3, 6], [-5, 5, 6]]
.forEach((p, i) => p
.forEach((n, j) => expect(n).toBe(result[i][j])));
});
test("transformVector", () => {
const vector = [1, 2, 3];
const result = ear.math.multiplyMatrix4Vector3(
ear.math.makeMatrix4Scale([0.5, 0.5, 0.5]),
vector,
);
expect(result[0]).toBeCloseTo(0.5);
expect(result[1]).toBeCloseTo(1);
expect(result[2]).toBeCloseTo(1.5);
});
test("transformLine", () => {
const result = ear.math.multiplyMatrix4Line3(
ear.math.makeMatrix4Scale([0.5, 0.5, 0.5]),
[0.707, 0.707, 0],
[1, 0, 0],
);
expect(result.vector[0]).toBeCloseTo(0.3535);
expect(result.vector[1]).toBeCloseTo(0.3535);
expect(result.vector[2]).toBeCloseTo(0);
expect(result.origin[0]).toBeCloseTo(0.5);
expect(result.origin[1]).toBeCloseTo(0);
expect(result.origin[2]).toBeCloseTo(0);
});
/**
* WebGL Matrices
*/
test("perspective matrix", () => {
const res1 = ear.math.makePerspectiveMatrix4(Math.PI / 2, 1, 1, 10);
[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -(11 / 9), -1, 0, 0, -(20 / 9), 0]
.forEach((n, i) => expect(res1[i]).toBeCloseTo(n));
// fov 180deg results in 0 in x and y diagonal
const res2 = ear.math.makePerspectiveMatrix4(Math.PI, 1, 1, 10);
expect(res2[0]).toBeCloseTo(0);
expect(res2[5]).toBeCloseTo(0);
});
test("orthographic matrix", () => {
const res1 = ear.math.makeOrthographicMatrix4(1, 1, -1, -1, 1, 10);
[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -(2 / 9), 0, 0, 0, -(11 / 9), 1]
.forEach((n, i) => expect(res1[i]).toBeCloseTo(n));
});
test("lookat matrix", () => {
const res1 = ear.math.makeLookAtMatrix4([0, 0, 1], [0, 0, 0], [0, 1, 0]);
[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1]
.forEach((n, i) => expect(res1[i]).toBeCloseTo(n));
const res2 = ear.math.makeLookAtMatrix4([1, 0, 0], [0, 0, 0], [0, 1, 0]);
[0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1]
.forEach((n, i) => expect(res2[i]).toBeCloseTo(n));
const res3 = ear.math.makeLookAtMatrix4([0, 0, -1], [0, 0, 0], [0, 1, 0]);
[-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, -1, 1]
.forEach((n, i) => expect(res3[i]).toBeCloseTo(n));
const res4 = ear.math.makeLookAtMatrix4([0, 0, 1], [0, 0, 0], [0, -1, 0]);
[-1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1]
.forEach((n, i) => expect(res4[i]).toBeCloseTo(n));
});
================================================
FILE: tests/math.algebra.quaternion.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("quaternionFromTwoVectors", () => {
const res1 = ear.math.quaternionFromTwoVectors([1, 0, 0], [0, 1, 0]);
[0, 0, Math.SQRT1_2, Math.SQRT1_2]
.forEach((n, i) => expect(res1[i]).toBeCloseTo(n));
const res2 = ear.math.quaternionFromTwoVectors([1, 0, 0], [0, 0, 1]);
[0, -Math.SQRT1_2, 0, Math.SQRT1_2]
.forEach((n, i) => expect(res2[i]).toBeCloseTo(n));
const res3 = ear.math.quaternionFromTwoVectors([0, 1, 0], [0, 0, 1]);
[Math.SQRT1_2, 0, 0, Math.SQRT1_2]
.forEach((n, i) => expect(res3[i]).toBeCloseTo(n));
});
test("matrix4FromQuaternion", () => {
const res1 = ear.math.matrix4FromQuaternion([0, 0, 0, 1]);
ear.math.identity4x4
.forEach((n, i) => expect(res1[i]).toBeCloseTo(n));
const res2 = ear.math.matrix4FromQuaternion([1, 0, 0, 0]);
[1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1]
.forEach((n, i) => expect(res2[i]).toBeCloseTo(n));
const res3 = ear.math.matrix4FromQuaternion([0, 1, 0, 0]);
[-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1]
.forEach((n, i) => expect(res3[i]).toBeCloseTo(n));
const res4 = ear.math.matrix4FromQuaternion([0, 0, 1, 0]);
[-1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
.forEach((n, i) => expect(res4[i]).toBeCloseTo(n));
});
================================================
FILE: tests/math.algebra.vector.resize.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
const equalTest = (a, b) => expect(JSON.stringify(a))
.toBe(JSON.stringify(b));
test("resize", () => {
const a = [1, 2, 3];
const _a = ear.math.resize(5, a);
equalTest(_a, [1, 2, 3, 0, 0]);
});
test("resize empty", () => {
const res = ear.math.resize(3, []);
expect(ear.math.epsilonEqualVectors([0, 0, 0], res)).toBe(true);
});
test("resize undefined", () => {
try {
ear.math.resize(3);
} catch (err) {
expect(err).not.toBe(undefined);
}
});
test("resizeUp", () => {
const a = [1, 2, 3];
const b = [4, 5];
expect(a.length).toBe(3);
expect(b.length).toBe(2);
const [_a, _b] = ear.math.resizeUp(a, b);
expect(_a.length).toBe(3);
expect(_b.length).toBe(3);
});
// function is not included.
// since implementation it has never been used
// test("resizeDown", () => {
// const a = [1, 2, 3];
// const b = [4, 5];
// expect(a.length).toBe(3);
// expect(b.length).toBe(2);
// const [_a, _b] = ear.math.resizeDown(a, b);
// expect(_a.length).toBe(2);
// expect(_b.length).toBe(2);
// });
================================================
FILE: tests/math.algebra.vector.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
const testEqual = function (...args) {
expect(ear.math.epsilonEqualVectors(...args)).toBe(true);
};
/**
* algebra core
*/
test("magnitude", () => {
expect(ear.math.magnitude([0, 0, 0, 0, 0, 1])).toBe(1);
expect(ear.math.magnitude([1, 1])).toBeCloseTo(Math.sqrt(2));
expect(ear.math.magnitude([0, 0, 0, 0, 0, 0])).toBe(0);
expect(ear.math.magnitude([])).toBe(0);
expect(ear.math.magnitude2([1, 0, 10])).toBe(1);
expect(ear.math.magnitude2([1, 0])).toBe(1);
expect(ear.math.magnitude2([0, 0, 1])).toBe(0);
expect(ear.math.magnitude3([0, 0, 10])).toBe(10);
expect(ear.math.magnitude3([1, 0, 0])).toBe(1);
expect(ear.math.magnitude3([0, 0, 1])).toBe(1);
expect(ear.math.magnitude3([0, 0, 0, 1])).toBe(0);
});
test("mag sq", () => {
expect(ear.math.magSquared([1, 1, 1, 1])).toBe(4);
expect(ear.math.magSquared([])).toBe(0);
expect(ear.math.magSquared([1, -2, 3]))
.toBe((1 ** 2) + (2 ** 2) + (3 ** 2));
expect(ear.math.magSquared([-100])).toBe(100 * 100);
});
test("normalize", () => {
expect(ear.math.normalize([]).length).toBe(0);
expect(ear.math.normalize([1, 1])[0]).toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.normalize([1, 1])[1]).toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.normalize([1, -1, 1])[0]).toBeCloseTo(Math.sqrt(3) / 3);
expect(ear.math.normalize2([]).length).toBe(2);
expect(ear.math.normalize2([1, 1])[0]).toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.normalize2([1, 1])[1]).toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.normalize2([1, 1])[2]).toBe(undefined);
expect(ear.math.normalize2([1, 1, 10])[0]).toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.normalize2([1, 1, 10])[1]).toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.normalize2([1, 1, 10])[2]).toBe(undefined);
expect(ear.math.normalize3([]).length).toBe(3);
expect(ear.math.normalize3([0, 0, 0])[0]).toBeCloseTo(0);
expect(ear.math.normalize3([0, 0, 0])[1]).toBeCloseTo(0);
expect(ear.math.normalize3([0, 0, 0])[2]).toBeCloseTo(0);
expect(ear.math.normalize3([1, 1, 1])[0]).toBeCloseTo(Math.sqrt(3) / 3);
expect(ear.math.normalize3([1, 1, 1])[1]).toBeCloseTo(Math.sqrt(3) / 3);
expect(ear.math.normalize3([1, 1, 1])[2]).toBeCloseTo(Math.sqrt(3) / 3);
expect(ear.math.normalize3([1, 1, 1])[3]).toBe(undefined);
expect(ear.math.normalize3([1, 1, 1, 10])[0]).toBeCloseTo(Math.sqrt(3) / 3);
expect(ear.math.normalize3([1, 1, 1, 10])[1]).toBeCloseTo(Math.sqrt(3) / 3);
expect(ear.math.normalize3([1, 1, 1, 10])[2]).toBeCloseTo(Math.sqrt(3) / 3);
expect(ear.math.normalize3([1, 1, 1, 10])[3]).toBe(undefined);
});
test("scale", () => {
expect(ear.math.scale([]).length).toBe(0);
expect(ear.math.scale([1])[0]).toBe(NaN);
expect(ear.math.scale([1], 2)[0]).toBe(2);
expect(ear.math.scale([1], -2)[0]).toBe(-2);
expect(ear.math.scale2([]).length).toBe(2);
expect(ear.math.scale2([1])[0]).toBe(NaN);
expect(ear.math.scale2([1], 2)[1]).toBe(NaN);
expect(ear.math.scale2([1], 2)[2]).toBe(undefined);
expect(ear.math.scale2([1, 1], 2)[1]).toBe(2);
expect(ear.math.scale2([1, 1], 2)[2]).toBe(undefined);
expect(ear.math.scale2([1, 1, 1], 2)[2]).toBe(undefined);
expect(ear.math.scale3([]).length).toBe(3);
expect(ear.math.scale3([1])[0]).toBe(NaN);
expect(ear.math.scale3([1], 2)[1]).toBe(NaN);
expect(ear.math.scale3([1], 2)[2]).toBe(NaN);
expect(ear.math.scale3([1, 1, 1], 2)[1]).toBe(2);
expect(ear.math.scale3([1, 1, 1], 2)[2]).toBe(2);
expect(ear.math.scale3([1, 1, 1], 2)[3]).toBe(undefined);
});
test("add", () => {
expect(ear.math.add([1], [1, 2, 3]).length).toBe(1);
expect(ear.math.add([1], [1, 2, 3])[0]).toBe(2);
expect(ear.math.add([1, 2, 3], [1, 2])[0]).toBe(2);
expect(ear.math.add([1, 2, 3], [1, 2])[1]).toBe(4);
expect(ear.math.add([1, 2, 3], [1, 2])[2]).toBe(3);
expect(ear.math.add([1, 2, 3], [])[0]).toBe(1);
expect(ear.math.add2([1], [1, 2, 3]).length).toBe(2);
expect(ear.math.add2([1], [1, 2, 3])[0]).toBe(2);
expect(ear.math.add2([1], [1, 2, 3])[1]).toBe(NaN);
expect(ear.math.add2([1, 2, 3], [1, 2])[0]).toBe(2);
expect(ear.math.add2([1, 2, 3], [1, 2])[1]).toBe(4);
expect(ear.math.add2([1, 2, 3], [1, 2])[2]).toBe(undefined);
expect(ear.math.add2([1, 2, 3], [])[0]).toBe(NaN);
expect(ear.math.add3([1], [1, 2, 3]).length).toBe(3);
expect(ear.math.add3([1], [1, 2, 3])[0]).toBe(2);
expect(ear.math.add3([1], [1, 2, 3])[1]).toBe(NaN);
expect(ear.math.add3([1, 2, 3], [1, 2])[0]).toBe(2);
expect(ear.math.add3([1, 2, 3], [1, 2])[1]).toBe(4);
expect(ear.math.add3([1, 2, 3], [1, 2])[2]).toBe(NaN);
expect(ear.math.add3([1, 2, 3], [])[0]).toBe(NaN);
});
test("subtract", () => {
expect(ear.math.subtract([1], [2, 3, 4]).length).toBe(1);
expect(ear.math.subtract([1], [2, 3, 4])[0]).toBe(-1);
expect(ear.math.subtract([1, 2, 3], [1, 2])[0]).toBe(0);
expect(ear.math.subtract([1, 2, 3], [1, 2])[1]).toBe(0);
expect(ear.math.subtract([1, 2, 3], [1, 2])[2]).toBe(3);
expect(ear.math.subtract([1, 2, 3], [])[0]).toBe(1);
expect(ear.math.subtract2([1], [2, 3, 4]).length).toBe(2);
expect(ear.math.subtract2([1], [2, 3, 4])[0]).toBe(-1);
expect(ear.math.subtract2([1, 2, 3], [1, 2])[0]).toBe(0);
expect(ear.math.subtract2([1, 2, 3], [1, 2])[1]).toBe(0);
expect(ear.math.subtract2([1, 2, 3], [1, 2])[2]).toBe(undefined);
expect(ear.math.subtract2([1, 2, 3], [])[0]).toBe(NaN);
expect(ear.math.subtract3([1], [2, 3, 4]).length).toBe(3);
expect(ear.math.subtract3([1], [2, 3, 4])[0]).toBe(-1);
expect(ear.math.subtract3([1, 2, 3], [1, 2])[0]).toBe(0);
expect(ear.math.subtract3([1, 2, 3], [1, 2])[1]).toBe(0);
expect(ear.math.subtract3([1, 2, 3], [1, 2])[2]).toBe(NaN);
expect(ear.math.subtract3([1, 2, 3], [])[0]).toBe(NaN);
});
test("dot", () => {
expect(ear.math.dot([3, 1000], [1, 0])).toBe(3);
expect(ear.math.dot([3, 1000], [1, 0])).toBe(3);
expect(ear.math.dot([3, 1000], [0, 1])).toBe(1000);
expect(ear.math.dot([1, 1000], [400])).toBe(400);
expect(ear.math.dot([1, 1000], [400, 0])).toBe(400);
expect(ear.math.dot([1, 1000], [400, 1])).toBe(1400);
expect(ear.math.dot([1, 1000], [])).toBe(0);
expect(ear.math.dot2([3, 1000], [1, 0])).toBe(3);
expect(ear.math.dot2([3, 1000], [1, 0])).toBe(3);
expect(ear.math.dot2([3, 1000], [0, 1])).toBe(1000);
expect(ear.math.dot2([1, 1000], [400])).toBe(NaN);
expect(ear.math.dot2([1, 1000], [400, 0])).toBe(400);
expect(ear.math.dot2([1, 1000], [400, 1])).toBe(1400);
expect(ear.math.dot2([1, 1000], [])).toBe(NaN);
expect(ear.math.dot3([3, 1000], [1, 0])).toBe(NaN);
expect(ear.math.dot3([3, 1000], [1, 0])).toBe(NaN);
expect(ear.math.dot3([3, 1000], [0, 1])).toBe(NaN);
expect(ear.math.dot3([1, 1000], [400])).toBe(NaN);
expect(ear.math.dot3([1, 1000], [400, 0])).toBe(NaN);
expect(ear.math.dot3([1, 1000], [400, 1])).toBe(NaN);
expect(ear.math.dot3([1, 1000], [])).toBe(NaN);
expect(ear.math.dot3([3, 1000, 0], [1, 0, 0])).toBe(3);
expect(ear.math.dot3([3, 1000, 0], [0, 1, 0])).toBe(1000);
expect(ear.math.dot3([3, 1000, 200], [1, 1, 1])).toBe(1203);
expect(ear.math.dot3([1, 1000, 0], [400])).toBe(NaN);
expect(ear.math.dot3([1, 1000, 0], [400, 0, 0])).toBe(400);
expect(ear.math.dot3([1, 1000, 0], [400, 1, 0])).toBe(1400);
expect(ear.math.dot3([1, 1000, 0], [])).toBe(NaN);
});
test("midpoint", () => {
expect(ear.math.midpoint([1, 2], [5, 6, 7]).length).toBe(2);
expect(ear.math.midpoint([1, 2], [5, 6, 7])[0]).toBe(3);
expect(ear.math.midpoint([1, 2], [5, 6, 7])[1]).toBe(4);
expect(ear.math.midpoint([], [5, 6, 7]).length).toBe(0);
expect(ear.math.midpoint2([1, 2], [5, 6, 7]).length).toBe(2);
expect(ear.math.midpoint2([1, 2], [5, 6, 7])[0]).toBe(3);
expect(ear.math.midpoint2([1, 2], [5, 6, 7])[1]).toBe(4);
expect(ear.math.midpoint2([1, 2], [5, 6, 7])[2]).toBe(undefined);
expect(ear.math.midpoint2([], [5, 6, 7]).length).toBe(2);
expect(ear.math.midpoint2([], [5, 6, 7])[0]).toBe(NaN);
expect(ear.math.midpoint2([], [5, 6, 7])[1]).toBe(NaN);
expect(ear.math.midpoint3([1, 2], [5, 6, 7]).length).toBe(3);
expect(ear.math.midpoint3([1, 2], [5, 6, 7])[0]).toBe(3);
expect(ear.math.midpoint3([1, 2], [5, 6, 7])[1]).toBe(4);
expect(ear.math.midpoint3([1, 2], [5, 6, 7])[2]).toBe(NaN);
expect(ear.math.midpoint3([], [5, 6, 7]).length).toBe(3);
expect(ear.math.midpoint3([], [5, 6, 7])[0]).toBe(NaN);
expect(ear.math.midpoint3([], [5, 6, 7])[1]).toBe(NaN);
});
test("average function", () => {
// improper use
expect(ear.math.average()).toBe(undefined);
expect(ear.math.average(0, 1, 2).length).toBe(0);
expect(ear.math.average([], [], []).length).toBe(0);
// correct
testEqual(
[3.75, 4.75],
ear.math.average([4, 1], [5, 6], [4, 6], [2, 6]),
);
testEqual(
[4, 5, 3],
ear.math.average([1, 2, 3], [4, 5, 6], [7, 8]),
);
testEqual(
[4, 5, 6],
ear.math.average([1, 2, 3], [4, 5, 6], [7, 8, 9]),
);
});
test("average2", () => {
expect(ear.math.average2()).toBe(undefined);
expect(ear.math.average2([0, 1], [2, 3])[0]).toBe(1);
expect(ear.math.average2([0, 1], [2, 3])[1]).toBe(2);
expect(ear.math.average2([], [], []).length).toBe(2);
expect(ear.math.average2([], [], [])[0]).toBe(NaN);
expect(ear.math.average2([], [], [])[1]).toBe(NaN);
});
test("lerp", () => {
expect(ear.math.lerp([0, 1], [2, 0], 0)[0]).toBe(0);
expect(ear.math.lerp([0, 1], [2, 0], 0)[1]).toBe(1);
expect(ear.math.lerp([0, 1], [2, 0], 1)[0]).toBe(2);
expect(ear.math.lerp([0, 1], [2, 0], 1)[1]).toBe(0);
expect(ear.math.lerp([0, 1], [2, 0], 0.5)[0]).toBe(1);
expect(ear.math.lerp([0, 1], [2, 0], 0.5)[1]).toBe(0.5);
});
test("cross2", () => {
expect(ear.math.cross2([1, 0], [-4, 3])).toBe(3);
expect(ear.math.cross2([2, -1], [1, 3])).toBe(7);
});
test("cross3", () => {
expect(ear.math.cross3([-3, 0, -2], [5, -1, 2])[0]).toBe(-2);
expect(ear.math.cross3([-3, 0, -2], [5, -1, 2])[1]).toBe(-4);
expect(ear.math.cross3([-3, 0, -2], [5, -1, 2])[2]).toBe(3);
expect(Number.isNaN(ear.math.cross3([-3, 0], [5, -1, 2])[0])).toBe(true);
expect(Number.isNaN(ear.math.cross3([-3, 0], [5, -1, 2])[1])).toBe(true);
expect(Number.isNaN(ear.math.cross3([-3, 0], [5, -1, 2])[2])).toBe(false);
});
test("distance3", () => {
const r1 = ear.math.distance3([1, 2, 3], [4, 5, 6]);
const r2 = ear.math.distance3([1, 2, 3], [4, 5]);
expect(r1).toBeCloseTo(5.196152422706632);
expect(Number.isNaN(r2)).toBe(true);
});
test("rotate90, rotate270", () => {
expect(ear.math.rotate90([-3, 2])[0]).toBe(-2);
expect(ear.math.rotate90([-3, 2])[1]).toBe(-3);
expect(ear.math.rotate270([-3, 2])[0]).toBe(2);
expect(ear.math.rotate270([-3, 2])[1]).toBe(3);
});
test("flip", () => {
expect(ear.math.flip([-2, -1])[0]).toBe(2);
expect(ear.math.flip([-2, -1])[1]).toBe(1);
});
test("degenerate", () => {
expect(ear.math.degenerate([1])).toBe(false);
expect(ear.math.degenerate([1], 1)).toBe(false);
expect(ear.math.degenerate([1], 1 + ear.math.EPSILON)).toBe(true);
expect(ear.math.degenerate([1, 1], 2)).toBe(false);
expect(ear.math.degenerate([1, 1], 2 + ear.math.EPSILON)).toBe(true);
});
test("parallel", () => {
expect(ear.math.parallel([1, 0], [0, 1])).toBe(false);
expect(ear.math.parallel([1, 0], [-1, 0])).toBe(true);
// this is where the parallel test breaks down when it uses dot product
expect(ear.math.parallel([1, 0], [1, 0.0014142])).toBe(true);
expect(ear.math.parallel([1, 0], [1, 0.0014143])).toBe(false);
// this is the parallel test using cross product
expect(ear.math.parallel2([1, 0], [1, 0.0000009])).toBe(true);
expect(ear.math.parallel2([1, 0], [1, 0.0000010])).toBe(false);
});
test("parallelNormalized", () => {
expect(ear.math.parallelNormalized([1, 0], [0, 1])).toBe(false);
expect(ear.math.parallelNormalized([1, 0], [1, 0])).toBe(true);
expect(ear.math.parallelNormalized([1, 0], [-1, 0])).toBe(true);
// unintended usage
expect(ear.math.parallelNormalized([3, 0], [3, 0])).toBe(true);
expect(ear.math.parallelNormalized([2, 0], [1, 0])).toBe(true);
expect(ear.math.parallelNormalized([-2, 0], [1, 0])).toBe(true);
expect(ear.math.parallelNormalized([1, 0], [2, 0])).toBe(true);
expect(ear.math.parallelNormalized([1, 0], [-2, 0])).toBe(true);
});
test("basisVectors2", () => {
expect(ear.math.basisVectors2().length).toBe(2);
const basis1 = ear.math.basisVectors2([1, 0]);
// [-v[1], v[0]]
expect(basis1[0][0]).toBeCloseTo(1);
expect(basis1[0][1]).toBeCloseTo(0);
expect(basis1[1][0]).toBeCloseTo(0);
expect(basis1[1][1]).toBeCloseTo(1);
const basis2 = ear.math.basisVectors2([500, 0]);
expect(basis2[0][0]).toBeCloseTo(1);
expect(basis2[0][1]).toBeCloseTo(0);
expect(basis2[1][0]).toBeCloseTo(0);
expect(basis2[1][1]).toBeCloseTo(1);
const basis3 = ear.math.basisVectors2([0, 500]);
expect(basis3[0][0]).toBeCloseTo(0);
expect(basis3[0][1]).toBeCloseTo(1);
expect(basis3[1][0]).toBeCloseTo(-1);
expect(basis3[1][1]).toBeCloseTo(0);
const basis4 = ear.math.basisVectors2([20, 20]);
expect(basis4[0][0]).toBeCloseTo(Math.SQRT1_2);
expect(basis4[0][1]).toBeCloseTo(Math.SQRT1_2);
expect(basis4[1][0]).toBeCloseTo(-Math.SQRT1_2);
expect(basis4[1][1]).toBeCloseTo(Math.SQRT1_2);
const basis5 = ear.math.basisVectors2([0, 0]);
expect(basis5[0][0]).toBeCloseTo(0);
expect(basis5[0][1]).toBeCloseTo(0);
expect(basis5[1][0]).toBeCloseTo(0);
expect(basis5[1][1]).toBeCloseTo(0);
});
test("basisVectors3", () => {
expect(ear.math.basisVectors3().length).toBe(3);
const basis1 = ear.math.basisVectors3([1, 0, 0]);
expect(basis1[0][0]).toBeCloseTo(1);
expect(basis1[0][1]).toBeCloseTo(0);
expect(basis1[0][2]).toBeCloseTo(0);
expect(basis1[1][0]).toBeCloseTo(0);
expect(basis1[1][1]).toBeCloseTo(0);
expect(basis1[1][2]).toBeCloseTo(-1);
expect(basis1[2][0]).toBeCloseTo(0);
expect(basis1[2][1]).toBeCloseTo(1);
expect(basis1[2][2]).toBeCloseTo(0);
const basis2 = ear.math.basisVectors3([0, 0, 500]);
expect(basis2[0][0]).toBeCloseTo(0);
expect(basis2[0][1]).toBeCloseTo(0);
expect(basis2[0][2]).toBeCloseTo(1);
expect(basis2[1][0]).toBeCloseTo(0);
expect(basis2[1][1]).toBeCloseTo(-1);
expect(basis2[1][2]).toBeCloseTo(0);
expect(basis2[2][0]).toBeCloseTo(1);
expect(basis2[2][1]).toBeCloseTo(0);
expect(basis2[2][2]).toBeCloseTo(0);
const basis3 = ear.math.basisVectors3([1, 1, 1]);
expect(basis3[0][0]).toBeCloseTo(Math.sqrt(3) / 3);
expect(basis3[0][1]).toBeCloseTo(Math.sqrt(3) / 3);
expect(basis3[0][2]).toBeCloseTo(Math.sqrt(3) / 3);
expect(basis3[1][0]).toBeCloseTo(0);
expect(basis3[1][1]).toBeCloseTo(-Math.SQRT1_2);
expect(basis3[1][2]).toBeCloseTo(Math.SQRT1_2);
expect(basis3[2][0]).toBeCloseTo((Math.sqrt(3) / 3) * Math.SQRT2);
expect(basis3[2][1]).toBeCloseTo(-((Math.sqrt(3) / 3) * Math.SQRT2) / 2);
expect(basis3[2][2]).toBeCloseTo(-((Math.sqrt(3) / 3) * Math.SQRT2) / 2);
const basis4 = ear.math.basisVectors3([0, 0, 0]);
expect(basis4[0][0]).toBeCloseTo(0);
expect(basis4[0][1]).toBeCloseTo(0);
expect(basis4[0][2]).toBeCloseTo(0);
expect(basis4[1][0]).toBeCloseTo(0);
expect(basis4[1][1]).toBeCloseTo(0);
expect(basis4[1][2]).toBeCloseTo(0);
expect(basis4[2][0]).toBeCloseTo(0);
expect(basis4[2][1]).toBeCloseTo(0);
expect(basis4[2][2]).toBeCloseTo(0);
});
================================================
FILE: tests/math.debug.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("single test for debugging", () => {
expect(true).toBe(true);
});
================================================
FILE: tests/math.general.array.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("removed", () => expect(true).toBe(true));
// const equalTest = (a, b) => expect(JSON.stringify(a))
// .toBe(JSON.stringify(b));
// /**
// * inputs and argument inference
// */
// test("semiFlattenArrays", () => {
// equalTest(
// [[0, 1, 2], [2, 3, 4]],
// ear.math.semiFlattenArrays([0, 1, 2], [2, 3, 4]),
// );
// equalTest(
// [[0, 1, 2], [2, 3, 4]],
// ear.math.semiFlattenArrays([[0, 1, 2]], [[2, 3, 4]]),
// );
// equalTest(
// [[0, 1, 2], [2, 3, 4]],
// ear.math.semiFlattenArrays([[[0, 1, 2]], [[2, 3, 4]]]),
// );
// equalTest(
// [[0, 1, 2], [2, 3, 4]],
// ear.math.semiFlattenArrays([[[[0, 1, 2]], [[2, 3, 4]]]]),
// );
// equalTest(
// [[[0], [1], [2]], [2, 3, 4]],
// ear.math.semiFlattenArrays([[[[0], [1], [2]]], [[2, 3, 4]]]),
// );
// equalTest(
// [[[0], [1], [2]], [2, 3, 4]],
// ear.math.semiFlattenArrays([[[[[[0]]], [[[1]]], [2]]], [[2, 3, 4]]]),
// );
// equalTest(
// [{ x: 5, y: 3 }],
// ear.math.semiFlattenArrays({ x: 5, y: 3 }),
// );
// equalTest(
// [{ x: 5, y: 3 }],
// ear.math.semiFlattenArrays([[[{ x: 5, y: 3 }]]]),
// );
// equalTest(
// [5, 3],
// ear.math.semiFlattenArrays([[[5, 3]]]),
// );
// equalTest(
// [[5], [3]],
// ear.math.semiFlattenArrays([[[5], [3]]]),
// );
// equalTest(
// [[5], [3]],
// ear.math.semiFlattenArrays([[[5]], [[3]]]),
// );
// equalTest(
// [[5], [3]],
// ear.math.semiFlattenArrays([[[5]]], [[[3]]]),
// );
// });
// test("flattenArrays", () => {
// equalTest(
// [1],
// ear.math.flattenArrays([[[1]], []]),
// );
// equalTest(
// [1, 2, 3, 4],
// ear.math.flattenArrays([[[1, 2, 3, 4]]]),
// );
// equalTest(
// [1, 2, 3, 4],
// ear.math.flattenArrays(1, 2, 3, 4),
// );
// equalTest(
// [1, 2, 3, 4, 2, 4],
// ear.math.flattenArrays([1, 2, 3, 4], [2, 4]),
// );
// equalTest(
// [1, 2, 3, 4, 6, 7, 6],
// ear.math.flattenArrays([1, 2, 3, 4], [6, 7], 6),
// );
// equalTest(
// [1, 2, 3, 4, 6, 7, 6, 2, 4, 5],
// ear.math.flattenArrays([1, 2, 3, 4], [6, 7], 6, 2, 4, 5),
// );
// equalTest(
// [{ x: 5, y: 3 }],
// ear.math.flattenArrays({ x: 5, y: 3 }),
// );
// equalTest(
// [{ x: 5, y: 3 }],
// ear.math.flattenArrays([[{ x: 5, y: 3 }]]),
// );
// equalTest(
// [1, 2, 3, 4, 5, 6],
// ear.math.flattenArrays([[[1], [2, 3]]], 4, [5, 6]),
// );
// equalTest(
// [undefined, undefined],
// ear.math.flattenArrays([[[undefined, [[undefined]]]]]),
// );
// });
================================================
FILE: tests/math.general.constant.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("constants", () => {
expect(typeof ear.math.EPSILON).toBe("number");
expect(typeof ear.math.TWO_PI).toBe("number");
expect(typeof ear.math.D2R).toBe("number");
expect(typeof ear.math.R2D).toBe("number");
});
================================================
FILE: tests/math.general.convert.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
const t = 0.38268343236509;
const n = 0.92387953251129;
const s = Math.SQRT1_2;
// [
// {u:[ 0, 1], d:0},
// {u:[-t, n], d:0},
// {u:[-s, s], d:0},
// {u:[-n, t], d:0},
// {u:[-1, 0], d:0},
// {u:[-n,-t], d:0},
// {u:[-s,-s], d:0},
// {u:[-t,-n], d:0},
// {u:[ 0,-1], d:0},
// {u:[ t,-n], d:0},
// {u:[ s,-s], d:0},
// {u:[ n,-t], d:0},
// {u:[ 1, 0], d:0},
// {u:[ n, t], d:0},
// {u:[ s, s], d:0},
// {u:[ t, n], d:0},
// ]
test("16 angles of lines, through the origin", () => {
const angles = Array.from(Array(16))
.map((_, i) => ((Math.PI * 2) / 16) * i);
const vectors = angles.map(a => [Math.cos(a), Math.sin(a)]);
const origins = angles.map(() => [0, 0]);
vectors
.map((vector, i) => ({ vector, origin: origins[i] }))
.map(vec_or => ear.math.vecLineToUniqueLine(vec_or))
.map(norm_dist => ear.math.uniqueLineToVecLine(norm_dist))
.forEach((el, i) => {
expect(el.vector[0]).toBeCloseTo(vectors[i][0]);
expect(el.vector[1]).toBeCloseTo(vectors[i][1]);
expect(el.origin[0]).toBeCloseTo(origins[i][0]);
expect(el.origin[1]).toBeCloseTo(origins[i][1]);
});
});
// [
// {u:[-0, 1], d:1},
// {u:[-t, n], d:1},
// {u:[-s, s], d:1},
// {u:[-n, t], d:1},
// {u:[-1, 0], d:1},
// {u:[-n,-t], d:1},
// {u:[-s,-s], d:1},
// {u:[-t,-n], d:1},
// {u:[-0,-1], d:1},
// {u:[ t,-n], d:1},
// {u:[ s,-s], d:1},
// {u:[ n,-t], d:1},
// {u:[ 1,-0], d:1},
// {u:[ n, t], d:1},
// {u:[ s, s], d:1},
// {u:[ t, n], d:1},
// ];
test("16 angles of lines, not through the origin, dir 1", () => {
const angles = Array.from(Array(16))
.map((_, i) => ((Math.PI * 2) / 16) * i);
const vectors = angles.map(a => [Math.cos(a), Math.sin(a)]);
const origins = angles
.map(a => [Math.cos(a + Math.PI / 2), Math.sin(a + Math.PI / 2)]);
vectors
.map((vector, i) => ({ vector, origin: origins[i] }))
.map(vec_or => ear.math.vecLineToUniqueLine(vec_or))
.map(norm_dist => ear.math.uniqueLineToVecLine(norm_dist))
.forEach((el, i) => {
expect(el.vector[0]).toBeCloseTo(vectors[i][0]);
expect(el.vector[1]).toBeCloseTo(vectors[i][1]);
expect(el.origin[0]).toBeCloseTo(origins[i][0]);
expect(el.origin[1]).toBeCloseTo(origins[i][1]);
});
});
test("16 angles of lines, not through the origin, dir 2", () => {
const angles = Array.from(Array(16))
.map((_, i) => ((Math.PI * 2) / 16) * i);
const vectors = angles.map(a => [Math.cos(a), Math.sin(a)]);
const origins = angles
.map(a => [Math.cos(a - Math.PI / 2), Math.sin(a - Math.PI / 2)]);
vectors
.map((vector, i) => ({ vector, origin: origins[i] }))
.map(vec_or => ear.math.vecLineToUniqueLine(vec_or))
.map(norm_dist => ear.math.uniqueLineToVecLine(norm_dist))
.forEach((el, i) => {
expect(el.vector[0]).toBeCloseTo(vectors[i][0]);
expect(el.vector[1]).toBeCloseTo(vectors[i][1]);
expect(el.origin[0]).toBeCloseTo(origins[i][0]);
expect(el.origin[1]).toBeCloseTo(origins[i][1]);
});
});
================================================
FILE: tests/math.general.function.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("clamp functions", () => {
expect(ear.math.clampLine(0)).toBe(0);
expect(ear.math.clampLine(-Infinity)).toBe(-Infinity);
expect(ear.math.clampLine(Infinity)).toBe(Infinity);
expect(ear.math.clampLine(NaN)).toBe(NaN);
expect(ear.math.clampRay(0)).toBe(0);
expect(ear.math.clampRay(-1e-10)).toBe(-1e-10);
expect(ear.math.clampRay(-1e-1)).toBe(0);
expect(ear.math.clampRay(Infinity)).toBe(Infinity);
expect(ear.math.clampRay(-Infinity)).toBe(0);
expect(ear.math.clampSegment(0)).toBe(0);
expect(ear.math.clampSegment(-1e-10)).toBe(-1e-10);
expect(ear.math.clampSegment(-1e-1)).toBe(0);
expect(ear.math.clampSegment(Infinity)).toBe(1);
expect(ear.math.clampSegment(-Infinity)).toBe(0);
});
test("epsilonEqual", () => {
const smEp = ear.math.EPSILON / 10; // smaller than epsilon
const bgEp = ear.math.EPSILON * 10; // larger than epsilon
expect(ear.math.epsilonEqual(0, 0)).toBe(true);
expect(ear.math.epsilonEqual(0, smEp)).toBe(true);
expect(ear.math.epsilonEqual(10, 10)).toBe(true);
expect(ear.math.epsilonEqual(0, 1)).toBe(false);
expect(ear.math.epsilonEqual(1, 0)).toBe(false);
expect(ear.math.epsilonEqual(0, 0, smEp)).toBe(true);
expect(ear.math.epsilonEqual(0, 0, 1)).toBe(true);
expect(ear.math.epsilonEqual(0, 1, smEp)).toBe(false);
expect(ear.math.epsilonEqual(1, 0, smEp)).toBe(false);
expect(ear.math.epsilonEqual(0, 1, 10)).toBe(true);
expect(ear.math.epsilonEqual(0, smEp, bgEp)).toBe(true);
expect(ear.math.epsilonEqual(0, bgEp, smEp)).toBe(false);
expect(ear.math.epsilonEqual(bgEp, 0, smEp)).toBe(false);
});
test("epsilonCompare", () => {
const smEp = ear.math.EPSILON / 10; // smaller than epsilon
const bgEp = ear.math.EPSILON * 10; // larger than epsilon
expect(ear.math.epsilonCompare(0, 0)).toBe(0);
expect(ear.math.epsilonCompare(0, smEp)).toBe(0);
expect(ear.math.epsilonCompare(10, 10)).toBe(0);
expect(ear.math.epsilonCompare(0, 1)).toBe(-1);
expect(ear.math.epsilonCompare(1, 0)).toBe(1);
expect(ear.math.epsilonCompare(0, 0, smEp)).toBe(0);
expect(ear.math.epsilonCompare(0, 0, 1)).toBe(0);
expect(ear.math.epsilonCompare(0, 1, smEp)).toBe(-1);
expect(ear.math.epsilonCompare(1, 0, smEp)).toBe(1);
expect(ear.math.epsilonCompare(0, 1, 10)).toBe(0);
expect(ear.math.epsilonCompare(0, smEp, bgEp)).toBe(0);
expect(ear.math.epsilonCompare(0, bgEp, smEp)).toBe(-1);
expect(ear.math.epsilonCompare(bgEp, 0, smEp)).toBe(1);
});
test("epsilonCompare to sort", () => {
const smEp = ear.math.EPSILON / 10; // smaller than epsilon
const array = [0, 0 + smEp, 1, 3 + smEp * 2, 3, 2, 1.1];
// sort increasing (or leave pairs untouched)
array.sort(ear.math.epsilonCompare);
// the result is an increasing array, except that values within an epsilon
// are allowed to be unsorted with respect to each other.
// hence, we test for equality. will be either "less than" or "equal".
for (let i = 0; i < array.length - 1; i += 1) {
const equal = ear.math.epsilonEqual(array[i], array[i + 1]);
const lessThan = array[i] < array[i + 1];
expect(equal || lessThan).toBe(true);
}
});
test("equivalent vectors", () => {
const smEp = ear.math.EPSILON / 10; // smaller than epsilon
const bgEp = ear.math.EPSILON * 10; // larger than epsilon
expect(ear.math.epsilonEqualVectors([1, 2, 3], [1, 2, 3])).toBe(true);
expect(ear.math.epsilonEqualVectors([1, 2 + smEp], [1, 2 - smEp])).toBe(true);
expect(ear.math.epsilonEqualVectors([1, 2 + bgEp], [1, 2 - bgEp])).toBe(false);
expect(ear.math.epsilonEqualVectors([1, 2], [1, 2.0000000001])).toBe(true);
expect(ear.math.epsilonEqualVectors([1, 2, 3, 4], [1, 2])).toBe(false);
expect(ear.math.epsilonEqualVectors([], [])).toBe(true);
expect(ear.math.epsilonEqualVectors([1.000000001, -1], [1, -1])).toBe(true);
expect(ear.math.epsilonEqualVectors([1.000000001, 0], [1])).toBe(true);
expect(ear.math.epsilonEqualVectors([1.000000001, 0], [1, 0])).toBe(true);
});
================================================
FILE: tests/math.general.get.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("removed", () => expect(true).toBe(true));
// const equalTest = (a, b) => expect(JSON.stringify(a))
// .toBe(JSON.stringify(b));
// test("getVector", () => {
// equalTest(
// [1, 2, 3, 4],
// ear.math.getVector([[[1, 2, 3, 4]]]),
// );
// equalTest(
// [1, 2, 3, 4],
// ear.math.getVector(1, 2, 3, 4),
// );
// equalTest(
// [1, 2, 3, 4, 2, 4],
// ear.math.getVector([1, 2, 3, 4], [2, 4]),
// );
// equalTest(
// [1, 2, 3, 4, 6, 7, 6],
// ear.math.getVector([1, 2, 3, 4], [6, 7], 6),
// );
// equalTest(
// [1, 2, 3, 4, 6, 7, 6, 2, 4, 5],
// ear.math.getVector([1, 2, 3, 4], [6, 7], 6, 2, 4, 5),
// );
// equalTest(
// [5, 3],
// ear.math.getVector({ x: 5, y: 3 }),
// );
// equalTest(
// [5, 3],
// ear.math.getVector([[[{ x: 5, y: 3 }]]]),
// );
// equalTest(
// [5, 3],
// ear.math.getVector([[[5, 3]]]),
// );
// equalTest(
// [5, 3],
// ear.math.getVector([[[5], [3]]]),
// );
// equalTest(
// [5, 3],
// ear.math.getVector([[[5]], [[3]]]),
// );
// equalTest(
// [5, 3],
// ear.math.getVector([[[5]]], [[[3]]]),
// );
// equalTest(
// [5, 3],
// ear.math.getVector([[[5]]], 3),
// );
// });
// test("getLine", () => {
// equalTest(ear.math.getLine(1), { vector: [1], origin: [] });
// equalTest(ear.math.getLine(1, 2), { vector: [1, 2], origin: [] });
// equalTest(ear.math.getLine(1, 2, 3), { vector: [1, 2, 3], origin: [] });
// equalTest(ear.math.getLine([1], [2]), { vector: [1], origin: [2] });
// equalTest(ear.math.getLine([1, 2], [2, 3]), { vector: [1, 2], origin: [2, 3] });
// equalTest(ear.math.getLine(), { vector: [], origin: [] });
// equalTest(ear.math.getLine({}), { vector: [], origin: [] });
// equalTest(
// ear.math.getLine({ vector: [1], origin: [2] }),
// { vector: [1], origin: [2] },
// );
// equalTest(
// ear.math.getLine({ vector: [1, 2], origin: [2, 3] }),
// { vector: [1, 2], origin: [2, 3] },
// );
// equalTest(
// ear.math.getLine({ vector: [1] }),
// { vector: [1], origin: [] },
// );
// // "getLine" only looks for a "vector" key,
// // this will result in an empty object
// equalTest(
// ear.math.getLine({ origin: [1] }),
// { vector: [], origin: [] },
// );
// equalTest(ear.math.getLine(), { vector: [], origin: [] });
// equalTest(ear.math.getLine({}), { vector: [], origin: [] });
// equalTest(ear.math.getLine([]), { vector: [], origin: [] });
// equalTest(ear.math.getLine([{}]), { vector: [], origin: [] });
// equalTest(ear.math.getLine(undefined), { vector: [], origin: [] });
// equalTest(ear.math.getLine([undefined]), { vector: [], origin: [] });
// equalTest(ear.math.getLine(null), { vector: [], origin: [] });
// equalTest(ear.math.getLine([null]), { vector: [], origin: [] });
// equalTest(ear.math.getLine(NaN), { vector: [NaN], origin: [] });
// equalTest(ear.math.getLine([NaN]), { vector: [NaN], origin: [] });
// });
// test("getArrayOfVectors", () => {
// equalTest(
// [[1, 2], [3, 4]],
// ear.math.getArrayOfVectors({ x: 1, y: 2 }, { x: 3, y: 4 }),
// );
// equalTest(
// [[1, 2], [3, 4]],
// ear.math.getArrayOfVectors([[[{ x: 1, y: 2 }, { x: 3, y: 4 }]]]),
// );
// equalTest(
// [[1, 2], [3, 4]],
// ear.math.getArrayOfVectors([[[1, 2], [3, 4]]]),
// );
// equalTest(
// [[1, 2], [3, 4]],
// ear.math.getArrayOfVectors([[[1, 2]], [[3, 4]]]),
// );
// equalTest(
// [[1, 2], [3, 4]],
// ear.math.getArrayOfVectors([[[1, 2]]], [[[3, 4]]]),
// );
// equalTest(
// [[1], [2], [3], [4]],
// ear.math.getArrayOfVectors([[[1], [2], [3], [4]]]),
// );
// equalTest(
// [[1], [2], [3], [4]],
// ear.math.getArrayOfVectors([[[1]], [[2]], [[3]], [[4]]]),
// );
// equalTest(
// [[1], [2], [3], [4]],
// ear.math.getArrayOfVectors([[[1]]], 2, 3, 4),
// );
// equalTest(
// [[1], [2], [3], [4]],
// ear.math.getArrayOfVectors([[[1, 2, 3, 4]]]),
// );
// });
// test("getSegment", () => {
// equalTest([[1, 2], [3, 4]], ear.math.getSegment(1, 2, 3, 4));
// equalTest([[1, 2], [3, 4]], ear.math.getSegment([1, 2], [3, 4]));
// equalTest([[1, 2], [3, 4]], ear.math.getSegment([1, 2, 3, 4]));
// equalTest([[1, 2], [3, 4]], ear.math.getSegment([[1, 2], [3, 4]]));
// });
// test("get_matrix2", () => {
// equalTest(
// [1, 2, 3, 4, 5, 6],
// ear.math.get_matrix2([[[1, 2, 3, 4, 5, 6]]])
// );
// equalTest(
// [1, 2, 3, 4, 0, 0],
// ear.math.get_matrix2([[1, 2, 3, 4]])
// );
// equalTest(
// [1, 2, 3, 1, 0, 0],
// ear.math.get_matrix2(1, 2, 3)
// );
// equalTest(
// [1, 2, 3, 1, 0, 0],
// ear.math.get_matrix2(1, 2, 3, 1)
// );
// });
// test("getMatrix3x4", () => {
// equalTest(
// [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
// ear.math.getMatrix3x4([[[]]]),
// );
// equalTest(
// [1, 2, 0, 3, 4, 0, 0, 0, 1, 0, 0, 0],
// ear.math.getMatrix3x4([[[1, 2, 3, 4]]]),
// );
// equalTest(
// [1, 2, 0, 3, 4, 0, 0, 0, 1, 5, 6, 0],
// ear.math.getMatrix3x4([[[1, 2, 3, 4, 5, 6]]]),
// );
// equalTest(
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0],
// ear.math.getMatrix3x4([[[1, 2, 3, 4, 5, 6, 7, 8, 9]]]),
// );
// });
================================================
FILE: tests/math.general.sort.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
const equalTest = (a, b) => expect(JSON.stringify(a))
.toBe(JSON.stringify(b));
test("sortPointsAlongVector", () => {
const points = [[1, 0], [0, 1], [-1, 0], [0, -1]];
const result = ear.general.sortPointsAlongVector(points, [1, 0]);
expect(result[0]).toBe(2);
expect([result[1], result[2]].sort((a, b) => a - b).join(" ")).toBe("1 3");
expect(result[3]).toBe(0);
});
// no longer included in API
// test("clusterIndicesOfSortedNumbers", () => {
// const result = ear.general.clusterIndicesOfSortedNumbers([0, 1, 2, 3, 4, 5]);
// equalTest(result, [[0], [1], [2], [3], [4], [5]]);
// const result1 = ear.general.clusterIndicesOfSortedNumbers([0, 1, 2, 3, 4, 5], 1);
// equalTest(result1, [[0], [1], [2], [3], [4], [5]]);
// const result2 = ear.general
// .clusterIndicesOfSortedNumbers([0, 1, 2, 3, 4, 5], 1 + ear.math.EPSILON * 2);
// equalTest(result2, [[0, 1, 2, 3, 4, 5]]);
// });
test("convexHullRadialSortPoints", () => {
equalTest(ear.math.convexHullRadialSortPoints(), []);
const result0 = ear.math.convexHullRadialSortPoints([[1, 0], [0, 1], [-1, 0]]);
equalTest(result0, [[2], [0], [1]]);
const result1 = ear.math.convexHullRadialSortPoints([[0, 1], [-1, 0], [1, 0]]);
equalTest(result1, [[1], [2], [0]]);
const result2 = ear.math.convexHullRadialSortPoints([[-1, 0], [1, 0], [0, 1]]);
equalTest(result2, [[0], [1], [2]]);
const result3 = ear.math.convexHullRadialSortPoints([[1, 0], [0, 1], [-1, 0]], 2);
equalTest(result3, [[2], [1, 0]]);
const result4 = ear.math.convexHullRadialSortPoints([[0, 1], [-1, 0], [1, 0]], 2);
equalTest(result4, [[1], [0, 2]]);
const result5 = ear.math.convexHullRadialSortPoints([[-1, 0], [1, 0], [0, 1]], 2);
equalTest(result5, [[0], [2, 1]]);
});
test("radialSortVectors3", () => {
const points = Array.from(Array(24))
.map(() => [Math.random() * 2 - 1, Math.random() * 2 - 1, Math.random() * 2 - 1]);
points.push([0, 0, 0]);
const result = ear.general.radialSortVectors3(points, [1, 0, 0]);
expect(result.length).toBe(25);
});
test("radialSortVectors3", () => {
const points = [
[1, 1, 1],
[-1, -1, -1],
[-1, -1, 1],
[1, 1, -1],
];
const resultX = ear.general.radialSortVectors3(points, [1, 0, 0]);
const resultY = ear.general.radialSortVectors3(points, [0, 1, 0]);
const resultZ = ear.general.radialSortVectors3(points, [0, 0, 1]);
const resultXn = ear.general.radialSortVectors3(points, [-1, 0, 0]);
const resultYn = ear.general.radialSortVectors3(points, [0, -1, 0]);
const resultZn = ear.general.radialSortVectors3(points, [0, 0, -1]);
expect(JSON.stringify(resultX)).toBe(JSON.stringify([3, 0, 2, 1]));
expect(JSON.stringify(resultY)).toBe(JSON.stringify([0, 3, 1, 2]));
expect(JSON.stringify(resultZ)).toBe(JSON.stringify([0, 3, 1, 2]));
expect(JSON.stringify(resultXn)).toBe(JSON.stringify([0, 3, 1, 2]));
expect(JSON.stringify(resultYn)).toBe(JSON.stringify([3, 0, 2, 1]));
expect(JSON.stringify(resultZn)).toBe(JSON.stringify([0, 3, 1, 2]));
});
// test("smallestVector2 easy", () => {
// expect(ear.math.smallestVector2()).toBe(undefined);
// expect(ear.math.smallestVector2([])).toBe(undefined);
// expect(ear.math.smallestVector2([[0, 0], [1, 0], [2, 0], [3, 0], [4, 0]])).toBe(0);
// expect(ear.math.smallestVector2([[4, 0], [3, 0], [2, 0], [1, 0], [0, 0]])).toBe(4);
// expect(ear.math.smallestVector2([[2, 0], [1, 0], [0, 0], [4, 0], [3, 0]])).toBe(2);
// });
// test("smallestVector2 vertically aligned", () => {
// expect(ear.math.smallestVector2([[3, 0], [3, 1], [3, 2], [3, 3], [3, 4]])).toBe(0);
// expect(ear.math.smallestVector2([[3, 1], [3, 2], [3, 3], [3, 4], [3, 0]])).toBe(4);
// expect(ear.math.smallestVector2([[3, 2], [3, 3], [3, 4], [3, 0], [3, 1]])).toBe(3);
// expect(ear.math.smallestVector2([[3, 3], [3, 4], [3, 0], [3, 1], [3, 2]])).toBe(2);
// });
================================================
FILE: tests/math.general.typeof.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("removed", () => expect(true).toBe(true));
// test("type guessing", () => {
// const vector1 = [1, 2, 3];
// const vector2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// const line = { vector: [1, 1], origin: [0.5, 0.5] };
// const segment1 = [[1, 2], [4, 5]];
// const polygon1 = [[1, 2]];
// const polygon2 = [[1, 2], [4, 5], [6, 7]];
// const polygon3 = [[1], [2], [3], [4]];
// const circle = { radius: 1, origin: [1, 2] };
// const boundingBox1 = { min: [1, 2], max: [6, 8], span: [5, 6] };
// const boundingBox2 = { min: [3], max: [5], span: [2] };
// expect(ear.math.typeof(vector1)).toBe("vector");
// expect(ear.math.typeof(vector2)).toBe("vector");
// expect(ear.math.typeof(line)).toBe("line");
// expect(ear.math.typeof(segment1)).toBe("segment");
// expect(ear.math.typeof(polygon1)).toBe("polygon");
// expect(ear.math.typeof(polygon2)).toBe("polygon");
// expect(ear.math.typeof(polygon3)).toBe("polygon");
// expect(ear.math.typeof(circle)).toBe("circle");
// expect(ear.math.typeof(boundingBox1)).toBe("box");
// expect(ear.math.typeof(boundingBox2)).toBe("box");
// // Javascript primitives
// expect(ear.math.typeof({})).toBe("object");
// expect(ear.math.typeof([])).toBe("object");
// expect(ear.math.typeof(() => {})).toBe("function");
// expect(ear.math.typeof(4)).toBe("number");
// expect(ear.math.typeof(true)).toBe("boolean");
// expect(ear.math.typeof("s")).toBe("string");
// });
// test("speed of type guessing", () => {
// const objects = [
// [1, 2, 3],
// [1, 2, 3, 4, 5, 6, 7, 8, 9],
// { vector: [1, 1], origin: [0.5, 0.5] },
// [[1, 2], [4, 5]],
// [[1, 2]],
// [[1, 2], [4, 5], [6, 7]],
// [[1], [2], [3], [4]],
// { radius: 1, origin: [1, 2] },
// ];
// // one million takes 54 milliseconds
// console.time("type-speed");
// for (let i = 0; i < 1000000; i += 1) {
// ear.math.typeof(objects[i % objects.length]);
// }
// console.timeEnd("type-speed");
// });
================================================
FILE: tests/math.geometry.convexHull.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("convexHull", () => {
const rect = [
[1, 0],
[0, 0],
[1, 1],
[0, 1],
];
const res0 = ear.math.convexHull(rect)
.map(v => rect[v]);
const res1 = ear.math.convexHull(rect, true)
.map(v => rect[v]);
expect(res0.length).toBe(4);
expect(res1.length).toBe(4);
});
test("convexHull collinear", () => {
const rect_collinear = [
[1, 0],
[0, 0],
[1, 1],
[0, 1],
[0.5, 0],
[0, 0.5],
[1, 0.5],
[0.5, 1],
];
const res0 = ear.math.convexHull(rect_collinear)
.map(v => rect_collinear[v]);
const res1 = ear.math.convexHull(rect_collinear, true)
.map(v => rect_collinear[v]);
expect(res0.length).toBe(4);
expect(res1.length).toBe(8);
});
test("convexHull collinear", () => {
const rect_collinear = [
[3, 0],
[0, 0],
[3, 3],
[0, 3],
// collinear points
[1, 0],
[0, 1],
[3, 1],
[1, 3],
[2, 0],
[0, 2],
[3, 2],
[2, 3],
];
const res0 = ear.math.convexHull(rect_collinear)
.map(v => rect_collinear[v]);
const res1 = ear.math.convexHull(rect_collinear, true)
.map(v => rect_collinear[v]);
expect(res0.length).toBe(4);
expect(res1.length).toBe(12);
});
test("convexHull axisaligned", () => {
const rect = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
];
const res0 = ear.math.convexHull(rect)
.map(v => rect[v]);
const res1 = ear.math.convexHull(rect, true)
.map(v => rect[v]);
expect(res0.length).toBe(4);
expect(res1.length).toBe(4);
});
test("convexHull collinear axisaligned", () => {
const rect = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
[0.5, 0.5],
[0.5, -0.5],
[-0.5, -0.5],
[-0.5, 0.5],
];
const res0 = ear.math.convexHull(rect)
.map(v => rect[v]);
const res1 = ear.math.convexHull(rect, true)
.map(v => rect[v]);
expect(res0.length).toBe(4);
expect(res1.length).toBe(8);
});
test("convexHull collinear axisaligned", () => {
const rect = [
[3, 0],
[-3, 0],
[0, 3],
[0, -3],
// collinear points
[1, 2],
[2, 1],
[1, -2],
[2, -1],
[-1, -2],
[-2, -1],
[-1, 2],
[-2, 1],
];
const res0 = ear.math.convexHull(rect)
.map(v => rect[v]);
const res1 = ear.math.convexHull(rect, true)
.map(v => rect[v]);
expect(res0.length).toBe(4);
expect(res1.length).toBe(12);
});
================================================
FILE: tests/math.geometry.line.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("collinearBetween", () => {
const [p0, p2] = [[0, 0], [1, 0]];
const p1 = [0.5, 0];
expect(ear.math.collinearBetween(p0, p1, p2, false)).toBe(true);
});
test("collinearBetween on endpoint, inclusive", () => {
const [p0, p2] = [[0, 0], [1, 0]];
const p1 = [1e-12, 0];
expect(ear.math.collinearBetween(p0, p1, p2, true)).toBe(true);
});
test("collinearBetween on endpoint, exclusive", () => {
const [p0, p2] = [[0, 0], [1, 0]];
const p1 = [1e-12, 0];
expect(ear.math.collinearBetween(p0, p1, p2)).toBe(false);
});
test("collinearBetween almost near endpoint, exclusive", () => {
const [p0, p2] = [[0, 0], [1, 0]];
const p1 = [1e-4, 0];
expect(ear.math.collinearBetween(p0, p1, p2)).toBe(true);
});
test("collinearBetween perpendicularly away too far", () => {
const [p0, p2] = [[0, 0], [1, 0]];
expect(ear.math.collinearBetween(p0, [0.5, 1e-2], p2)).toBe(false);
expect(ear.math.collinearBetween(p0, [0.5, 1e-3], p2)).toBe(false);
expect(ear.math.collinearBetween(p0, [0.5, 1e-4], p2)).toBe(true);
expect(ear.math.collinearBetween(p0, [0.5, 1e-5], p2)).toBe(true);
});
test("collinearBetween perpendicularly away near", () => {
const [p0, p2] = [[0, 0], [1, 0]];
const p1 = [0.5, 1e-12];
expect(ear.math.collinearBetween(p0, p1, p2)).toBe(true);
});
test("pleats", () => {
const a = { vector: [1, 0], origin: [0, 0] };
const b = { vector: [1, 0], origin: [10, 0] };
const pleats = ear.math.pleat(a, b, 10);
pleats[0].forEach((line, i) => {
expect(line.origin[0]).toBeCloseTo(i + 1);
});
pleats[0].forEach(line => {
expect(line.vector[0]).toBeCloseTo(1);
expect(line.vector[1]).toBeCloseTo(0);
});
});
test("pleats, opposite vector", () => {
const a = { vector: [1, 0], origin: [0, 0] };
const b = { vector: [-1, 0], origin: [1, 0] };
const pleats = ear.math.pleat(a, b, 4);
expect(pleats[0].length).toBe(0);
pleats[1].forEach(line => {
expect(line.vector[0]).toBeCloseTo(1);
expect(line.vector[1]).toBeCloseTo(0);
});
});
// test("lerp lines, opposite vectors", () => {
// const a = { vector: [1, 0], origin: [0, 0] };
// const b = { vector: [-1, 0], origin: [1, 0] };
// expect(ear.math.lerpLines(a, b, 0.25).origin[0]).toBeCloseTo(0.25);
// expect(ear.math.lerpLines(a, b, 0.5).origin[0]).toBeCloseTo(0.5);
// expect(ear.math.lerpLines(a, b, 0.75).origin[0]).toBeCloseTo(0.75);
// expect(ear.math.lerpLines(a, b, 0.25).origin[1]).toBeCloseTo(0);
// expect(ear.math.lerpLines(a, b, 0.5).origin[1]).toBeCloseTo(0);
// expect(ear.math.lerpLines(a, b, 0.75).origin[1]).toBeCloseTo(0);
// expect(ear.math.lerpLines(a, b, 0.25).vector[0]).toBeCloseTo(0.5);
// expect(ear.math.lerpLines(a, b, 0.5).vector[0]).toBeCloseTo(0);
// expect(ear.math.lerpLines(a, b, 0.75).vector[0]).toBeCloseTo(-0.5);
// expect(ear.math.lerpLines(a, b, 0.25).vector[1]).toBeCloseTo(0);
// expect(ear.math.lerpLines(a, b, 0.5).vector[1]).toBeCloseTo(0);
// expect(ear.math.lerpLines(a, b, 0.75).vector[1]).toBeCloseTo(0);
// });
================================================
FILE: tests/math.geometry.nearest.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
const testEqualVectors = function (...args) {
expect(ear.math.epsilonEqualVectors(...args)).toBe(true);
};
test("nearest point", () => {
testEqualVectors([5, 5], ear.math.nearestPoint2(
[[0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7], [8, 8], [9, 9]],
[10, 0],
));
testEqualVectors([6, 6, 0], ear.math.nearestPoint(
[[0, 0, 0], [1, 1, 0], [2, 2, 0], [3, 3, 0], [4, 4, 1],
[5, 5, 10], [6, 6, 0], [7, 7, 0], [8, 8, 0], [9, 9, 0]],
[10, 0, 0],
));
});
test("nearestPointOnPolygon", () => {
const polygon = [[1, 0], [0, 1], [-1, 0], [0, -1]];
const result = ear.math.nearestPointOnPolygon(polygon, [10, 10]);
// result { point: [ 0.5, 0.5 ], edge: 0, distance: 13.435028842544403 }
expect(result.point[0]).toBe(0.5);
expect(result.point[1]).toBe(0.5);
expect(result.distance).toBeCloseTo(13.435028842544403);
expect(result.edge).toBe(0);
expect(polygon[result.edge][0]).toBe(1);
expect(polygon[result.edge][1]).toBe(0);
expect(ear.math.nearestPointOnPolygon(polygon, [-10, 10]).edge).toBe(1);
expect(ear.math.nearestPointOnPolygon(polygon, [-10, -10]).edge).toBe(2);
expect(ear.math.nearestPointOnPolygon(polygon, [10, -10]).edge).toBe(3);
});
test("nearestPointOnPolygon nearest to vertex", () => {
const polygon = [[1, 0], [0, 1], [-1, 0], [0, -1]];
const result1 = ear.math.nearestPointOnPolygon(polygon, [10, 0]);
const result2 = ear.math.nearestPointOnPolygon(polygon, [0, 10]);
const result3 = ear.math.nearestPointOnPolygon(polygon, [-10, 0]);
const result4 = ear.math.nearestPointOnPolygon(polygon, [0, -10]);
expect(result1.point[0]).toBe(1);
expect(result1.point[1]).toBe(0);
expect(result2.point[0]).toBe(0);
expect(result2.point[1]).toBe(1);
expect(result3.point[0]).toBe(-1);
expect(result3.point[1]).toBe(0);
expect(result4.point[0]).toBe(0);
expect(result4.point[1]).toBe(-1);
expect(result1.edge).toBe(0);
expect(result2.edge).toBe(0);
expect(result3.edge).toBe(1);
expect(result4.edge).toBe(2);
});
test("nearestPointOnCircle", () => {
const circle = { radius: 1, origin: [0, 0] };
const result1 = ear.math.nearestPointOnCircle(circle, [10, 0]);
const result2 = ear.math.nearestPointOnCircle(circle, [0, 10]);
const result3 = ear.math.nearestPointOnCircle(circle, [-10, 0]);
const result4 = ear.math.nearestPointOnCircle(circle, [0, -10]);
const result5 = ear.math.nearestPointOnCircle(circle, [10, 10]);
const result6 = ear.math.nearestPointOnCircle(circle, [-10, 10]);
const result7 = ear.math.nearestPointOnCircle(circle, [-10, -10]);
const result8 = ear.math.nearestPointOnCircle(circle, [10, -10]);
expect(result1[0]).toBeCloseTo(1);
expect(result1[1]).toBeCloseTo(0);
expect(result2[0]).toBeCloseTo(0);
expect(result2[1]).toBeCloseTo(1);
expect(result3[0]).toBeCloseTo(-1);
expect(result3[1]).toBeCloseTo(0);
expect(result4[0]).toBeCloseTo(0);
expect(result4[1]).toBeCloseTo(-1);
expect(result5[0]).toBeCloseTo(Math.SQRT1_2);
expect(result5[1]).toBeCloseTo(Math.SQRT1_2);
expect(result6[0]).toBeCloseTo(-Math.SQRT1_2);
expect(result6[1]).toBeCloseTo(Math.SQRT1_2);
expect(result7[0]).toBeCloseTo(-Math.SQRT1_2);
expect(result7[1]).toBeCloseTo(-Math.SQRT1_2);
expect(result8[0]).toBeCloseTo(Math.SQRT1_2);
expect(result8[1]).toBeCloseTo(-Math.SQRT1_2);
});
================================================
FILE: tests/math.geometry.polygon.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
const testEqualVectorVectors = function (a, b) {
expect(a.length).toBe(b.length);
a.forEach((_, i) => expect(ear.math.epsilonEqualVectors(a[i], b[i]))
.toBe(true));
};
test("signedArea", () => {
expect(ear.math.signedArea([[1, 0], [0, 1], [-1, 0], [0, -1]])).toBeCloseTo(2);
expect(ear.math.signedArea([[1, 0], [0, 1], [-1, 0]])).toBeCloseTo(1);
});
test("centroid", () => {
expect(ear.math.centroid([[1, 0], [0, 1], [-1, 0], [0, -1]])[0]).toBeCloseTo(0);
expect(ear.math.centroid([[1, 0], [0, 1], [-1, 0], [0, -1]])[1]).toBeCloseTo(0);
expect(ear.math.centroid([[1, 0], [0, 1], [-1, 0]])[0]).toBeCloseTo(0);
expect(ear.math.centroid([[1, 0], [0, 1], [-1, 0]])[1]).toBeCloseTo(1 / 3);
});
test("boundingBox", () => {
const box = ear.math.boundingBox([[1, 0], [0, 1], [-1, 0], [0, -1]]);
expect(box.min[0]).toBe(-1);
expect(box.min[1]).toBe(-1);
expect(box.span[0]).toBe(2);
expect(box.span[1]).toBe(2);
const badBox = ear.math.boundingBox();
expect(badBox).toBe(undefined);
});
test("makePolygonCircumradius", () => {
expect(ear.math.makePolygonCircumradius().length).toBe(3);
const vert_square = ear.math.makePolygonCircumradius(4);
expect(vert_square[0][0]).toBe(1);
expect(vert_square[0][1]).toBe(0);
const vert_square_2 = ear.math.makePolygonCircumradius(4, 2);
expect(vert_square_2[0][0]).toBe(2);
expect(vert_square_2[0][1]).toBe(0);
const tri1 = ear.math.makePolygonCircumradius(3);
const tri2 = ear.math.makePolygonCircumradius(3, 2);
// first coord (1,0)
expect(tri1[0][0]).toBeCloseTo(1);
expect(tri1[0][1]).toBeCloseTo(0);
expect(tri1[1][0]).toBeCloseTo(-0.5);
expect(tri1[1][1]).toBeCloseTo(Math.sqrt(3) / 2);
expect(tri1[2][0]).toBeCloseTo(-0.5);
expect(tri1[2][1]).toBeCloseTo(-Math.sqrt(3) / 2);
// 2
expect(tri2[0][0]).toBeCloseTo(2);
expect(tri2[1][0]).toBeCloseTo(-1);
});
test("make regular polygon side aligned", () => {
const tri = ear.math.makePolygonCircumradiusSide();
expect(tri.length).toBe(3);
const square = ear.math.makePolygonCircumradiusSide(4);
expect(square[0][0]).toBeCloseTo(Math.sqrt(2) / 2);
const square2 = ear.math.makePolygonCircumradiusSide(4, 2);
expect(square2[0][0]).toBeCloseTo(Math.sqrt(2));
});
test("make regular polygon inradius", () => {
const tri = ear.math.makePolygonInradius();
expect(tri.length).toBe(3);
const square = ear.math.makePolygonInradius(4);
expect(square[0][0]).toBeCloseTo(Math.sqrt(2));
expect(square[0][1]).toBeCloseTo(0);
});
test("make_polygon_inradius_s", () => {
const tri = ear.math.makePolygonInradiusSide();
expect(tri.length).toBe(3);
const square = ear.math.makePolygonInradiusSide(4);
expect(square[0][0]).toBeCloseTo(1);
const square2 = ear.math.makePolygonInradiusSide(4, 2);
expect(square2[0][0]).toBeCloseTo(2);
});
test("make_polygon_side_length", () => {
const tri = ear.math.makePolygonSideLength();
expect(tri.length).toBe(3);
const square = ear.math.makePolygonSideLength(4);
expect(square[0][0]).toBeCloseTo(Math.sqrt(2) / 2);
expect(square[0][1]).toBeCloseTo(0);
const square2 = ear.math.makePolygonSideLength(4, 2);
expect(square2[0][0]).toBeCloseTo(Math.sqrt(2));
expect(square2[0][1]).toBeCloseTo(0);
});
test("make_polygon_side_length_s", () => {
const tri = ear.math.makePolygonSideLengthSide();
expect(tri.length).toBe(3);
const square = ear.math.makePolygonSideLengthSide(4);
expect(square[0][0]).toBeCloseTo(0.5);
const square2 = ear.math.makePolygonSideLengthSide(4, 2);
expect(square2[0][0]).toBeCloseTo(1);
});
test("makePolygonNonCollinear", () => {
const polygon = [[0, 0], [1, 0], [2, 0], [2, 2], [0, 2]];
const result = ear.math.makePolygonNonCollinear(polygon);
testEqualVectorVectors(
[[0, 0], [2, 0], [2, 2], [0, 2]],
result,
);
});
================================================
FILE: tests/math.geometry.radial.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
const testEqualVectors = function (...args) {
expect(ear.math.epsilonEqualVectors(...args)).toBe(true);
};
test("isCounterClockwiseBetween", () => {
expect(ear.math.isCounterClockwiseBetween(0.5, 0, 1)).toBe(true);
expect(ear.math.isCounterClockwiseBetween(0.5, 1, 0)).toBe(false);
expect(ear.math.isCounterClockwiseBetween(11, 10, 12)).toBe(true);
expect(ear.math.isCounterClockwiseBetween(11, 12, 10)).toBe(false);
expect(ear.math.isCounterClockwiseBetween(
Math.PI * (2 * 4) + Math.PI / 2,
0,
Math.PI,
)).toBe(true);
expect(ear.math.isCounterClockwiseBetween(
Math.PI * (2 * 4) + Math.PI / 2,
Math.PI,
0,
)).toBe(false);
});
test("interior angles", () => {
testEqualVectors(
[Math.PI / 2, Math.PI / 2, Math.PI / 2, Math.PI / 2],
[[1, 0], [0, 1], [-1, 0], [0, -1]]
.map((v, i, ar) => ear.math.counterClockwiseAngle2(v, ar[(i + 1) % ar.length])),
);
testEqualVectors(
[Math.PI / 2, Math.PI / 2, Math.PI / 2, Math.PI / 2],
[[1, 1], [-1, 1], [-1, -1], [1, -1]]
.map((v, i, ar) => ear.math.counterClockwiseAngle2(v, ar[(i + 1) % ar.length])),
);
});
test("counter-clockwise vector sorting", () => {
testEqualVectors(
[0, 1, 2, 3],
ear.math.counterClockwiseOrder2([[1, 1], [-1, 1], [-1, -1], [1, -1]]),
);
testEqualVectors(
[0, 3, 2, 1],
ear.math.counterClockwiseOrder2([[1, -1], [-1, -1], [-1, 1], [1, 1]]),
);
});
// test("sectors", () => {
// testEqual(Math.PI / 2, ear.math.sector.fromVectors([1, 0], [0, 1]).angle);
// testEqual(true, ear.math.sector.fromVectors([1, 0], [0, 1]).contains([1, 1]));
// testEqual(false, ear.math.sector.fromVectors([1, 0], [0, 1]).contains([-1, 1]));
// testEqual(false, ear.math.sector.fromVectors([1, 0], [0, 1]).contains([-1, -1]));
// testEqual(false, ear.math.sector.fromVectors([1, 0], [0, 1]).contains([1, -1]));
// });
// test("junctions", () => {
// testEqual([[1, 1], [1, -1], [-1, 1], [-1, -1]],
// ear.math.junction([1, 1], [1, -1], [-1, 1], [-1, -1]).vectors);
// testEqual([0, 2, 3, 1],
// ear.math.junction([1, 1], [1, -1], [-1, 1], [-1, -1]).vectorOrder);
// testEqual([Math.PI / 2, Math.PI / 2, Math.PI / 2, Math.PI / 2],
// ear.math.junction([1, 1], [1, -1], [-1, 1], [-1, -1]).angles());
// });
test("clockwiseAngleRadians", () => {
expect(ear.math.clockwiseAngleRadians(Math.PI, Math.PI / 2))
.toBeCloseTo(Math.PI * (1 / 2));
expect(ear.math.clockwiseAngleRadians(Math.PI / 2, Math.PI))
.toBeCloseTo(Math.PI * (3 / 2));
// same as above with negative numbers
expect(ear.math.clockwiseAngleRadians(
Math.PI + Math.PI * (2 * 4),
Math.PI / 2 - Math.PI * (2 * 8),
)).toBeCloseTo(Math.PI * (1 / 2));
expect(ear.math.clockwiseAngleRadians(
Math.PI / 2 - Math.PI * (2 * 3),
Math.PI + Math.PI * (2 * 4),
)).toBeCloseTo(Math.PI * (3 / 2));
expect(ear.math.clockwiseAngleRadians(
Math.PI - Math.PI * (2 * 4),
Math.PI / 2 - Math.PI * (2 * 8),
)).toBeCloseTo(Math.PI * (1 / 2));
expect(ear.math.clockwiseAngleRadians(
Math.PI / 2 - Math.PI * (2 * 3),
Math.PI - Math.PI * (2 * 4),
)).toBeCloseTo(Math.PI * (3 / 2));
});
test("counterClockwiseAngleRadians", () => {
expect(ear.math.counterClockwiseAngleRadians(Math.PI, Math.PI / 2))
.toBeCloseTo(Math.PI * (3 / 2));
expect(ear.math.counterClockwiseAngleRadians(Math.PI / 2, Math.PI))
.toBeCloseTo(Math.PI * (1 / 2));
// same as above with negative numbers
expect(ear.math.counterClockwiseAngleRadians(
Math.PI - Math.PI * (2 * 4),
Math.PI / 2 - Math.PI * (2 * 5),
)).toBeCloseTo(Math.PI * (3 / 2));
expect(ear.math.counterClockwiseAngleRadians(
Math.PI + Math.PI * (2 * 4),
Math.PI / 2 + Math.PI * (2 * 5),
)).toBeCloseTo(Math.PI * (3 / 2));
expect(ear.math.counterClockwiseAngleRadians(
Math.PI / 2 - Math.PI * (2 * 7),
Math.PI - Math.PI * (2 * 3),
)).toBeCloseTo(Math.PI * (1 / 2));
});
test("clockwiseAngle2", () => {
expect(ear.math.clockwiseAngle2([1, 0], [0, 1])).toBeCloseTo(Math.PI * (3 / 2));
expect(ear.math.clockwiseAngle2([0, 1], [1, 0])).toBeCloseTo(Math.PI * (1 / 2));
});
test("counterClockwiseAngle2", () => {
expect(ear.math.counterClockwiseAngle2([1, 0], [0, 1]))
.toBeCloseTo(Math.PI * (1 / 2));
expect(ear.math.counterClockwiseAngle2([0, 1], [1, 0]))
.toBeCloseTo(Math.PI * (3 / 2));
});
// test("counter_clockwise_vector_order", () => {
// ear.math.counter_clockwise_vector_order(...vectors)
// });
test("interior sector angles", () => {
expect(ear.math.counterClockwiseSectors2([[1, 0], [0, 1], [-1, 0]])[0])
.toBeCloseTo(Math.PI / 2);
expect(ear.math.counterClockwiseSectors2([[1, 0], [0, 1], [-1, 0]])[1])
.toBeCloseTo(Math.PI / 2);
expect(ear.math.counterClockwiseSectors2([[1, 0], [0, 1], [-1, 0]])[2])
.toBeCloseTo(Math.PI);
expect(ear.math.counterClockwiseSectors2([[1, 0], [-1, 0], [0, -1]])[0])
.toBeCloseTo(Math.PI);
expect(ear.math.counterClockwiseSectors2([[1, 0], [-1, 0], [0, -1]])[1])
.toBeCloseTo(Math.PI / 2);
expect(ear.math.counterClockwiseSectors2([[1, 0], [-1, 0], [0, -1]])[2])
.toBeCloseTo(Math.PI / 2);
});
test("clockwise bisect", () => {
expect(ear.math.clockwiseBisect2([1, 0], [0, -1])[0]).toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.clockwiseBisect2([1, 0], [0, -1])[1]).toBeCloseTo(-Math.sqrt(2) / 2);
expect(ear.math.clockwiseBisect2([1, 0], [-1, 0])[0]).toBeCloseTo(0);
expect(ear.math.clockwiseBisect2([1, 0], [-1, 0])[1]).toBeCloseTo(-1);
expect(ear.math.clockwiseBisect2([1, 0], [0, 1])[0]).toBeCloseTo(-Math.sqrt(2) / 2);
expect(ear.math.clockwiseBisect2([1, 0], [0, 1])[1]).toBeCloseTo(-Math.sqrt(2) / 2);
expect(ear.math.clockwiseBisect2([1, 0], [1, 0])[0]).toBeCloseTo(1);
expect(ear.math.clockwiseBisect2([1, 0], [1, 0])[1]).toBeCloseTo(0);
});
test("counter-clockwise bisect", () => {
expect(ear.math.counterClockwiseBisect2([1, 0], [0, 1])[0]).toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.counterClockwiseBisect2([1, 0], [0, 1])[1]).toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.counterClockwiseBisect2([1, 0], [-1, 0])[0]).toBeCloseTo(0);
expect(ear.math.counterClockwiseBisect2([1, 0], [-1, 0])[1]).toBeCloseTo(1);
expect(ear.math.counterClockwiseBisect2([1, 0], [0, -1])[0]).toBeCloseTo(-Math.sqrt(2) / 2);
expect(ear.math.counterClockwiseBisect2([1, 0], [0, -1])[1]).toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.counterClockwiseBisect2([1, 0], [1, 0])[0]).toBeCloseTo(1);
expect(ear.math.counterClockwiseBisect2([1, 0], [1, 0])[1]).toBeCloseTo(0);
});
test("counterClockwiseBisect2", () => {
expect(ear.math.counterClockwiseBisect2([1, 0], [0, 1])[0])
.toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.counterClockwiseBisect2([1, 0], [0, 1])[1])
.toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.counterClockwiseBisect2([0, 1], [-1, 0])[0])
.toBeCloseTo(-Math.sqrt(2) / 2);
expect(ear.math.counterClockwiseBisect2([0, 1], [-1, 0])[1])
.toBeCloseTo(Math.sqrt(2) / 2);
// flipped vectors
expect(ear.math.counterClockwiseBisect2([1, 0], [-1, 0])[0]).toBeCloseTo(0);
expect(ear.math.counterClockwiseBisect2([1, 0], [-1, 0])[1]).toBeCloseTo(1);
});
test("bisectLines2", () => {
expect(ear.math.bisectLines2(
{ vector: [0, 1], origin: [0, 0] },
{ vector: [0, 1], origin: [1, 0] },
)[1])
.toBe(undefined);
expect(ear.math.bisectLines2(
{ vector: [0, 1], origin: [0, 0] },
{ vector: [0, 1], origin: [1, 0] },
)[0].vector[0])
.toBeCloseTo(0);
expect(ear.math.bisectLines2(
{ vector: [0, 1], origin: [0, 0] },
{ vector: [0, 1], origin: [1, 0] },
)[0].vector[1])
.toBeCloseTo(1);
expect(ear.math.bisectLines2(
{ vector: [0, 1], origin: [0, 0] },
{ vector: [0, 1], origin: [1, 0] },
)[0].origin[0])
.toBeCloseTo(0.5);
expect(ear.math.bisectLines2(
{ vector: [0, 1], origin: [0, 0] },
{ vector: [0, 1], origin: [1, 0] },
)[0].origin[1])
.toBeCloseTo(0);
expect(ear.math.bisectLines2(
{ vector: [0, 1], origin: [0, 0] },
{ vector: [1, 1], origin: [1, 0] },
)[0].vector[0])
.toBeCloseTo(0.3826834323650897);
expect(ear.math.bisectLines2(
{ vector: [0, 1], origin: [0, 0] },
{ vector: [1, 1], origin: [1, 0] },
)[0].vector[1])
.toBeCloseTo(0.9238795325112867);
expect(ear.math.bisectLines2(
{ vector: [0, 1], origin: [0, 0] },
{ vector: [1, 1], origin: [1, 0] },
)[0].origin[0])
.toBeCloseTo(0);
expect(ear.math.bisectLines2(
{ vector: [0, 1], origin: [0, 0] },
{ vector: [1, 1], origin: [1, 0] },
)[0].origin[1])
.toBeCloseTo(-1);
});
test("counterClockwiseSubsectRadians", () => {
testEqualVectors(
ear.math.counterClockwiseSubsectRadians(0, 3, 3),
[1, 2],
);
testEqualVectors(
ear.math.counterClockwiseSubsectRadians(-1, 2, 3),
[0, 1],
);
expect(ear.math.counterClockwiseSubsectRadians(0, -Math.PI, 4)[0])
.toBeCloseTo(Math.PI * (1 / 4));
expect(ear.math.counterClockwiseSubsectRadians(0, -Math.PI, 4)[1])
.toBeCloseTo(Math.PI * (2 / 4));
expect(ear.math.counterClockwiseSubsectRadians(0, -Math.PI, 4)[2])
.toBeCloseTo(Math.PI * (3 / 4));
expect(ear.math.counterClockwiseSubsectRadians(0, -Math.PI, 2)[0])
.toBeCloseTo(Math.PI / 2);
expect(ear.math.counterClockwiseSubsectRadians(0, -Math.PI, 1).length)
.toBe(0);
});
test("counterClockwiseSubsect2", () => {
expect(ear.math.counterClockwiseSubsect2([1, 0], [0, 1], 2)[0][0])
.toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.counterClockwiseSubsect2([1, 0], [0, 1], 2)[0][1])
.toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.counterClockwiseSubsect2([1, 0], [-1, 0], 4)[0][0])
.toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.counterClockwiseSubsect2([1, 0], [-1, 0], 4)[0][1])
.toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.counterClockwiseSubsect2([1, 0], [-1, 0], 4)[1][0])
.toBeCloseTo(0);
expect(ear.math.counterClockwiseSubsect2([1, 0], [-1, 0], 4)[1][1])
.toBeCloseTo(1);
expect(ear.math.counterClockwiseSubsect2([1, 0], [-1, 0], 4)[2][0])
.toBeCloseTo(-Math.sqrt(2) / 2);
expect(ear.math.counterClockwiseSubsect2([1, 0], [-1, 0], 4)[2][1])
.toBeCloseTo(Math.sqrt(2) / 2);
});
test("clockwiseSubsectRadians", () => {
testEqualVectors(ear.math.clockwiseSubsectRadians(3, 0, 3), [4, 5]);
testEqualVectors(ear.math.clockwiseSubsectRadians(2, -1, 3), [3, 4]);
testEqualVectors(ear.math.clockwiseSubsectRadians(2, -2, 4), [3, 4, 5]);
expect(ear.math.clockwiseSubsectRadians(-Math.PI, 0, 4)[0])
.toBeCloseTo(-Math.PI * (3 / 4));
expect(ear.math.clockwiseSubsectRadians(-Math.PI, 0, 4)[1])
.toBeCloseTo(-Math.PI * (2 / 4));
expect(ear.math.clockwiseSubsectRadians(-Math.PI, 0, 4)[2])
.toBeCloseTo(-Math.PI * (1 / 4));
expect(ear.math.clockwiseSubsectRadians(-Math.PI, 0, 2)[0])
.toBeCloseTo(-Math.PI / 2);
expect(ear.math.clockwiseSubsectRadians(-Math.PI, 0, 1).length)
.toBe(0);
});
test("clockwiseSubsect2", () => {
expect(ear.math.clockwiseSubsect2([0, 1], [1, 0], 2)[0][0])
.toBeCloseTo(-Math.sqrt(2) / 2);
expect(ear.math.clockwiseSubsect2([0, 1], [1, 0], 2)[0][1])
.toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.clockwiseSubsect2([-1, 0], [1, 0], 4)[0][0])
.toBeCloseTo(-Math.sqrt(2) / 2);
expect(ear.math.clockwiseSubsect2([-1, 0], [1, 0], 4)[0][1])
.toBeCloseTo(-Math.sqrt(2) / 2);
expect(ear.math.clockwiseSubsect2([-1, 0], [1, 0], 4)[1][0])
.toBeCloseTo(0);
expect(ear.math.clockwiseSubsect2([-1, 0], [1, 0], 4)[1][1])
.toBeCloseTo(-1);
expect(ear.math.clockwiseSubsect2([-1, 0], [1, 0], 4)[2][0])
.toBeCloseTo(Math.sqrt(2) / 2);
expect(ear.math.clockwiseSubsect2([-1, 0], [1, 0], 4)[2][1])
.toBeCloseTo(-Math.sqrt(2) / 2);
});
test("threePointTurnDirection", () => {
expect(ear.math.threePointTurnDirection([0, 0], [1, 0], [2, 0])).toBe(0);
expect(ear.math.threePointTurnDirection([0, 0], [1, 0], [2, 1])).toBe(1);
expect(ear.math.threePointTurnDirection([0, 0], [1, 0], [2, -1])).toBe(-1);
// with epsilon
expect(ear.math.threePointTurnDirection([0, 0], [1, 0], [2, 0.000001], 0.001)).toBe(0);
expect(ear.math.threePointTurnDirection([0, 0], [1, 0], [2, 0.001], 0.000001)).toBe(1);
expect(ear.math.threePointTurnDirection([0, 0], [1, 0], [2, -0.000001], 0.001)).toBe(0);
expect(ear.math.threePointTurnDirection([0, 0], [1, 0], [2, -0.001], 0.000001)).toBe(-1);
// 180 degree turn
expect(ear.math.threePointTurnDirection([0, 0], [2, 0], [1, 0])).toBe(undefined);
expect(ear.math.threePointTurnDirection([0, 0], [5, 5], [2, 2])).toBe(undefined);
expect(ear.math.threePointTurnDirection([0, 0], [5, 0], [0, 0])).toBe(undefined);
expect(ear.math.threePointTurnDirection([0, 0], [1, 0], [-1, 0])).toBe(undefined);
});
================================================
FILE: tests/math.geometry.straightSkeleton.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("straight skeleton triangle", () => {
const f1f = Math.sqrt(2) - 1;
const skeleton = ear.math.straightSkeleton([[1, 0], [0, 1], [-1, 0]]);
expect(skeleton.length).toBe(4);
["skeleton", "skeleton", "skeleton", "perpendicular"]
.forEach((key, i) => expect(skeleton[i].type).toBe(key));
[[1, 0], [0, f1f]].forEach((pt, i) => ear.math.epsilonEqualVectors(
pt,
skeleton[0].points[i],
));
[[0, 1], [0, f1f]].forEach((pt, i) => ear.math.epsilonEqualVectors(
pt,
skeleton[1].points[i],
));
[[-1, 0], [0, f1f]].forEach((pt, i) => ear.math.epsilonEqualVectors(
pt,
skeleton[2].points[i],
));
});
test("straight skeleton quad", () => {
const skeleton = ear.math.straightSkeleton([[0, 0], [2, 0], [2, 1], [0, 1]]);
expect(skeleton.length).toBe(7);
// const points = skeleton.map(el => el.points);
const keys = ["skeleton", "perpendicular"];
[0, 0, 1, 0, 0, 0, 1].forEach((n, i) => expect(skeleton[i].type).toBe(keys[n]));
});
================================================
FILE: tests/math.geometry.triangle.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("circumcircle", () => {
const circle = ear.math.circumcircle([1, 0], [0, 1], [-1, 0]);
expect(circle.origin[0]).toBeCloseTo(0);
expect(circle.origin[1]).toBeCloseTo(0);
expect(circle.radius).toBeCloseTo(1);
// todo, this is the degenerate case. not sure why the result is such
const circle2 = ear.math.circumcircle([1, 0], [0, 0], [-1, 0]);
expect(circle2.origin[0]).toBeCloseTo(0);
expect(circle2.origin[1]).toBeCloseTo(0);
expect(circle2.radius).toBeCloseTo(1);
});
================================================
FILE: tests/math.intersect.clip.line.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
// const {
// exclude,
// include,
// includeL,
// excludeL,
// includeR,
// excludeR,
// includeS,
// excludeS,
// } = math;
const clip_line_in_convex_poly_inclusive = function () {
return ear.math.clipLineConvexPolygon(
...arguments,
ear.math.include,
ear.math.includeL,
);
};
const clip_line_in_convex_poly_exclusive = function () {
return ear.math.clipLineConvexPolygon(
...arguments,
ear.math.exclude,
ear.math.excludeL,
);
};
const clip_ray_in_convex_poly_inclusive = function () {
return ear.math.clipLineConvexPolygon(
...arguments,
ear.math.include,
ear.math.includeR,
);
};
const clip_ray_in_convex_poly_exclusive = function () {
return ear.math.clipLineConvexPolygon(
...arguments,
ear.math.exclude,
ear.math.excludeR,
);
};
const clip_segment_in_convex_poly_inclusive = function (poly, s0, s1) {
const vector = [s1[0] - s0[0], s1[1] - s0[1]];
return ear.math.clipLineConvexPolygon(
poly,
{ vector, origin: s0 },
ear.math.include,
ear.math.includeS,
);
};
const clip_segment_in_convex_poly_exclusive = function (poly, s0, s1) {
const vector = [s1[0] - s0[0], s1[1] - s0[1]];
return ear.math.clipLineConvexPolygon(
poly,
{ vector, origin: s0 },
ear.math.exclude,
ear.math.excludeS,
);
};
test("collinear line", () => {
// all inclusive cases will return a segment with unique endpoints
// all exclusive cases will return undefined
const rect = [[0, 0], [1, 0], [1, 1], [0, 1]];
const lineHoriz1 = { vector: [1, 0], origin: [0.5, 0] };
const lineHoriz2 = { vector: [1, 0], origin: [0.5, 1] };
const lineVert1 = { vector: [0, 1], origin: [0, 0.5] };
const lineVert2 = { vector: [0, 1], origin: [1, 0.5] };
const result1 = ear.math.clipLineConvexPolygon(
rect,
lineHoriz1,
ear.math.include,
ear.math.includeL,
);
const result2 = ear.math.clipLineConvexPolygon(
rect,
lineHoriz2,
ear.math.include,
ear.math.includeL,
);
const result3 = ear.math.clipLineConvexPolygon(
rect,
lineVert1,
ear.math.include,
ear.math.includeL,
);
const result4 = ear.math.clipLineConvexPolygon(
rect,
lineVert2,
ear.math.include,
ear.math.includeL,
);
const result5 = ear.math.clipLineConvexPolygon(
rect,
lineHoriz1,
ear.math.exclude,
ear.math.excludeL,
);
const result6 = ear.math.clipLineConvexPolygon(
rect,
lineHoriz2,
ear.math.exclude,
ear.math.excludeL,
);
const result7 = ear.math.clipLineConvexPolygon(
rect,
lineVert1,
ear.math.exclude,
ear.math.excludeL,
);
const result8 = ear.math.clipLineConvexPolygon(
rect,
lineVert2,
ear.math.exclude,
ear.math.excludeL,
);
expect(result1.length).toBe(2);
expect(result2.length).toBe(2);
expect(result3.length).toBe(2);
expect(result4.length).toBe(2);
expect(result5).toBe(undefined);
expect(result6).toBe(undefined);
expect(result7).toBe(undefined);
expect(result8).toBe(undefined);
expect(JSON.stringify(result1[0])).not.toBe(JSON.stringify(result1[1]));
expect(JSON.stringify(result2[0])).not.toBe(JSON.stringify(result2[1]));
expect(JSON.stringify(result3[0])).not.toBe(JSON.stringify(result3[1]));
expect(JSON.stringify(result4[0])).not.toBe(JSON.stringify(result4[1]));
});
test("vertex-incident line", () => {
// all cases will return undefined
const quad = [[1, 0], [0, 1], [-1, 0], [0, -1]];
const lineHoriz1 = { vector: [1, 0], origin: [-1, 1] };
const lineHoriz2 = { vector: [1, 0], origin: [-1, -1] };
const lineVert1 = { vector: [0, 1], origin: [-1, -1] };
const lineVert2 = { vector: [0, 1], origin: [1, -1] };
const results = [
ear.math.clipLineConvexPolygon(quad, lineHoriz1, ear.math.include, ear.math.includeL),
ear.math.clipLineConvexPolygon(quad, lineHoriz2, ear.math.include, ear.math.includeL),
ear.math.clipLineConvexPolygon(quad, lineVert1, ear.math.include, ear.math.includeL),
ear.math.clipLineConvexPolygon(quad, lineVert2, ear.math.include, ear.math.includeL),
ear.math.clipLineConvexPolygon(quad, lineHoriz1, ear.math.exclude, ear.math.excludeL),
ear.math.clipLineConvexPolygon(quad, lineHoriz2, ear.math.exclude, ear.math.excludeL),
ear.math.clipLineConvexPolygon(quad, lineVert1, ear.math.exclude, ear.math.excludeL),
ear.math.clipLineConvexPolygon(quad, lineVert2, ear.math.exclude, ear.math.excludeL),
];
results.forEach(res => expect(res).toBe(undefined));
});
test("collinear core, segment", () => {
const rect = [[0, 0], [1, 0], [1, 1], [0, 1]];
const segHoriz1 = { vector: [1, 0], origin: [0.5, 0] };
const segHoriz2 = { vector: [1, 0], origin: [-0.5, 0] };
const segVert1 = { vector: [0, 1], origin: [0, 0.5] };
const segVert2 = { vector: [0, 1], origin: [1, 0.5] };
const result1 = ear.math.clipLineConvexPolygon(rect, segHoriz1, ear.math.include, ear.math.includeS);
const result2 = ear.math.clipLineConvexPolygon(rect, segHoriz2, ear.math.include, ear.math.includeS);
const result3 = ear.math.clipLineConvexPolygon(rect, segVert1, ear.math.include, ear.math.includeS);
const result4 = ear.math.clipLineConvexPolygon(rect, segVert2, ear.math.include, ear.math.includeS);
const result5 = ear.math.clipLineConvexPolygon(rect, segHoriz1, ear.math.exclude, ear.math.excludeS);
const result6 = ear.math.clipLineConvexPolygon(rect, segHoriz2, ear.math.exclude, ear.math.excludeS);
const result7 = ear.math.clipLineConvexPolygon(rect, segVert1, ear.math.exclude, ear.math.excludeS);
const result8 = ear.math.clipLineConvexPolygon(rect, segVert2, ear.math.exclude, ear.math.excludeS);
expect(result1.length).toBe(2);
expect(result2.length).toBe(2);
expect(result3.length).toBe(2);
expect(result4.length).toBe(2);
expect(result5).toBe(undefined);
expect(result6).toBe(undefined);
expect(result7).toBe(undefined);
expect(result8).toBe(undefined);
expect(JSON.stringify(result1[0])).not.toBe(JSON.stringify(result1[1]));
expect(JSON.stringify(result2[0])).not.toBe(JSON.stringify(result2[1]));
expect(JSON.stringify(result3[0])).not.toBe(JSON.stringify(result3[1]));
expect(JSON.stringify(result4[0])).not.toBe(JSON.stringify(result4[1]));
expect(result1[0][0]).toBe(0.5);
expect(result1[0][1]).toBe(0);
expect(result1[1][0]).toBe(1);
expect(result1[1][1]).toBe(0);
expect(result2[0][0]).toBe(0);
expect(result2[0][1]).toBe(0);
expect(result2[1][0]).toBe(0.5);
expect(result2[1][1]).toBe(0);
// remember these are VECTORS, ORIGIN
const segHoriz3 = { vector: [0.5, 0], origin: [0.25, 0] };
const segVert3 = { vector: [0, 2], origin: [0, -0.5] };
const result9 = ear.math.clipLineConvexPolygon(rect, segHoriz3, ear.math.include, ear.math.includeS);
const result10 = ear.math.clipLineConvexPolygon(rect, segVert3, ear.math.include, ear.math.includeS);
const result11 = ear.math.clipLineConvexPolygon(rect, segHoriz3, ear.math.exclude, ear.math.excludeS);
const result12 = ear.math.clipLineConvexPolygon(rect, segVert3, ear.math.exclude, ear.math.excludeS);
expect(result9[0][0]).toBe(0.25);
expect(result9[0][1]).toBe(0);
expect(result9[1][0]).toBe(0.75);
expect(result9[1][1]).toBe(0);
expect(result10[0][0]).toBe(0);
expect(result10[0][1]).toBe(0);
expect(result10[1][0]).toBe(0);
expect(result10[1][1]).toBe(1);
});
test("vertex-incident segment", () => {
// all cases will return undefined
const quad = [[1, 0], [0, 1], [-1, 0], [0, -1]];
const horiz1 = { vector: [1, 0], origin: [-1, 1] };
const horiz2 = { vector: [1, 0], origin: [-1, -1] };
const vert1 = { vector: [0, 1], origin: [-1, -1] };
const vert2 = { vector: [0, 1], origin: [1, -1] };
const results = [
ear.math.clipLineConvexPolygon(quad, horiz1, ear.math.include, ear.math.includeS),
ear.math.clipLineConvexPolygon(quad, horiz2, ear.math.include, ear.math.includeS),
ear.math.clipLineConvexPolygon(quad, vert1, ear.math.include, ear.math.includeS),
ear.math.clipLineConvexPolygon(quad, vert2, ear.math.include, ear.math.includeS),
ear.math.clipLineConvexPolygon(quad, horiz1, ear.math.exclude, ear.math.excludeS),
ear.math.clipLineConvexPolygon(quad, horiz2, ear.math.exclude, ear.math.excludeS),
ear.math.clipLineConvexPolygon(quad, vert1, ear.math.exclude, ear.math.excludeS),
ear.math.clipLineConvexPolygon(quad, vert2, ear.math.exclude, ear.math.excludeS),
];
results.forEach(res => expect(res).toBe(undefined));
});
test("collinear core, ray", () => {
const rect = [[0, 0], [1, 0], [1, 1], [0, 1]];
const rayHoriz1 = { vector: [1, 0], origin: [0.5, 0] };
const rayHoriz2 = { vector: [1, 0], origin: [0.5, 1] };
const rayVert1 = { vector: [0, 1], origin: [0, 0.5] };
const rayVert2 = { vector: [0, 1], origin: [1, 0.5] };
const result1 = ear.math.clipLineConvexPolygon(rect, rayHoriz1, ear.math.include, ear.math.includeR);
const result2 = ear.math.clipLineConvexPolygon(rect, rayHoriz2, ear.math.include, ear.math.includeR);
const result3 = ear.math.clipLineConvexPolygon(rect, rayVert1, ear.math.include, ear.math.includeR);
const result4 = ear.math.clipLineConvexPolygon(rect, rayVert2, ear.math.include, ear.math.includeR);
const result5 = ear.math.clipLineConvexPolygon(rect, rayHoriz1, ear.math.exclude, ear.math.excludeR);
const result6 = ear.math.clipLineConvexPolygon(rect, rayHoriz2, ear.math.exclude, ear.math.excludeR);
const result7 = ear.math.clipLineConvexPolygon(rect, rayVert1, ear.math.exclude, ear.math.excludeR);
const result8 = ear.math.clipLineConvexPolygon(rect, rayVert2, ear.math.exclude, ear.math.excludeR);
expect(result1.length).toBe(2);
expect(result2.length).toBe(2);
expect(result3.length).toBe(2);
expect(result4.length).toBe(2);
expect(result5).toBe(undefined);
expect(result6).toBe(undefined);
expect(result7).toBe(undefined);
expect(result8).toBe(undefined);
expect(JSON.stringify(result1[0])).not.toBe(JSON.stringify(result1[1]));
expect(JSON.stringify(result2[0])).not.toBe(JSON.stringify(result2[1]));
expect(JSON.stringify(result3[0])).not.toBe(JSON.stringify(result3[1]));
expect(JSON.stringify(result4[0])).not.toBe(JSON.stringify(result4[1]));
});
test("vertex-incident ray", () => {
// all cases will return undefined
const quad = [[1, 0], [0, 1], [-1, 0], [0, -1]];
const horiz1 = { vector: [1, 0], origin: [-1, 1] };
const horiz2 = { vector: [1, 0], origin: [-1, -1] };
const vert1 = { vector: [0, 1], origin: [-1, -1] };
const vert2 = { vector: [0, 1], origin: [1, -1] };
const results = [
ear.math.clipLineConvexPolygon(quad, horiz1, ear.math.include, ear.math.includeR),
ear.math.clipLineConvexPolygon(quad, horiz2, ear.math.include, ear.math.includeR),
ear.math.clipLineConvexPolygon(quad, vert1, ear.math.include, ear.math.includeR),
ear.math.clipLineConvexPolygon(quad, vert2, ear.math.include, ear.math.includeR),
ear.math.clipLineConvexPolygon(quad, horiz1, ear.math.exclude, ear.math.excludeR),
ear.math.clipLineConvexPolygon(quad, horiz2, ear.math.exclude, ear.math.excludeR),
ear.math.clipLineConvexPolygon(quad, vert1, ear.math.exclude, ear.math.excludeR),
ear.math.clipLineConvexPolygon(quad, vert2, ear.math.exclude, ear.math.excludeR),
];
results.forEach(res => expect(res).toBe(undefined));
});
test("collinear core, segment", () => {
const rect = [[0, 0], [1, 0], [1, 1], [0, 1]];
const segHoriz1 = [[1, 0], [0.5, 0]];
const segHoriz2 = [[1, 0], [0.5, 1]];
const segVert1 = [[0, 1], [0, 0.5]];
const segVert2 = [[0, 1], [1, 0.5]];
const result1 = clip_segment_in_convex_poly_exclusive(rect, ...segHoriz1);
const result2 = clip_segment_in_convex_poly_exclusive(rect, ...segHoriz2);
const result3 = clip_segment_in_convex_poly_exclusive(rect, ...segVert1);
const result4 = clip_segment_in_convex_poly_exclusive(rect, ...segVert2);
});
test("collinear core, segment, spanning multiple points", () => {
const poly = [
[0, 0], [5, 0], [5, 1], [5, 2], [5, 3], [5, 4], [5, 5], [0, 5],
];
const seg = [[5, -1], [5, 6]];
const res = ear.math.clipLineConvexPolygon(
poly,
{ vector: ear.math.subtract(seg[1], seg[0]), origin: seg[0] },
ear.math.include,
ear.math.includeS,
);
expect(res[0][0]).toBe(5);
expect(res[0][1]).toBe(0);
expect(res[1][0]).toBe(5);
expect(res[1][1]).toBe(5);
});
test("collinear core, segment, spanning multiple points, inside", () => {
const poly = [
[0, 0], [5, 0], [5, 1], [5, 2], [5, 3], [5, 4], [5, 5], [0, 5],
];
const seg = [[5, 0.5], [5, 4.5]];
const res = clip_segment_in_convex_poly_inclusive(poly, ...seg);
expect(res[0][0]).toBe(5);
expect(res[0][1]).toBe(0.5);
expect(res[1][0]).toBe(5);
expect(res[1][1]).toBe(4.5);
});
================================================
FILE: tests/math.intersect.clip.polygon.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
const testEqualVectorVectors = function (a, b) {
expect(a.length).toBe(b.length);
a.forEach((_, i) => expect(ear.math.epsilonEqualVectors(a[i], b[i]))
.toBe(true));
};
test("clipPolygonPolygon edge adjacent non intersecting", () => {
const poly1 = [[0, 0], [1, 0], [1, 1], [0, 1]];
const poly2 = [[1, 0], [2, 0], [2, 1], [1, 1]];
const res1 = ear.math.clipPolygonPolygon(poly1, poly2);
const res2 = ear.math.clipPolygonPolygon(poly1, poly2, 0.1);
const res3 = ear.math.clipPolygonPolygon(poly1, poly2, -0.1);
expect(res1).toBe(undefined);
expect(res2).toBe(undefined);
expect(res3).not.toBe(undefined);
});
test("clipPolygonPolygon overlapping collinear edges, axis-aligned", () => {
const poly1 = [[0, 0], [2, 0], [2, 1], [0, 1]];
const poly2 = [[1, 0], [3, 0], [3, 1], [1, 1]];
const res1 = ear.math.clipPolygonPolygon(poly1, poly2);
testEqualVectorVectors(
res1,
[[1, 1], [1, 0], [2, 0], [2, 1]],
);
});
test("clipPolygonPolygon overlapping collinear edges, angled edges", () => {
const poly1 = [[2, 0], [0, 2], [-2, 0], [0, -2]];
const poly2 = [[1, -1], [3, 1], [1, 3], [-1, 1]];
const res1 = ear.math.clipPolygonPolygon(poly1, poly2);
testEqualVectorVectors(
res1,
[[-1, 1], [1, -1], [2, 0], [0, 2]],
);
});
test("clipPolygonPolygon enclosing polygons", () => {
const poly1 = [[0, 0], [10, 0], [10, 10], [0, 10]];
const poly2 = [[4, 4], [5, 4], [5, 5], [4, 5]];
const res1 = ear.math.clipPolygonPolygon(poly1, poly2);
const res2 = ear.math.clipPolygonPolygon(poly2, poly1);
testEqualVectorVectors([[4, 5], [4, 4], [5, 4], [5, 5]], res1);
testEqualVectorVectors([[4, 4], [5, 4], [5, 5], [4, 5]], res2);
});
test("clipPolygonPolygon same vertex, edge on vertex", () => {
// all vertices exist on top of each other
const poly1 = [[0, 0], [1, 0], [1, 1], [0, 1]];
const poly2 = [[1, 0], [1, 1], [0, 1]];
const res1 = ear.math.clipPolygonPolygon(poly1, poly2);
testEqualVectorVectors(
res1,
[[0, 1], [1, 0], [1, 1]],
);
const poly3 = [[3, -2], [3, 3], [-2, 3]];
const res2 = ear.math.clipPolygonPolygon(poly1, poly3);
testEqualVectorVectors(
res2,
[[1, 0], [1, 1], [0, 1]],
);
});
test("clipPolygonPolygon ensure input parameters did not modify", () => {
const poly1 = [[2, 0], [0, 2], [-2, 0], [0, -2]];
const poly2 = [[1, -1], [3, 1], [1, 3], [-1, 1]];
ear.math.clipPolygonPolygon(poly1, poly2);
ear.math.clipPolygonPolygon(poly2, poly1);
testEqualVectorVectors(
poly1,
[[2, 0], [0, 2], [-2, 0], [0, -2]],
);
testEqualVectorVectors(
poly2,
[[1, -1], [3, 1], [1, 3], [-1, 1]],
);
});
================================================
FILE: tests/math.intersect.encloses.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("enclosingBoundingBoxes fully enclosed", () => {
const box1 = { min: [0, 0], max: [1, 1] };
const box2 = { min: [0.25, 0.25], max: [0.75, 0.75] };
expect(ear.math.enclosingBoundingBoxes(box1, box2)).toBe(true);
});
test("enclosingBoundingBoxes edge collinear", () => {
const box1 = { min: [0, 0], max: [1, 1] };
const box2 = { min: [0, 0], max: [0.5, 0.5] };
expect(ear.math.enclosingBoundingBoxes(box1, box2)).toBe(true);
});
test("enclosingBoundingBoxes edge collinear epsilon", () => {
const box1 = { min: [0, 0], max: [1, 1] };
const box2 = { min: [0, 0], max: [0.5, 0.5] };
expect(ear.math.enclosingBoundingBoxes(box1, box2, -1e-4)).toBe(false);
expect(ear.math.enclosingBoundingBoxes(box1, box2, 1e-4)).toBe(true);
const box3 = { min: [-1e-3, -1e-3], max: [0.5, 0.5] };
expect(ear.math.enclosingBoundingBoxes(box1, box3, -1e-4)).toBe(false);
expect(ear.math.enclosingBoundingBoxes(box1, box3, 1e-4)).toBe(false);
expect(ear.math.enclosingBoundingBoxes(box1, box3, 1e-2)).toBe(true);
});
// enclosing polygon polygon is never used anywhere here or in
// Rabbit Ear so it's no longer included in the build.
// test("enclosingPolygonPolygon", () => {
// const poly1 = [[1, 0], [0, 1], [-1, 0], [0, -1]];
// const poly2 = [[10, 0], [0, 10], [-10, 0], [0, -10]];
// const poly3 = [[8, 8], [-8, 8], [-8, -8], [8, -8]];
// expect(ear.math.enclosingPolygonPolygon(poly2, poly1)).toBe(true);
// expect(ear.math.enclosingPolygonPolygon(poly3, poly1)).toBe(true);
// // todo, this should be false i think
// // expect(ear.math.enclosingPolygonPolygon(poly2, poly3)).toBe(false);
// expect(ear.math.enclosingPolygonPolygon(poly1, poly2)).toBe(false);
// expect(ear.math.enclosingPolygonPolygon(poly1, poly3)).toBe(false);
// });
================================================
FILE: tests/math.intersect.method.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("intersection method has been removed", () => expect(true).toBe(true));
// test("intersections", () => {
// const polygon = [[0, 1.15], [-1, -0.577], [1, -0.577]];
// const circle = { radius: 1, origin: [0, 0] };
// const line = { vector: [1, 2], origin: [0.5, 0] };
// const ray = { vector: [-1, 2], origin: [0.5, -0.1], domain: ear.math.excludeR };
// const segment = { vector: [4, 0], origin: [-2, 0.5], domain: ear.math.excludeS };
// const polygon2 = [[0, -1.15], [1, 0.577], [-1, 0.577]];
// const circle2 = { radius: 1, origin: [0.5, 0] };
// const line2 = { vector: [-1, 2], origin: [0.5, 0] };
// const ray2 = { vector: [1, 2], origin: [-0.5, 0], domain: ear.math.excludeR };
// const segment2 = { vector: [0, 4], origin: [0.5, -2], domain: ear.math.excludeS };
// [
// ear.math.intersect(polygon, line),
// ear.math.intersect(polygon, ray),
// ear.math.intersect(polygon, segment),
// ear.math.intersect(circle, circle2),
// ear.math.intersect(circle, line),
// ear.math.intersect(circle, ray),
// ear.math.intersect(circle, segment),
// ear.math.intersect(line, polygon),
// ear.math.intersect(line, circle),
// ear.math.intersect(line, line2),
// ear.math.intersect(line, ray),
// ear.math.intersect(line, segment),
// ear.math.intersect(ray, polygon),
// ear.math.intersect(ray, circle),
// ear.math.intersect(ray, line),
// ear.math.intersect(ray, ray2),
// ear.math.intersect(ray, segment),
// ear.math.intersect(segment, polygon),
// ear.math.intersect(segment, circle),
// ear.math.intersect(segment, line),
// ear.math.intersect(segment, ray),
// ear.math.intersect(segment, segment2),
// ].forEach(intersect => expect(intersect).not.toBeUndefined());
// // intersection between these types is not yet implemented
// [
// ear.math.intersect(polygon, polygon2),
// ear.math.intersect(polygon, circle),
// ear.math.intersect(circle, polygon),
// ].forEach(intersect => expect(intersect).toBeUndefined());
// });
// test("collinear segment intersections, types not core", () => {
// // horizontal
// const seg01 = ear.math.pointsToLine([0, 2], [2, 2]);
// const seg02 = ear.math.pointsToLine([-1, 2], [10, 2]);
// const seg03 = ear.math.pointsToLine([0, 2], [2, 2]);
// const seg04 = ear.math.pointsToLine([10, 2], [-1, 2]);
// // vertical
// const seg05 = ear.math.pointsToLine([2, 0], [2, 2]);
// const seg06 = ear.math.pointsToLine([2, -1], [2, 10]);
// const seg07 = ear.math.pointsToLine([2, 0], [2, 2]);
// const seg08 = ear.math.pointsToLine([2, 10], [2, -1]);
// // diagonal
// const seg09 = ear.math.pointsToLine([0, 0], [2, 2]);
// const seg10 = ear.math.pointsToLine([-1, -1], [5, 5]);
// const seg11 = ear.math.pointsToLine([0, 0], [2, 2]);
// const seg12 = ear.math.pointsToLine([5, 5], [-1, -1]);
// [seg01, seg02, seg03, seg04, seg05, seg06, seg07, seg08, seg09, seg10, seg11, seg12]
// .forEach(seg => { seg.domain = ear.math.excludeS; });
// [[seg01, seg02],
// [seg03, seg04],
// [seg05, seg06],
// [seg07, seg08],
// [seg09, seg10],
// [seg11, seg12],
// ].map(pair => ear.math.intersect(...pair))
// .forEach(res => expect(res.point).toBeUndefined());
// });
================================================
FILE: tests/math.intersect.overlap.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("overlapBoundingBoxes, point overlap", () => {
const box1 = { min: [0, 0], max: [1, 1] };
const box2 = { min: [0.9, 0.9], max: [2, 2] };
expect(ear.math.overlapBoundingBoxes(box1, box2)).toBe(true);
});
test("overlapBoundingBoxes, edge overlap", () => {
const box1 = { min: [0, 0], max: [1, 1] };
const box2 = { min: [1, 0], max: [2, 1] };
expect(ear.math.overlapBoundingBoxes(box1, box2)).toBe(true);
});
test("overlapBoundingBoxes, point overlap, epsilon away", () => {
const box1 = { min: [0, 0], max: [1, 1] };
const box2 = { min: [1 + 1e-2, 1 + 1e-2], max: [2, 2] };
expect(ear.math.overlapBoundingBoxes(box1, box2)).toBe(false);
});
test("overlapBoundingBoxes, edge overlap", () => {
const box1 = { min: [0, 0], max: [1, 1] };
const box2 = { min: [1 + 1e-2, 0], max: [2, 1] };
expect(ear.math.overlapBoundingBoxes(box1, box2)).toBe(false);
});
// test("overlap on member types", () => {
// const polygon = ear.math.polygon([0, 1.15], [-1, -0.577], [1, -0.577]);
// const circle = ear.math.circle(1);
// const line = ear.math.line([1, 2], [0.5, 0]);
// const ray = ear.math.ray([-1, 2], [0.5, -0.1]);
// const segment = ear.math.segment([-2, 0.5], [2, 0.5]);
// const vector = ear.math.vector(0.75, 0.5);
// const polygon2 = ear.math.polygon([0, -1.15], [1, 0.577], [-1, 0.577]);
// const circle2 = ear.math.circle(1, [0.5, 0]);
// const line2 = ear.math.line([-1, 2], [0.5, 0]);
// const ray2 = ear.math.ray([1, 2], [-0.5, 0]);
// const segment2 = ear.math.segment([0.5, -2], [0.5, 2]);
// const vector2 = ear.math.vector(0, 1);
// const vector3 = ear.math.vector(0, 1, 0);
// [
// polygon.overlap(polygon2),
// // polygon.overlap(circle),
// // polygon.overlap(line),
// // polygon.overlap(ray),
// // polygon.overlap(segment),
// polygon.overlap(vector2),
// // circle.overlap(polygon),
// // circle.overlap(circle2),
// // circle.overlap(line),
// // circle.overlap(ray),
// // circle.overlap(segment),
// circle.overlap(vector),
// // line.overlap(polygon),
// // line.overlap(circle),
// line.overlap(line2),
// line.overlap(ray),
// line.overlap(segment),
// line.overlap(vector),
// // ray.overlap(polygon),
// // ray.overlap(circle),
// ray.overlap(line),
// ray.overlap(ray2),
// ray.overlap(segment),
// ray2.overlap(vector2),
// // segment.overlap(polygon),
// // segment.overlap(circle),
// segment.overlap(line),
// segment.overlap(ray),
// segment.overlap(segment2),
// segment.overlap(vector),
// vector2.overlap(polygon),
// vector.overlap(circle),
// vector.overlap(line),
// vector2.overlap(ray2),
// vector.overlap(segment),
// vector2.overlap(vector3),
// ].forEach(overlap => expect(overlap).toBe(true));
// });
test("point on line, point at line origin", () => {
expect(ear.math.overlapLinePoint(
{ vector: [5, 5], origin: [0, 0] },
[0, 0],
ear.math.includeS,
)).toBe(true);
expect(ear.math.overlapLinePoint(
{ vector: [5, 5], origin: [0, 0] },
[5, 5],
ear.math.includeS,
)).toBe(true);
expect(ear.math.overlapLinePoint(
{ vector: [5, 5], origin: [0, 0] },
[Math.SQRT1_2, Math.SQRT1_2],
ear.math.includeS,
)).toBe(true);
expect(ear.math.overlapLinePoint(
{ vector: [5, 5], origin: [0, 0] },
[0, 0],
ear.math.excludeS,
)).toBe(false);
expect(ear.math.overlapLinePoint(
{ vector: [5, 5], origin: [0, 0] },
[5, 5],
ear.math.excludeS,
)).toBe(false);
expect(ear.math.overlapLinePoint(
{ vector: [5, 5], origin: [0, 0] },
[Math.SQRT1_2, Math.SQRT1_2],
ear.math.excludeS,
)).toBe(true);
});
test("point on line", () => {
expect(ear.math.overlapLinePoint({ vector: [5, 5], origin: [0, 0] }, [2, 2])).toBe(true);
expect(ear.math.overlapLinePoint({ vector: [1, 1], origin: [0, 0] }, [2, 2])).toBe(true);
expect(ear.math.overlapLinePoint({ vector: [2, 2], origin: [0, 0] }, [2.1, 2.1])).toBe(true);
expect(ear.math.overlapLinePoint({ vector: [2, 2], origin: [0, 0] }, [2.000000001, 2.000000001]))
.toBe(true);
expect(ear.math.overlapLinePoint({ vector: [2, 2], origin: [0, 0] }, [-1, -1])).toBe(true);
expect(ear.math.overlapLinePoint(
{ vector: [5, 5], origin: [0, 0] },
[2, 2],
ear.math.includeR,
)).toBe(true);
expect(ear.math.overlapLinePoint(
{ vector: [1, 1], origin: [0, 0] },
[2, 2],
ear.math.includeR,
)).toBe(true);
expect(ear.math.overlapLinePoint(
{ vector: [2, 2], origin: [0, 0] },
[2.1, 2.1],
ear.math.includeR,
)).toBe(true);
expect(ear.math.overlapLinePoint(
{ vector: [2, 2], origin: [0, 0] },
[2.000000001, 2.000000001],
ear.math.includeR,
)).toBe(true);
expect(ear.math.overlapLinePoint(
{ vector: [-1, -1], origin: [0, 0] },
[2, 2],
ear.math.includeR,
)).toBe(false);
expect(ear.math.overlapLinePoint(
{ vector: [1, 1], origin: [0, 0] },
[-0.1, -0.1],
ear.math.includeR,
)).toBe(false);
expect(ear.math.overlapLinePoint(
{ vector: [1, 1], origin: [0, 0] },
[-0.000000001, -0.000000001],
ear.math.includeR,
)).toBe(true);
expect(ear.math.overlapLinePoint(
{ vector: [1, 1], origin: [0, 0] },
[-0.000000001, -0.000000001],
ear.math.excludeR,
)).toBe(false);
expect(ear.math.overlapLinePoint(
{ vector: [5, 5], origin: [0, 0] },
[2, 2],
ear.math.includeS,
)).toBe(true);
expect(ear.math.overlapLinePoint(
{ vector: [1, 1], origin: [0, 0] },
[2, 2],
ear.math.includeS,
)).toBe(false);
expect(ear.math.overlapLinePoint(
{ vector: [2, 2], origin: [0, 0] },
[2.1, 2.1],
ear.math.includeS,
)).toBe(false);
expect(ear.math.overlapLinePoint(
{ vector: [2, 2], origin: [0, 0] },
[2.000000001, 2.000000001],
ear.math.includeS,
)).toBe(true);
expect(ear.math.overlapLinePoint(
{ vector: [-1, -1], origin: [0, 0] },
[2, 2],
ear.math.includeS,
)).toBe(false);
expect(ear.math.overlapLinePoint(
{ vector: [2, 2], origin: [0, 0] },
[2.000000001, 2.000000001],
ear.math.excludeS,
)).toBe(false);
});
test("overlap.point_on_segment_inclusive", () => {
expect(ear.math.overlapLinePoint(
{ vector: [3, 0], origin: [3, 3] },
[4, 3],
ear.math.includeS,
)).toBe(true);
expect(ear.math.overlapLinePoint(
{ vector: [3, 0], origin: [3, 3] },
[3, 3],
ear.math.includeS,
)).toBe(true);
expect(ear.math.overlapLinePoint(
{ vector: [3, 0], origin: [3, 3] },
[2.9, 3],
ear.math.includeS,
)).toBe(false);
expect(ear.math.overlapLinePoint(
{ vector: [3, 0], origin: [3, 3] },
[2.9999999999, 3],
ear.math.includeS,
)).toBe(true);
expect(ear.math.overlapLinePoint(
{ vector: [3, 0], origin: [3, 3] },
[6.1, 3],
ear.math.includeS,
)).toBe(false);
expect(ear.math.overlapLinePoint(
{ vector: [3, 0], origin: [3, 3] },
[6.0000000001, 3],
ear.math.includeS,
)).toBe(true);
expect(ear.math.overlapLinePoint(
{ vector: [2, 2], origin: [2, 2] },
[3.5, 3.5],
ear.math.includeS,
)).toBe(true);
expect(ear.math.overlapLinePoint(
{ vector: [2, 2], origin: [2, 2] },
[2.9, 3.1],
ear.math.includeS,
)).toBe(false);
expect(ear.math.overlapLinePoint(
{ vector: [2, 2], origin: [2, 2] },
[2.99999999, 3.000000001],
ear.math.includeS,
)).toBe(true);
// degenerate edge returns false
expect(ear.math.overlapLinePoint(
{ vector: [0, 0], origin: [2, 2] },
[2, 2],
ear.math.includeS,
)).toBe(false);
expect(ear.math.overlapLinePoint(
{ vector: [0, 0], origin: [2, 2] },
[2.1, 2.1],
ear.math.includeS,
)).toBe(false);
expect(ear.math.overlapLinePoint(
{ vector: [0, 0], origin: [2, 2] },
[2.000000001, 2.00000001],
ear.math.includeS,
)).toBe(false);
});
test("point on line epsilon", () => {
});
const overlapMethod = (...args) => (
ear.math.overlapConvexPolygonPoint(...args).overlap
);
test("point in poly", () => {
const poly = [[1, 0], [0, 1], [-1, 0], [0, -1]];
expect(overlapMethod(poly, [0.0, 0.0])).toBe(true);
expect(overlapMethod(poly, [0.999, 0.0])).toBe(true);
expect(overlapMethod(poly, [0.9999999999, 0.0])).toBe(false);
// edge collinear
expect(overlapMethod(poly, [0.5, 0.5])).toBe(false);
expect(overlapMethod(poly, [0.49, 0.49])).toBe(true);
expect(overlapMethod(poly, [0.51, 0.51])).toBe(false);
expect(overlapMethod(poly, [0.500000001, 0.500000001])).toBe(false);
expect(overlapMethod(poly, [0.5, -0.5])).toBe(false);
// expect(overlapMethod(poly, [-0.5, 0.5])).toBe(false);
// expect(overlapMethod(poly, [-0.5, -0.5])).toBe(false);
// polygon points
expect(overlapMethod(poly, [1.0, 0.0])).toBe(false);
expect(overlapMethod(poly, [0.0, 1.0])).toBe(false);
// expect(overlapMethod(poly, [-1.0, 0.0])).toBe(false);
expect(overlapMethod(poly, [0.0, -1.0])).toBe(false);
});
test("convex point in poly inclusive", () => {
const poly = [[1, 0], [0, 1], [-1, 0], [0, -1]];
expect(overlapMethod(poly, [0.0, 0.0], ear.math.include))
.toBe(true);
expect(overlapMethod(poly, [0.999, 0.0], ear.math.include))
.toBe(true);
expect(overlapMethod(poly, [0.9999999999, 0.0], ear.math.include))
.toBe(true);
expect(overlapMethod(poly, [1.1, 0.0], ear.math.include))
.toBe(false);
expect(overlapMethod(poly, [1.000000001, 0.0], ear.math.include))
.toBe(true);
// edge collinear
expect(overlapMethod(poly, [0.5, 0.5], ear.math.include))
.toBe(true);
expect(overlapMethod(poly, [0.49, 0.49], ear.math.include))
.toBe(true);
expect(overlapMethod(poly, [0.499999999, 0.499999999], ear.math.include))
.toBe(true);
expect(overlapMethod(poly, [0.51, 0.51], ear.math.include))
.toBe(false);
expect(overlapMethod(poly, [0.500000001, 0.500000001], ear.math.include))
.toBe(true);
expect(overlapMethod(poly, [0.5, -0.5], ear.math.include))
.toBe(true);
expect(overlapMethod(poly, [-0.5, 0.5], ear.math.include))
.toBe(true);
expect(overlapMethod(poly, [-0.5, -0.5], ear.math.include))
.toBe(true);
// polygon points
expect(overlapMethod(poly, [1.0, 0.0], ear.math.include))
.toBe(true);
expect(overlapMethod(poly, [0.0, 1.0], ear.math.include))
.toBe(true);
expect(overlapMethod(poly, [-1.0, 0.0], ear.math.include))
.toBe(true);
expect(overlapMethod(poly, [0.0, -1.0], ear.math.include))
.toBe(true);
});
test("convex point in poly exclusive", () => {
const poly = [[1, 0], [0, 1], [-1, 0], [0, -1]];
expect(overlapMethod(poly, [0.0, 0.0], ear.math.exclude))
.toBe(true);
expect(overlapMethod(poly, [0.999, 0.0], ear.math.exclude))
.toBe(true);
expect(overlapMethod(poly, [0.9999999999, 0.0], ear.math.exclude))
.toBe(false);
// edge collinear
expect(overlapMethod(poly, [0.5, 0.5], ear.math.exclude))
.toBe(false);
expect(overlapMethod(poly, [0.49, 0.49], ear.math.exclude))
.toBe(true);
expect(overlapMethod(poly, [0.499999999, 0.499999999], ear.math.exclude))
.toBe(false);
expect(overlapMethod(poly, [0.51, 0.51], ear.math.exclude))
.toBe(false);
expect(overlapMethod(poly, [0.5, -0.5], ear.math.exclude))
.toBe(false);
expect(overlapMethod(poly, [-0.5, 0.5], ear.math.exclude))
.toBe(false);
expect(overlapMethod(poly, [-0.5, -0.5], ear.math.exclude))
.toBe(false);
// polygon points
expect(overlapMethod(poly, [1.0, 0.0], ear.math.exclude))
.toBe(false);
expect(overlapMethod(poly, [0.0, 1.0], ear.math.exclude))
.toBe(false);
expect(overlapMethod(poly, [-1.0, 0.0], ear.math.exclude))
.toBe(false);
expect(overlapMethod(poly, [0.0, -1.0], ear.math.exclude))
.toBe(false);
});
================================================
FILE: tests/math.intersect.polyLine.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("intersectPolygonLine, edge collinear", () => {
// all cases will have length of 2
const square = [[0, 0], [1, 0], [1, 1], [0, 1]];
const lineHoriz1 = { vector: [1, 0], origin: [0, 0] };
const lineHoriz2 = { vector: [1, 0], origin: [1, 1] };
const lineVert1 = { vector: [0, 1], origin: [0, 0] };
const lineVert2 = { vector: [0, 1], origin: [1, 1] };
const results = [
ear.math.intersectPolygonLine(square, lineHoriz1, ear.math.includeL),
ear.math.intersectPolygonLine(square, lineHoriz2, ear.math.includeL),
ear.math.intersectPolygonLine(square, lineVert1, ear.math.includeL),
ear.math.intersectPolygonLine(square, lineVert2, ear.math.includeL),
];
results.forEach(res => expect(res).toHaveLength(2));
});
test("intersectPolygonLine, through two vertices", () => {
const square = [[0, 0], [1, 0], [1, 1], [0, 1]];
const lineDiag1 = { vector: [1, 1], origin: [0, 0] };
const lineDiag2 = { vector: [-1, 1], origin: [1, 0] };
expect(ear.math.intersectPolygonLine(square, lineDiag1, ear.math.includeL))
.toHaveLength(2);
expect(ear.math.intersectPolygonLine(square, lineDiag2, ear.math.includeL))
.toHaveLength(2);
expect(ear.math.intersectPolygonLine(square, lineDiag1, ear.math.includeS))
.toHaveLength(2);
expect(ear.math.intersectPolygonLine(square, lineDiag2, ear.math.includeS))
.toHaveLength(2);
expect(ear.math.intersectPolygonLine(square, lineDiag1, ear.math.excludeS))
.toHaveLength(0);
expect(ear.math.intersectPolygonLine(square, lineDiag2, ear.math.excludeS))
.toHaveLength(0);
});
================================================
FILE: tests/math.intersect.split.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("deprecated", () => expect(true).toBe(true));
// test("splitConvexPolygon", () => {
// const rect_counter = [
// [-1, -1],
// [+1, -1],
// [+1, +1],
// [-1, +1],
// ];
// const rect_clock = [
// [-1, -1],
// [-1, +1],
// [+1, +1],
// [+1, -1],
// ];
// const res0 = ear.math.splitConvexPolygon(rect_counter, { vector: [1, 2], origin: [0, 0] });
// [[-1, 1], [-1, -1], [-0.5, -1], [0.5, 1]].forEach((expected, i) => {
// expect(JSON.stringify(expected)).toBe(JSON.stringify(res0[0][i]));
// });
// [[1, -1], [1, 1], [0.5, 1], [-0.5, -1]].forEach((expected, i) => {
// expect(JSON.stringify(expected)).toBe(JSON.stringify(res0[1][i]));
// });
// });
// test("splitConvexPolygon no overlap", () => {
// const rect_counter = [
// [-1, -1],
// [+1, -1],
// [+1, +1],
// [-1, +1],
// ];
// const result = ear.math.splitConvexPolygon(rect_counter, { vector: [1, 2], origin: [10, 0] });
// rect_counter.forEach((expected, i) => {
// expect(JSON.stringify(expected)).toBe(JSON.stringify(result[0][i]));
// });
// });
// test("splitConvexPolygon vertex collinear", () => {
// const rect_counter = [
// [-1, -1],
// [+1, -1],
// [+1, +1],
// [-1, +1],
// ];
// const res0 = ear.math.splitConvexPolygon(rect_counter, { vector: [1, 1], origin: [0, 0] });
// [[1, 1], [-1, 1], [-1, -1]].forEach((expected, i) => {
// expect(JSON.stringify(expected)).toBe(JSON.stringify(res0[0][i]));
// });
// [[-1, -1], [1, -1], [1, 1]].forEach((expected, i) => {
// expect(JSON.stringify(expected)).toBe(JSON.stringify(res0[1][i]));
// });
// });
// test("splitConvexPolygon 1 edge and 1 vertex collinear", () => {
// const rect_counter = [
// [-1, -1],
// [+1, -1],
// [+1, +1],
// [-1, +1],
// ];
// const res0 = ear.math.splitConvexPolygon(rect_counter, { vector: [1, 2], origin: [-1, -1] });
// [[-1, 1], [-1, -1], [0, 1]].forEach((expected, i) => {
// expect(JSON.stringify(expected)).toBe(JSON.stringify(res0[0][i]));
// });
// [[1, -1], [1, 1], [0, 1], [-1, -1]].forEach((expected, i) => {
// expect(JSON.stringify(expected)).toBe(JSON.stringify(res0[1][i]));
// });
// });
================================================
FILE: tests/math.intersect.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("intersectLineLine include exclude", () => {
const res0 = ear.math.intersectLineLine(
{ vector: [0, 1], origin: [1, 0] },
{ vector: [1, 0], origin: [0, 1] },
).point;
const res1 = ear.math.intersectLineLine(
{ vector: [0, 1], origin: [1, 0] },
{ vector: [1, 0], origin: [0, 1] },
ear.math.includeS,
ear.math.includeS,
).point;
const res2 = ear.math.intersectLineLine(
{ vector: [0, 1], origin: [1, 0] },
{ vector: [1, 0], origin: [0, 1] },
ear.math.excludeS,
ear.math.excludeS,
).point;
expect(res0).not.toBe(undefined);
expect(res1).not.toBe(undefined);
expect(res2).toBe(undefined);
});
test("collinear line intersections", () => {
const intersect = (a, b, c, d, ...args) => ear.math.intersectLineLine(
{ vector: a, origin: b },
{ vector: c, origin: d },
...args,
).point;
[
// INCLUDE horizontal
intersect([1, 0], [2, 2], [1, 0], [-1, 2], ear.math.includeL, ear.math.includeL),
intersect([1, 0], [2, 2], [-1, 0], [-1, 2], ear.math.includeL, ear.math.includeL),
intersect([-1, 0], [2, 2], [1, 0], [-1, 2], ear.math.includeL, ear.math.includeL),
// INCLUDE vertical
intersect([0, 1], [3, 0], [0, 1], [3, 3], ear.math.includeL, ear.math.includeL),
intersect([0, 1], [3, 0], [0, -1], [3, 3], ear.math.includeL, ear.math.includeL),
intersect([0, -1], [3, 0], [0, 1], [3, 3], ear.math.includeL, ear.math.includeL),
// INCLUDE diagonal
intersect([1, 1], [2, 2], [1, 1], [-1, -1], ear.math.includeL, ear.math.includeL),
intersect([-1, -1], [2, 2], [1, 1], [-1, -1], ear.math.includeL, ear.math.includeL),
intersect([1, 1], [2, 2], [-1, -1], [-1, -1], ear.math.includeL, ear.math.includeL),
// EXCLUDE horizontal
intersect([1, 0], [2, 2], [1, 0], [-1, 2], ear.math.excludeL, ear.math.excludeL),
intersect([1, 0], [2, 2], [-1, 0], [-1, 2], ear.math.excludeL, ear.math.excludeL),
intersect([-1, 0], [2, 2], [1, 0], [-1, 2], ear.math.excludeL, ear.math.excludeL),
// EXCLUDE vertical
intersect([0, 1], [3, 0], [0, 1], [3, 3], ear.math.excludeL, ear.math.excludeL),
intersect([0, 1], [3, 0], [0, -1], [3, 3], ear.math.excludeL, ear.math.excludeL),
intersect([0, -1], [3, 0], [0, 1], [3, 3], ear.math.excludeL, ear.math.excludeL),
// EXCLUDE diagonal
intersect([1, 1], [2, 2], [1, 1], [-1, -1], ear.math.excludeL, ear.math.excludeL),
intersect([-1, -1], [2, 2], [1, 1], [-1, -1], ear.math.excludeL, ear.math.excludeL),
intersect([1, 1], [2, 2], [-1, -1], [-1, -1], ear.math.excludeL, ear.math.excludeL),
].forEach(res => expect(res).toBe(undefined));
});
test("collinear ray intersections", () => {
const intersect = (a, b, c, d, ...args) => ear.math.intersectLineLine(
{ vector: a, origin: b },
{ vector: c, origin: d },
...args,
).point;
[
// INCLUDE horizontal
intersect([1, 0], [2, 2], [1, 0], [-1, 2], ear.math.includeR, ear.math.includeR),
intersect([1, 0], [2, 2], [-1, 0], [-1, 2], ear.math.includeR, ear.math.includeR),
intersect([-1, 0], [2, 2], [1, 0], [-1, 2], ear.math.includeR, ear.math.includeR),
// INCLUDE vertical
intersect([0, 1], [3, 0], [0, 1], [3, 3], ear.math.includeR, ear.math.includeR),
intersect([0, 1], [3, 0], [0, -1], [3, 3], ear.math.includeR, ear.math.includeR),
intersect([0, -1], [3, 0], [0, 1], [3, 3], ear.math.includeR, ear.math.includeR),
// INCLUDE diagonal
intersect([1, 1], [2, 2], [1, 1], [-1, -1], ear.math.includeR, ear.math.includeR),
intersect([-1, -1], [2, 2], [1, 1], [-1, -1], ear.math.includeR, ear.math.includeR),
intersect([1, 1], [2, 2], [-1, -1], [-1, -1], ear.math.includeR, ear.math.includeR),
// EXCLUDE horizontal
intersect([1, 0], [2, 2], [1, 0], [-1, 2], ear.math.excludeR, ear.math.excludeR),
intersect([1, 0], [2, 2], [-1, 0], [-1, 2], ear.math.excludeR, ear.math.excludeR),
intersect([-1, 0], [2, 2], [1, 0], [-1, 2], ear.math.excludeR, ear.math.excludeR),
// EXCLUDE vertical
intersect([0, 1], [3, 0], [0, 1], [3, 3], ear.math.excludeR, ear.math.excludeR),
intersect([0, 1], [3, 0], [0, -1], [3, 3], ear.math.excludeR, ear.math.excludeR),
intersect([0, -1], [3, 0], [0, 1], [3, 3], ear.math.excludeR, ear.math.excludeR),
// EXCLUDE diagonal
intersect([1, 1], [2, 2], [1, 1], [-1, -1], ear.math.excludeR, ear.math.excludeR),
intersect([-1, -1], [2, 2], [1, 1], [-1, -1], ear.math.excludeR, ear.math.excludeR),
intersect([1, 1], [2, 2], [-1, -1], [-1, -1], ear.math.excludeR, ear.math.excludeR),
].forEach(res => expect(res).toBe(undefined));
});
test("collinear segment intersections", () => {
const intersect = (a, b, c, d, ...args) => ear.math.intersectLineLine(
{ vector: a, origin: b },
{ vector: c, origin: d },
...args,
).point;
[
// INCLUDE horizontal
intersect([1, 0], [2, 2], [1, 0], [-1, 2], ear.math.includeS, ear.math.includeS),
intersect([1, 0], [2, 2], [-1, 0], [-1, 2], ear.math.includeS, ear.math.includeS),
intersect([-1, 0], [2, 2], [1, 0], [-1, 2], ear.math.includeS, ear.math.includeS),
// INCLUDE vertical
intersect([0, 1], [3, 0], [0, 1], [3, 3], ear.math.includeS, ear.math.includeS),
intersect([0, 1], [3, 0], [0, -1], [3, 3], ear.math.includeS, ear.math.includeS),
intersect([0, -1], [3, 0], [0, 1], [3, 3], ear.math.includeS, ear.math.includeS),
// INCLUDE diagonal
intersect([1, 1], [2, 2], [1, 1], [-1, -1], ear.math.includeS, ear.math.includeS),
intersect([-1, -1], [2, 2], [1, 1], [-1, -1], ear.math.includeS, ear.math.includeS),
intersect([1, 1], [2, 2], [-1, -1], [-1, -1], ear.math.includeS, ear.math.includeS),
// EXCLUDE horizontal
intersect([1, 0], [2, 2], [1, 0], [-1, 2], ear.math.excludeS, ear.math.excludeS),
intersect([1, 0], [2, 2], [-1, 0], [-1, 2], ear.math.excludeS, ear.math.excludeS),
intersect([-1, 0], [2, 2], [1, 0], [-1, 2], ear.math.excludeS, ear.math.excludeS),
// EXCLUDE vertical
intersect([0, 1], [3, 0], [0, 1], [3, 3], ear.math.excludeS, ear.math.excludeS),
intersect([0, 1], [3, 0], [0, -1], [3, 3], ear.math.excludeS, ear.math.excludeS),
intersect([0, -1], [3, 0], [0, 1], [3, 3], ear.math.excludeS, ear.math.excludeS),
// EXCLUDE diagonal
intersect([1, 1], [2, 2], [1, 1], [-1, -1], ear.math.excludeS, ear.math.excludeS),
intersect([-1, -1], [2, 2], [1, 1], [-1, -1], ear.math.excludeS, ear.math.excludeS),
intersect([1, 1], [2, 2], [-1, -1], [-1, -1], ear.math.excludeS, ear.math.excludeS),
].forEach(res => expect(res).toBe(undefined));
});
test("collinear segment intersections, types not core", () => {
const intersect = (a, b) => ear.math.intersectLineLine(a, b).point;
[
// horizontal
intersect(
ear.math.pointsToLine([0, 2], [2, 2]),
ear.math.pointsToLine([-1, 2], [10, 2]),
),
intersect(
ear.math.pointsToLine([0, 2], [2, 2]),
ear.math.pointsToLine([10, 2], [-1, 2]),
),
// vertical
intersect(
ear.math.pointsToLine([2, 0], [2, 2]),
ear.math.pointsToLine([2, -1], [2, 10]),
),
intersect(
ear.math.pointsToLine([2, 0], [2, 2]),
ear.math.pointsToLine([2, 10], [2, -1]),
),
// diagonal
intersect(
ear.math.pointsToLine([0, 0], [2, 2]),
ear.math.pointsToLine([-1, -1], [5, 5]),
),
intersect(
ear.math.pointsToLine([0, 0], [2, 2]),
ear.math.pointsToLine([5, 5], [-1, -1]),
),
].forEach(res => expect(res).toBe(undefined));
});
test("clip polygon polygon, same polygon", () => {
// all of the "b" cases are flipped clockwise and should return no solution
// same polygon
const res1 = ear.math.clipPolygonPolygon(
[[60, 10], [50, 50], [20, 20]],
[[50, 50], [20, 20], [60, 10]],
);
expect(res1.length).toBe(3);
const res2 = ear.math.clipPolygonPolygon(
[[50, 50], [25, 25], [50, 0]],
[[50, 50], [25, 25], [50, 0]],
);
expect(res2.length).toBe(3);
const res2b = ear.math.clipPolygonPolygon(
[[50, 0], [25, 25], [50, 50]],
[[50, 0], [25, 25], [50, 50]],
);
expect(res2b).toBe(undefined);
// same polygon, array rotated
const res3 = ear.math.clipPolygonPolygon(
[[50, 50], [25, 25], [50, 0]],
[[25, 25], [50, 0], [50, 50]],
);
expect(res3.length).toBe(3);
const res3b = ear.math.clipPolygonPolygon(
[[50, 0], [25, 25], [50, 50]],
[[50, 50], [50, 0], [25, 25]],
);
expect(res3b).toBe(undefined);
});
test("polygon polygon, edge aligned", () => {
// edge aligned
const poly3 = [[40, 40], [100, 40], [80, 80]];
const poly4 = [[100, 40], [40, 40], [80, 0]];
const res2 = ear.math.clipPolygonPolygon(poly3, poly4);
expect(res2).toBe(undefined);
const poly5 = [[40, 40], [100, 40], [80, 80]];
const poly6 = [[90, 40], [50, 40], [80, 0]];
const res3 = ear.math.clipPolygonPolygon(poly5, poly6);
expect(res3).toBe(undefined);
const poly7 = [[40, 40], [100, 40], [80, 80]];
const poly8 = [[200, 40], [50, 40], [80, 0]];
const res4 = ear.math.clipPolygonPolygon(poly7, poly8);
expect(res4).toBe(undefined);
const poly9 = [[40, 40], [100, 40], [80, 80]];
const poly10 = [[200, 40], [20, 40], [80, 0]];
const res5 = ear.math.clipPolygonPolygon(poly9, poly10);
expect(res5).toBe(undefined);
});
test("polygon polygon, epsilon", () => {
// now with epsilon
const ep = 1e-10;
const poly11 = [[40, 40 - ep], [100, 40 - ep], [80, 80]];
const poly12 = [[100, 40], [40, 40], [80, 0]];
const res6 = ear.math.clipPolygonPolygon(poly11, poly12);
expect(res6).toBe(undefined);
const res7 = ear.math.clipPolygonPolygon(poly12, poly11);
expect(res7).toBe(undefined);
const poly13 = [[60, 10], [50, 50], [20, 20]];
const poly14 = [[50 + ep, 50 + ep], [20, 20], [60, 10]];
const res8 = ear.math.clipPolygonPolygon(poly13, poly14);
expect(res8.length).toBe(3);
const res9 = ear.math.clipPolygonPolygon(poly14, poly13);
expect(res9.length).toBe(3);
const poly15 = [[60, 10], [50, 50], [20, 20]];
const poly16 = [[50 - ep, 50 - ep], [20, 20], [60, 10]];
const res10 = ear.math.clipPolygonPolygon(poly15, poly16);
expect(res10.length).toBe(3);
const res11 = ear.math.clipPolygonPolygon(poly16, poly15);
expect(res11.length).toBe(3);
});
test("polygon polygon collinear edge", () => {
// these two polygons overlap and have 2 overlapping edges
const poly1clock = [[0, 0], [-1, 1], [0, 2], [2, 0]];
const poly2clock = [[0, 2], [1, 1], [1, -1], [-1, 1]];
const poly1counter = poly1clock.slice().reverse();
const poly2counter = poly2clock.slice().reverse();
// the only one guaranteed to work
expect(ear.math.clipPolygonPolygon(poly1counter, poly2counter)).not.toBeUndefined();
expect(ear.math.clipPolygonPolygon(poly2counter, poly1counter)).not.toBeUndefined();
// all of these have undefined behavior
expect(ear.math.clipPolygonPolygon(poly1clock, poly2clock)).toBeUndefined();
expect(ear.math.clipPolygonPolygon(poly2clock, poly1clock)).toBeUndefined();
expect(ear.math.clipPolygonPolygon(poly1clock, poly2counter)).not.toBeUndefined();
expect(ear.math.clipPolygonPolygon(poly2counter, poly1clock)).toBeUndefined();
expect(ear.math.clipPolygonPolygon(poly1counter, poly2clock)).toBeUndefined();
expect(ear.math.clipPolygonPolygon(poly2clock, poly1counter)).not.toBeUndefined();
});
test("intersect lines", () => {
const clipLine = ear.math.intersectCircleLine(
{ radius: 1, origin: [0, 0] },
{ vector: [0, 1], origin: [0.5, 0] },
);
const shouldBeLine = [[0.5, -Math.sqrt(3) / 2], [0.5, Math.sqrt(3) / 2]];
ear.math.epsilonEqualVectors(clipLine[0], shouldBeLine[0]);
ear.math.epsilonEqualVectors(clipLine[1], shouldBeLine[1]);
// no intersect
expect(ear.math.intersectCircleLine(
{ radius: 1, origin: [2, 2] },
{ vector: [0, 1], origin: [10, 0] },
)).toBe(undefined);
// tangent
const tangent = ear.math.intersectCircleLine(
{ radius: 1, origin: [2, 0] },
{ vector: [0, 1], origin: [3, 0] },
);
expect(tangent[0][0]).toBe(3);
expect(tangent[0][1]).toBe(0);
const shouldBeRay = [Math.SQRT1_2, Math.SQRT1_2];
const clipRay = ear.math.intersectCircleLine(
{ radius: 1, origin: [0, 0] },
{ vector: [0.1, 0.1], origin: [0, 0] },
ear.math.include,
ear.math.includeR,
);
ear.math.epsilonEqualVectors(shouldBeRay, clipRay[0]);
const shouldBeSeg = [Math.SQRT1_2, Math.SQRT1_2];
const clipSeg = ear.math.intersectCircleLine(
{ radius: 1, origin: [0, 0] },
{ vector: [10, 10], origin: [0, 0] },
ear.math.include,
ear.math.includeS,
);
ear.math.epsilonEqualVectors(shouldBeSeg, clipSeg[0]);
});
================================================
FILE: tests/math.overlap.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("overlapConvexPolygonPoint bad inputs", () => {
// invalid point
expect(ear.math.overlapConvexPolygonPoint(
[[0, 0], [1, 0], [1, 1], [0, 1]],
[],
ear.math.exclude,
).overlap).toBe(true);
});
test("overlapConvexPolygonPoint counter-clockwise point on boundary", () => {
// counter-clockwise
const square = [[0, 0], [1, 0], [1, 1], [0, 1]];
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, 0], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [1, 0.5], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, 1], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0, 0.5], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, 0], ear.math.include).overlap)
.toBe(true);
expect(ear.math.overlapConvexPolygonPoint(square, [1, 0.5], ear.math.include).overlap)
.toBe(true);
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, 1], ear.math.include).overlap)
.toBe(true);
expect(ear.math.overlapConvexPolygonPoint(square, [0, 0.5], ear.math.include).overlap)
.toBe(true);
});
test("overlapConvexPolygonPoint clockwise point on boundary", () => {
// clockwise
const square = [[0, 0], [0, 1], [1, 1], [1, 0]];
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, 0], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [1, 0.5], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, 1], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0, 0.5], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, 0], ear.math.include).overlap)
.toBe(true);
expect(ear.math.overlapConvexPolygonPoint(square, [1, 0.5], ear.math.include).overlap)
.toBe(true);
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, 1], ear.math.include).overlap)
.toBe(true);
expect(ear.math.overlapConvexPolygonPoint(square, [0, 0.5], ear.math.include).overlap)
.toBe(true);
});
test("overlapConvexPolygonPoint counter-clockwise point on vertex", () => {
// counter-clockwise
const square = [[0, 0], [1, 0], [1, 1], [0, 1]];
expect(ear.math.overlapConvexPolygonPoint(square, [0, 0], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [1, 0], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [1, 1], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0, 1], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0, 0], ear.math.include).overlap)
.toBe(true);
expect(ear.math.overlapConvexPolygonPoint(square, [1, 0], ear.math.include).overlap)
.toBe(true);
expect(ear.math.overlapConvexPolygonPoint(square, [1, 1], ear.math.include).overlap)
.toBe(true);
expect(ear.math.overlapConvexPolygonPoint(square, [0, 1], ear.math.include).overlap)
.toBe(true);
});
test("overlapConvexPolygonPoint clockwise point on vertex", () => {
// clockwise
const square = [[0, 0], [0, 1], [1, 1], [1, 0]];
expect(ear.math.overlapConvexPolygonPoint(square, [0, 0], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [1, 0], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [1, 1], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0, 1], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0, 0], ear.math.include).overlap)
.toBe(true);
expect(ear.math.overlapConvexPolygonPoint(square, [1, 0], ear.math.include).overlap)
.toBe(true);
expect(ear.math.overlapConvexPolygonPoint(square, [1, 1], ear.math.include).overlap)
.toBe(true);
expect(ear.math.overlapConvexPolygonPoint(square, [0, 1], ear.math.include).overlap)
.toBe(true);
});
test("overlapConvexPolygonPoint counter-clockwise point inside", () => {
// counter-clockwise
const square = [[0, 0], [1, 0], [1, 1], [0, 1]];
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, 0.5], ear.math.exclude).overlap)
.toBe(true);
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, 0.5], ear.math.include).overlap)
.toBe(true);
});
test("overlapConvexPolygonPoint clockwise point inside", () => {
// clockwise
const square = [[0, 0], [0, 1], [1, 1], [1, 0]];
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, 0.5], ear.math.exclude).overlap)
.toBe(true);
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, 0.5], ear.math.include).overlap)
.toBe(true);
});
test("overlapConvexPolygonPoint counter-clockwise point outside", () => {
// counter-clockwise
const square = [[0, 0], [1, 0], [1, 1], [0, 1]];
expect(ear.math.overlapConvexPolygonPoint(square, [2, 0.5], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, 2], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [-2, 0.5], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, -2], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [2, 0.5], ear.math.include).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, 2], ear.math.include).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [-2, 0.5], ear.math.include).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, -2], ear.math.include).overlap)
.toBe(false);
});
test("overlapConvexPolygonPoint clockwise point outside", () => {
// clockwise
const square = [[0, 0], [0, 1], [1, 1], [1, 0]];
expect(ear.math.overlapConvexPolygonPoint(square, [2, 0.5], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, 2], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [-2, 0.5], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, -2], ear.math.exclude).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [2, 0.5], ear.math.include).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, 2], ear.math.include).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [-2, 0.5], ear.math.include).overlap)
.toBe(false);
expect(ear.math.overlapConvexPolygonPoint(square, [0.5, -2], ear.math.include).overlap)
.toBe(false);
});
test("overlapConvexPolygons", () => {
const square1 = [[0, 0], [1, 0], [1, 1], [0, 1]];
const square2 = [[1, 0], [2, 0], [2, 1], [1, 1]];
// nudge squares by an amount larger than the epsilon
const square2Plus = [[1, 0], [2, 0], [2, 1], [1, 1]].map(p => [p[0] + 1e-2, p[1]]);
const square2Minus = [[1, 0], [2, 0], [2, 1], [1, 1]].map(p => [p[0] - 1e-2, p[1]]);
expect(ear.math.overlapConvexPolygons(square1, square2)).toBe(false);
expect(ear.math.overlapConvexPolygons(square2, square1)).toBe(false);
expect(ear.math.overlapConvexPolygons(square1, square2Plus)).toBe(false);
expect(ear.math.overlapConvexPolygons(square2Plus, square1)).toBe(false);
expect(ear.math.overlapConvexPolygons(square1, square2Minus)).toBe(true);
expect(ear.math.overlapConvexPolygons(square2Minus, square1)).toBe(true);
// increase epsilon until they overlap again
// this is not possible, you cannot adjust the epsilon to convert a
// non-overlapping to overlapping or visa-versa.
// expect(ear.math.overlapConvexPolygons(square1, square2Minus), 1e-3).toBe(false);
// expect(ear.math.overlapConvexPolygons(square2Minus, square1), 1e-3).toBe(false);
});
================================================
FILE: tests/math.primitives.circle.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("excluding primitives", () => expect(true).toBe(true));
// test("arguments", () => {
// expect(ear.math.circle(1, [4, 5]).radius).toBe(1);
// expect(ear.math.circle(1, [4, 5]).origin.x).toBe(4);
// expect(ear.math.circle(1, [4, 5]).origin.y).toBe(5);
// expect(ear.math.circle([4, 5], 1).radius).toBe(1);
// expect(ear.math.circle([4, 5], 1).origin.x).toBe(4);
// expect(ear.math.circle([4, 5], 1).origin.y).toBe(5);
// expect(ear.math.circle(1, 2).radius).toBe(2);
// expect(ear.math.circle(1, 2).origin.x).toBe(1);
// expect(ear.math.circle(1, 2, 3).radius).toBe(3);
// expect(ear.math.circle(1, 2, 3).origin.x).toBe(1);
// expect(ear.math.circle(1, 2, 3).origin.y).toBe(2);
// expect(ear.math.circle(1, 2, 3, 4).radius).toBe(4);
// expect(ear.math.circle(1, 2, 3, 4).origin.x).toBe(1);
// expect(ear.math.circle(1, 2, 3, 4).origin.y).toBe(2);
// expect(ear.math.circle(1, 2, 3, 4).origin.z).toBe(3);
// expect(ear.math.circle([1, 2], [3, 4]).radius).toBe(ear.math.distance2([1, 2], [3, 4]));
// expect(ear.math.circle([1, 2], [3, 4]).origin.x).toBe(1);
// expect(ear.math.circle([1, 2], [3, 4]).origin.y).toBe(2);
// // expect(ear.math.circle([1,2], [3,4], [5,6]) circumcenter between 3 points
// // expect(ear.math.circle([1,2], [3,4], [5,6]) circumcenter between 3 points
// });
// test("x, y", () => {
// const result = ear.math.circle(1, [2, 3]);
// expect(result.x).toBe(2);
// expect(result.y).toBe(3);
// expect(result.z).toBe(undefined);
// const result1 = ear.math.circle(1);
// expect(result1.x).toBe(0);
// expect(result1.y).toBe(0);
// expect(result1.z).toBe(0);
// });
// test("circle nearest point", () => {
// const result1 = ear.math.circle(1).nearestPoint([5, 0]);
// expect(result1.x).toBeCloseTo(1);
// expect(result1.y).toBeCloseTo(0);
// const result2 = ear.math.circle(2, [4, 4]).nearestPoint([0, 0]);
// expect(result2.x).toBeCloseTo(4 - Math.sqrt(2));
// expect(result2.y).toBeCloseTo(4 - Math.sqrt(2));
// });
// test("points", () => {
// const result = ear.math.circle(1, [1, 2]).points();
// expect(result.length).toBe(128);
// expect(result[0][0]).toBeCloseTo(2);
// expect(result[0][1]).toBeCloseTo(2);
// });
// test("points param", () => {
// const result1 = ear.math.circle(1).points(64);
// expect(result1.length).toBe(64);
// const result2 = ear.math.circle(1).points(1);
// expect(result2.length).toBe(1);
// const result3 = ear.math.circle(1).points(3);
// expect(result3.length).toBe(3);
// });
// test("polygon", () => {
// const result = ear.math.circle(1, [1, 2]).polygon();
// expect(result.points.length).toBe(128);
// expect(result.points[0][0]).toBeCloseTo(2);
// expect(result.points[0][1]).toBeCloseTo(2);
// });
// test("segments", () => {
// const result = ear.math.circle(1, [1, 2]).segments();
// expect(result.length).toBe(128);
// expect(result[0][0][0]).toBeCloseTo(2);
// expect(result[0][0][1]).toBeCloseTo(2);
// });
// test("circle fromPoints", () => {
// const result1 = ear.math.circle.fromPoints([1, 2], [0, 3], [-1, 2]);
// expect(result1.radius).toBeCloseTo(1);
// expect(result1.origin.x).toBeCloseTo(0);
// expect(result1.origin.y).toBeCloseTo(2);
// const result2 = ear.math.circle.fromPoints([1, 2], [0, 3]);
// expect(result2.radius).toBeCloseTo(Math.sqrt(2));
// expect(result2.origin.x).toBeCloseTo(1);
// expect(result2.origin.y).toBeCloseTo(2);
// });
// test("circle fromThreePoints", () => {
// const result = ear.math.circle.fromThreePoints([1, 2], [0, 3], [-1, 2]);
// expect(result.origin.x).toBeCloseTo(0);
// expect(result.origin.y).toBeCloseTo(2);
// });
// test("intersect lines", () => {
// const clipLine = ear.math.circle(1).intersect(ear.math.line([0, 1], [0.5, 0]));
// const shouldBeLine = [[0.5, -Math.sqrt(3) / 2], [0.5, Math.sqrt(3) / 2]];
// ear.math.epsilonEqualVectors(clipLine[0], shouldBeLine[0]);
// ear.math.epsilonEqualVectors(clipLine[1], shouldBeLine[1]);
// // no intersect
// expect(ear.math.circle(1, [2, 2]).intersect(ear.math.line([0, 1], [10, 0]))).toBe(undefined);
// // tangent
// const tangent = ear.math.circle(1, [2, 0]).intersect(ear.math.line([0, 1], [3, 0]));
// expect(tangent[0][0]).toBe(3);
// expect(tangent[0][1]).toBe(0);
// const shouldBeRay = [Math.sqrt(2) / 2, Math.sqrt(2) / 2];
// const clipRay = ear.math.circle(1).intersect(ear.math.ray(0.1, 0.1));
// ear.math.epsilonEqualVectors(shouldBeRay, clipRay[0]);
// const shouldBeSeg = [Math.sqrt(2) / 2, Math.sqrt(2) / 2];
// const clipSeg = ear.math.circle(1).intersect(ear.math.segment(0, 0, 10, 10));
// ear.math.epsilonEqualVectors(shouldBeSeg, clipSeg[0]);
// });
// test("circle circle intersect", () => {
// // same origin
// expect(ear.math.circle(1).intersect(ear.math.circle(2))).toBe(undefined);
// // kissing circles
// const result1 = ear.math.circle(1).intersect(ear.math.circle(1, [2, 0]));
// expect(result1[0][0]).toBe(1);
// expect(result1[0][1]).toBe(0);
// const result2 = ear.math.circle(1).intersect(ear.math.circle(1, [Math.sqrt(2), Math.sqrt(2)]));
// expect(result2[0][0]).toBeCloseTo(Math.sqrt(2) / 2);
// expect(result2[0][1]).toBeCloseTo(Math.sqrt(2) / 2);
// // circles are contained
// expect(ear.math.circle(10).intersect(ear.math.circle(1, [2, 0]))).toBe(undefined);
// });
================================================
FILE: tests/math.primitives.clip.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("excluding primitives", () => expect(true).toBe(true));
// test("math types, clip line in rect", () => {
// // const rect = [[-1, -1], [1, -1], [1, 1], [-1, 1]];
// const rect = ear.math.rect(-1, -1, 2, 2);
// rect.exclusive();
// expect(rect.clip(ear.math.line(1, 1))).not.toBe(undefined);
// expect(rect.clip(ear.math.line([1, 0], [0, 1]))).toBe(undefined);
// expect(rect.clip(ear.math.line(1, -1))).not.toBe(undefined);
// rect.inclusive();
// expect(rect.clip(ear.math.line([1, 0], [0, 1]))).not.toBe(undefined);
// // same as above, but inclusive test.
// const result1 = clip_line_in_convex_poly_inclusive(
// rect,
// ear.math.line(1, 1).vector,
// ear.math.line(1, 1).origin,
// );
// expect(result1[0][0]).toBe(-1);
// expect(result1[0][1]).toBe(-1);
// expect(result1[1][0]).toBe(1);
// expect(result1[1][1]).toBe(1);
// const result2 = clip_line_in_convex_poly_inclusive(
// rect,
// ear.math.line([1, 0], [0, 1]).vector,
// ear.math.line([1, 0], [0, 1]).origin,
// );
// expect(result2[0][0]).toBe(-1);
// expect(result2[0][1]).toBe(1);
// expect(result2[1][0]).toBe(1);
// expect(result2[1][1]).toBe(1);
// const result3 = clip_line_in_convex_poly_inclusive(
// rect,
// ear.math.line(1, -1).vector,
// ear.math.line(1, -1).origin,
// );
// expect(result3[0][0]).toBe(-1);
// expect(result3[0][1]).toBe(1);
// expect(result3[1][0]).toBe(1);
// expect(result3[1][1]).toBe(-1);
// });
// test("math types, clip ray in rect", () => {
// const rect = ear.math.rect(-1, -1, 2, 2);
// const result1 = rect.clip(ear.math.ray(1, 1));
// expect(result1[0][0]).toBe(0);
// expect(result1[0][1]).toBe(0);
// expect(result1[1][0]).toBe(1);
// expect(result1[1][1]).toBe(1);
// rect.inclusive();
// expect(rect.clip(ear.math.ray([1, 0], [0, 1]))).not.toBe(undefined);
// rect.exclusive();
// expect(rect.clip(ear.math.ray([1, 0], [0, 1]))).toBe(undefined);
// const result3 = rect.clip(ear.math.ray(1, -1));
// expect(result3[0][0]).toBe(0);
// expect(result3[0][1]).toBe(0);
// expect(result3[1][0]).toBe(1);
// expect(result3[1][1]).toBe(-1);
// });
// test("math types, clip segment in rect", () => {
// const rect = ear.math.rect(-1, -1, 2, 2);
// const result1 = rect.clip(ear.math.segment([0, 0], [1, 1]));
// expect(result1[0][0]).toBe(0);
// expect(result1[0][1]).toBe(0);
// expect(result1[1][0]).toBe(1);
// expect(result1[1][1]).toBe(1);
// const result2 = rect.clip(ear.math.segment([0, 0], [2, 2]));
// expect(result2[0][0]).toBe(0);
// expect(result2[0][1]).toBe(0);
// expect(result2[1][0]).toBe(1);
// expect(result2[1][1]).toBe(1);
// const result3 = rect.clip(ear.math.segment([0, 0], [1, -1]));
// expect(result3[0][0]).toBe(0);
// expect(result3[0][1]).toBe(0);
// expect(result3[1][0]).toBe(1);
// expect(result3[1][1]).toBe(-1);
// });
// test("no clips", () => {
// const rect = ear.math.rect(-1, -1, 2, 2);
// const result1 = rect.clip(ear.math.line([-0.707, 0.707], [2, 0]));
// expect(result1).toBe(undefined);
// });
// test("core clip", () => {
// const poly = [...ear.math.rect(-1, -1, 2, 2)];
// const vector = [1, 1];
// const origin = [0, 0];
// [
// clip_line_in_convex_poly_inclusive(poly, vector, origin),
// clip_ray_in_convex_poly_exclusive(poly, vector, origin),
// clip_ray_in_convex_poly_inclusive(poly, vector, origin),
// clip_segment_in_convex_poly_exclusive(poly, vector, origin),
// clip_segment_in_convex_poly_inclusive(poly, vector, origin),
// ].forEach(res => expect(res).not.toBe(undefined));
// });
// test("core no clip", () => {
// const poly = [...ear.math.rect(-1, -1, 2, 2)];
// const vector = [1, 1];
// const origin = [10, 0];
// const seg0 = [10, 0];
// const seg1 = [0, 10];
// [
// clip_line_in_convex_poly_inclusive(poly, vector, origin),
// clip_ray_in_convex_poly_exclusive(poly, vector, origin),
// clip_ray_in_convex_poly_inclusive(poly, vector, origin),
// clip_segment_in_convex_poly_exclusive(poly, seg0, seg1),
// clip_segment_in_convex_poly_inclusive(poly, seg0, seg1),
// ].forEach(res => expect(res).toBe(undefined));
// });
// test("core clip segments exclusive", () => {
// const poly = [...ear.math.rect(-1, -1, 2, 2)];
// // all inside
// const seg0 = [[0, 0], [0.2, 0.2]];
// const result0 = clip_segment_in_convex_poly_exclusive(poly, ...seg0);
// expect(ear.math.epsilonEqualVectors(seg0[0], result0[0])).toBe(true);
// expect(ear.math.epsilonEqualVectors(seg0[1], result0[1])).toBe(true);
// // all outside
// const seg1 = [[10, 10], [10.2, 10.2]];
// // const result1 = clip_segment_in_convex_poly_exclusive(poly, ...seg1);
// const result1 = ear.math.clipLineConvexPolygon(
// [[-1, -1], [1, -1], [1, 1], [-1, 1]],
// [0.2, 0.2],
// [10, 10],
// ear.math.include,
// ear.math.includeS,
// );
// expect(result1).toBe(undefined);
// // inside and collinear
// const seg2 = [[0, 0], [1, 0]];
// const result2 = ear.math.clipLineConvexPolygon(
// poly,
// [1, 0],
// [0, 0],
// ear.math.include,
// ear.math.includeS,
// );
// expect(ear.math.epsilonEqualVectors(seg2[0], result2[0])).toBe(true);
// expect(ear.math.epsilonEqualVectors(seg2[1], result2[1])).toBe(true);
// // outside and collinear
// const seg3 = [[5, 0], [1, 0]];
// // const result3 = clip_segment_in_convex_poly_exclusive(poly, ...seg3);
// const result3 = ear.math.clipLineConvexPolygon(
// poly,
// [5, 0],
// [1, 0],
// ear.math.exclude,
// ear.math.excludeS,
// );
// expect(result3).toBe(undefined);
// // inside and collinear
// const seg4 = [[-1, 0], [1, 0]];
// const result4 = clip_segment_in_convex_poly_exclusive(poly, ...seg4);
// expect(ear.math.epsilonEqualVectors(seg4[0], result4[0])).toBe(true);
// expect(ear.math.epsilonEqualVectors(seg4[1], result4[1])).toBe(true);
// });
// test("core clip segments inclusive", () => {
// const poly = [...ear.math.rect(-1, -1, 2, 2)];
// // all inside
// const seg0 = [[0, 0], [0.2, 0.2]];
// const result0 = clip_segment_in_convex_poly_inclusive(poly, ...seg0);
// expect(ear.math.epsilonEqualVectors(seg0[0], result0[0])).toBe(true);
// expect(ear.math.epsilonEqualVectors(seg0[1], result0[1])).toBe(true);
// // all outside
// const seg1 = [[10, 10], [10.2, 10.2]];
// const result1 = clip_segment_in_convex_poly_inclusive(poly, ...seg1);
// expect(result1).toBe(undefined);
// // inside and collinear
// const seg2 = [[0, 0], [1, 0]];
// const result2 = clip_segment_in_convex_poly_inclusive(poly, ...seg2);
// expect(ear.math.epsilonEqualVectors(seg2[0], result2[0])).toBe(true);
// expect(ear.math.epsilonEqualVectors(seg2[1], result2[1])).toBe(true);
// // outside and collinear
// // const seg3 = [[5, 0], [1, 0]];
// // const result3 = clip_segment_in_convex_poly_inclusive(poly, ...seg3);
// const result3 = ear.math.clipLineConvexPolygon(
// poly,
// [5, 0],
// [1, 0],
// ear.math.include,
// ear.math.includeS,
// );
// expect(result3).toBe(undefined);
// // inside and collinear
// const seg4 = [[-1, 0], [1, 0]];
// const result4 = clip_segment_in_convex_poly_inclusive(poly, ...seg4);
// expect(ear.math.epsilonEqualVectors(seg4[0], result4[0])).toBe(true);
// expect(ear.math.epsilonEqualVectors(seg4[1], result4[1])).toBe(true);
// });
================================================
FILE: tests/math.primitives.ellipse.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("excluding primitives", () => expect(true).toBe(true));
// test("x, y", () => {
// const ellipse0 = ear.math.ellipse(2, 1);
// expect(ellipse0.x).toBe(0);
// expect(ellipse0.y).toBe(0);
// // expect(ellipse0.z).toBe(0);
// const ellipse1 = ear.math.ellipse(2, 1, 5, 6);
// expect(ellipse1.x).toBe(5);
// expect(ellipse1.y).toBe(6);
// const ellipse2 = ear.math.ellipse(2, 1, [5, 6], 9);
// expect(ellipse2.x).toBe(5);
// expect(ellipse2.y).toBe(6);
// expect(ellipse2.spin).toBe(9);
// });
// test("foci", () => {
// const result = ear.math.ellipse(1, 0.5).foci;
// // one of these is negative
// expect(Math.abs(result[0].x)).toBeCloseTo(Math.sqrt(3) / 2);
// expect(result[0].y).toBeCloseTo(0);
// expect(Math.abs(result[1].x)).toBeCloseTo(Math.sqrt(3) / 2);
// expect(result[1].y).toBeCloseTo(0);
// });
// // test("nearestPoint", () => {
// // const result = ear.math.ellipse(2, 1).nearestPoint(0, 0);
// // };
// // test("intersect", () => {
// // const result = ear.math.ellipse(2, 1).intersect(object);
// // };
// test("svgPath", () => {
// expect(ear.math.ellipse(2, 1).svgPath()).toBe("M2 0A2 1 0 0 1 -2 0A2 1 0 0 1 2 0");
// expect(ear.math.ellipse(2, 1, 5, 6).svgPath()).toBe("M7 6A2 1 0 0 1 3 6A2 1 0 0 1 7 6");
// });
// test("points", () => {
// expect(ear.math.ellipse(2, 1).points().length).toBe(128);
// expect(ear.math.ellipse(2, 1).points(10).length).toBe(10);
// });
// test("polygon", () => {
// const result = ear.math.ellipse(2, 1).polygon();
// expect(result.length).toBe(128);
// expect(result[0][0]).toBeCloseTo(2);
// expect(result[0][1]).toBeCloseTo(0);
// });
// test("segments", () => {
// const result = ear.math.ellipse(2, 1).segments();
// expect(result.length).toBe(128);
// expect(result[0][0][0]).toBeCloseTo(2);
// expect(result[0][0][1]).toBeCloseTo(0);
// });
================================================
FILE: tests/math.primitives.json.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("excluding primitives", () => expect(true).toBe(true));
// test("vector", () => {
// const v = JSON.stringify(ear.math.vector(1, 2, 3));
// expect(v).toBe(`{"0":1,"1":2,"2":3,"length":3}`);
// });
// test("circle", () => {
// const c = JSON.stringify(ear.math.circle(1, 2, 3));
// expect(c).toBe(`{"radius":3,"origin":{"0":1,"1":2,"length":2}}`);
// });
================================================
FILE: tests/math.primitives.junction.test.js
================================================
import { expect, test } from "vitest";
// import ear from "../src/index.js";
test("empty", () => { expect(true).toBe(true); });
/*
test("getters", () => {
const junction = ear.math.junction([1, 0], [0, 1], [-1, 0]);
expect(junction.order.length).toBe(3);
expect(junction.radians.length).toBe(3);
expect(junction.vectors.length).toBe(3);
expect(junction.sectors.length).toBe(3);
});
test("alternating angle sum", () => {
const junction = ear.math.junction([1, 0], [0, 1], [-1, 0], [0, -1]);
const res = junction.alternatingAngleSum();
expect(res[0]).toBe(Math.PI);
expect(res[1]).toBe(Math.PI);
});
test("alternating angle 3", () => {
const junction = ear.math.junction([1, 0], [0, 1], [-1, 0]);
const res = junction.alternatingAngleSum();
expect(res[0]).toBe(Math.PI / 2 * 3);
expect(res[1]).toBe(Math.PI / 2);
});
test("static fromRadians 1", () => {
const junction = ear.math.junction.fromRadians(0, 1, 2);
expect(ear.math.equivalent_vectors(junction.radians, [0, 1, 2])).toBe(true);
});
test("static fromRadians 2", () => {
const junction = ear.math.junction.fromRadians(Math.PI/2, Math.PI, Math.PI/2*3);
expect(junction.vectors[0].x).toBeCloseTo(0);
expect(junction.vectors[0].y).toBeCloseTo(1);
expect(junction.vectors[1].x).toBeCloseTo(-1);
expect(junction.vectors[1].y).toBeCloseTo(0);
expect(junction.vectors[2].x).toBeCloseTo(0);
expect(junction.vectors[2].y).toBeCloseTo(-1);
});
*/
================================================
FILE: tests/math.primitives.line.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("excluding primitives", () => expect(true).toBe(true));
// const testEqual = function (...args) {
// expect(ear.math.equivalent(...args)).toBe(true);
// };
// test("arguments", () => {
// const l1 = ear.math.line(1);
// expect(l1.origin[0]).toBe(0);
// expect(l1.origin[1]).toBe(undefined);
// expect(l1.origin[2]).toBe(undefined);
// const l2 = ear.math.line(1, 2);
// expect(l2.origin[0]).toBe(0);
// expect(l2.origin[1]).toBe(0);
// expect(l2.origin[2]).toBe(undefined);
// const l3 = ear.math.line(1, 2, 3);
// expect(l3.origin[0]).toBe(0);
// expect(l3.origin[1]).toBe(0);
// expect(l3.origin[2]).toBe(0);
// });
// test("u d form", () => {
// const l1 = ear.math.line.fromNormalDistance({ normal: [1, 0], distance: 3 });
// expect(l1.vector.x).toBeCloseTo(0);
// expect(l1.vector.y).toBeCloseTo(-1);
// expect(l1.origin.x).toBeCloseTo(3);
// expect(l1.origin.y).toBeCloseTo(0);
// });
// // from the prototype
// test("isParallel", () => {
// const l = ear.math.line([0, 1], [2, 3]);
// expect(l.isParallel([0, -1], [7, 8])).toBe(true);
// });
// test("isDegenerate", () => {
// const l = ear.math.line([0, 0], [2, 3]);
// expect(l.isDegenerate()).toBe(true);
// });
// test("reflection", () => {
// const result = ear.math.line([0, 1], [2, 3]).reflectionMatrix();
// expect(result[0]).toBeCloseTo(-1);
// expect(result[1]).toBeCloseTo(0);
// expect(result[2]).toBeCloseTo(0);
// expect(result[3]).toBeCloseTo(0);
// expect(result[4]).toBeCloseTo(1);
// expect(result[9]).toBeCloseTo(4);
// expect(result[10]).toBeCloseTo(0);
// // expect(l.reflection().origin).toBe();
// });
// test("nearestPoint", () => {
// const res = ear.math.line([1, 1], [2, 3]).nearestPoint(0, 0);
// expect(res[0]).toBe(-0.5);
// expect(res[1]).toBe(0.5);
// // expect(l.nearestPoint(0,0)).toBe(true);
// });
// test("transform", () => {
// const res = ear.math.line([0, 1], [2, 3]).transform([2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0]);
// expect(res.vector[0]).toBeCloseTo(0);
// expect(res.vector[1]).toBeCloseTo(2);
// expect(res.origin[0]).toBeCloseTo(4);
// expect(res.origin[1]).toBeCloseTo(6);
// });
// test("intersect", () => {
// const polygon = ear.math.polygon([0, 1.15], [-1, -0.577], [1, -0.577]);
// const circle = ear.math.circle(1);
// const line = ear.math.line([1, 2], [-0.5, 0]);
// const line2 = ear.math.line([-1, 2], [0.5, 0]);
// const ray = ear.math.ray([-1, 2], [0.5, 0]);
// const segment = ear.math.segment([-2, 0.5], [2, 0.5]);
// [
// line.intersect(polygon),
// line.intersect(circle),
// line.intersect(line2),
// line.intersect(ray),
// line.intersect(segment),
// ].forEach(intersect => expect(intersect).not.toBe(undefined));
// });
// // todo problems
// test("bisect", () => {
// expect(true).toBe(true);
// const l0 = ear.math.line([0, 1], [0, 0]);
// const l1 = ear.math.line([0, 1], [1, 0]);
// const res = l0.bisect(l1);
// // console.log("Bisec", res);
// // expect(l.bisectLine()).toBe(true);
// });
// // line
// test("fromPoints", () => {
// const result = ear.math.line.fromPoints([1, 2], [3, 4]);
// expect(result.origin.x).toBe(1);
// expect(result.origin.y).toBe(2);
// expect(result.vector.x).toBe(2);
// expect(result.vector.y).toBe(2);
// });
// test("perpendicularBisector", () => {
// const result = ear.math.line.perpendicularBisector([0, 1], [2, 3]);
// expect(result.origin.x).toBe(1);
// expect(result.origin.y).toBe(2);
// expect(result.vector.x).toBe(-2);
// expect(result.vector.y).toBe(2);
// });
// // this is no longer a property
// // test("length infinity", () => {
// // expect(ear.math.line().length).toBe(Infinity);
// // expect(ear.math.line([1,2],[3,4]).length).toBe(Infinity);
// // expect(ear.math.line.fromPoints([1,2],[3,4]).length).toBe(Infinity);
// // expect(ear.math.ray().length).toBe(Infinity);
// // expect(ear.math.ray([1,2],[3,4]).length).toBe(Infinity);
// // expect(ear.math.ray.fromPoints([1,2],[3,4]).length).toBe(Infinity);
// // });
// // // ray
// // test("transform", () => {
// // const r = ear.math.ray(0,1,2,3);
// // expect(r.transform()).toBe(true);
// // });
// test("ray", () => {
// const result = ear.math.ray([1, 2], [3, 3]);
// expect(result.origin.x).toBe(3);
// expect(result.origin.y).toBe(3);
// expect(result.vector.x).toBe(1);
// expect(result.vector.y).toBe(2);
// });
// test("flip", () => {
// const result = ear.math.ray([1, 2], [3, 3]).flip();
// expect(result.origin.x).toBe(3);
// expect(result.origin.y).toBe(3);
// expect(result.vector.x).toBe(-1);
// expect(result.vector.y).toBe(-2);
// });
// test("scale", () => {
// const ray = ear.math.ray([6, 2], [3, 4]);
// const res = ray.scale(1 / 2);
// expect(res.vector.x).toBe(3);
// expect(res.vector.y).toBe(1);
// });
// test("normalize", () => {
// const ray = ear.math.ray([4, 4], [2, 3]);
// const res = ray.normalize();
// expect(res.vector.x).toBeCloseTo(Math.SQRT1_2);
// expect(res.vector.y).toBeCloseTo(Math.SQRT1_2);
// });
// test("fromPoints", () => {
// const result = ear.math.ray.fromPoints([1, 2], [3, 4]);
// expect(result.origin.x).toBe(1);
// expect(result.origin.y).toBe(2);
// expect(result.vector.x).toBe(2);
// expect(result.vector.y).toBe(2);
// });
// test("nearestPoint", () => {
// const result = ear.math.ray([1, 1], [2, 3]).nearestPoint(0, 0);
// expect(result[0]).toBe(2);
// expect(result[1]).toBe(3);
// const result2 = ear.math.ray([0, 1], [5, -5]).nearestPoint(0, 0);
// expect(result2[0]).toBe(5);
// expect(result2[1]).toBe(0);
// });
// // segment
// test("[0], [1]", () => {
// const result = ear.math.segment([1, 2], [3, 4]);
// expect(result[0][0]).toBe(1);
// expect(result[0][1]).toBe(2);
// expect(result[1][0]).toBe(3);
// expect(result[1][1]).toBe(4);
// });
// test("length", () => {
// const result = ear.math.segment([1, 2], [3, 4]);
// // the Array.prototype length property
// expect(result.length).toBe(2);
// // geometric length
// expect(result.magnitude).toBeCloseTo(Math.sqrt(2) * 2);
// });
// test("transform", () => {
// const result1 = ear.math.segment([1, 2], [3, 4]).transform(ear.math.matrix().scale([0.5, 0.5, 0.5]));
// expect(result1[0].x).toBe(0.5);
// expect(result1[0].y).toBe(1);
// expect(result1[1].x).toBe(1.5);
// expect(result1[1].y).toBe(2);
// });
// test("midpoint", () => {
// const result = ear.math.segment([1, 2], [3, 4]).midpoint();
// expect(result.x).toBe(2);
// expect(result.y).toBe(3);
// });
// test("fromPoints", () => {
// const result = ear.math.segment.fromPoints([1, 2], [3, 4]);
// expect(result[0].x).toBe(1);
// expect(result[0].y).toBe(2);
// expect(result[1].x).toBe(3);
// expect(result[1].y).toBe(4);
// });
// test("nearestPoint", () => {
// const res = ear.math.segment([1, 1], [2, 3]).nearestPoint(0, 0);
// expect(res[0]).toBe(1);
// expect(res[1]).toBe(1);
// });
// /**
// * lines, rays, segments
// */
// // test("line ray segment intersections", () => {
// // testEqual([5, 5], ear.math.line(0, 0, 1, 1).intersect(ear.math.line(10, 0, -1, 1)));
// // testEqual([5, 5], ear.math.line(0, 0, 1, 1).intersect(ear.math.ray(10, 0, -1, 1)));
// // testEqual([5, 5], ear.math.line(0, 0, 1, 1).intersect(ear.math.segment(10, 0, 0, 10)));
// // });
// // test("line ray segment parallel", () => {
// // testEqual(true, ear.math.line(0, 0, 1, 1).isParallel(ear.math.ray(10, 0, 1, 1)));
// // testEqual(true, ear.math.line(0, 0, -1, 1).isParallel(ear.math.segment(0, 0, -2, 2)));
// // testEqual(false, ear.math.line(0, 0, -1, 1).isParallel(ear.math.segment(10, 0, 1, 1)));
// // });
// // test("line ray segment reflection matrices", () => {
// // testEqual(
// // ear.math.line(10, 0, -1, 1).reflection(),
// // ear.math.ray(10, 0, -1, 1).reflection()
// // );
// // testEqual(
// // ear.math.segment(10, 0, 0, 10).reflection(),
// // ear.math.ray(10, 0, -1, 1).reflection()
// // );
// // });
// test("line ray segment nearest points", () => {
// // testEqual([20, -10], ear.math.line(10, 0, -1, 1).nearestPoint([20, -10]));
// // testEqual([-50, 60], ear.math.line(10, 0, -1, 1).nearestPoint([-10, 100]));
// // testEqual([10, 0], ear.math.ray(10, 0, -1, 1).nearestPoint([20, -10]));
// // testEqual([-50, 60], ear.math.ray(10, 0, -1, 1).nearestPoint([-10, 100]));
// // testEqual([10, 0], ear.math.segment(10, 0, 0, 10).nearestPoint([20, -10]));
// // testEqual([0, 10], ear.math.segment(10, 0, 0, 10).nearestPoint([-10, 100]));
// // testEqual(
// // ear.math.ray(10, 0, -1, 1).nearestPoint([0, 0]),
// // ear.math.line(10, 0, -1, 1).nearestPoint([0, 0])
// // );
// // testEqual(
// // ear.math.segment(10, 0, 0, 10).nearestPoint([0, 0]),
// // ear.math.ray(10, 0, -1, 1).nearestPoint([0, 0])
// // );
// });
================================================
FILE: tests/math.primitives.matrix.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("excluding primitives", () => expect(true).toBe(true));
// test("copy", () => {
// const matrix = ear.math.matrix(1, 2, 3, 4, 5, 6, 7, 8, 9);
// const result = matrix.copy();
// matrix.set(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0);
// expect(result[3]).toBe(4);
// });
// test("set", () => {
// const matrix = ear.math.matrix(1, 2, 3, 4, 5, 6, 7, 8, 9);
// matrix.set(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0);
// expect(matrix[3]).toBe(0);
// });
// test("isIdentity", () => {
// expect(ear.math.matrix(1, 2, 3, 4, 5, 6, 7, 8, 9).isIdentity()).toBe(false);
// expect(ear.math.matrix().isIdentity()).toBe(true);
// expect(ear.math.matrix(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 5, 6).isIdentity()).toBe(false);
// expect(ear.math.matrix(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0).isIdentity()).toBe(true);
// });
// test("multiply", () => {
// const matrix = ear.math.matrix();
// const m = ear.math.matrix().multiply(ear.math.matrix().rotateX(Math.PI / 4).rotateZ(Math.PI / 4));
// const sq = Math.sqrt(2) / 2;
// [sq, 0.5, 0.5, -sq, 0.5, 0.5, 0, -sq, sq, 0, 0, 0]
// .forEach((a, i) => expect(a).toBeCloseTo(m[i]));
// });
// test("determinant", () => {
// expect(ear.math.matrix().determinant()).toBe(1);
// });
// test("inverse", () => {
// const m = ear.math.matrix(0, -1, 0, 1, 0, 0, 0, 0, 1).inverse();
// [0, 1, -0, -1, 0, 0, 0, -0, 1, 0, 0, 0].forEach((a, i) => expect(a).toBeCloseTo(m[i]));
// });
// test("translate", () => {
// expect(ear.math.matrix().translate(4, 5, 6)[9]).toBe(4);
// expect(ear.math.matrix().translate(4, 5, 6)[10]).toBe(5);
// expect(ear.math.matrix().translate(4, 5, 6)[11]).toBe(6);
// });
// test("rotateX", () => {
// const sq = Math.sqrt(2) / 2;
// const m = ear.math.matrix().rotateX(Math.PI / 4);
// [1, 0, 0, 0, sq, sq, 0, -sq, sq, 0, 0, 0].forEach((a, i) => expect(a).toBeCloseTo(m[i]));
// });
// test("rotateY", () => {
// const sq = Math.sqrt(2) / 2;
// const m = ear.math.matrix().rotateY(Math.PI / 4);
// [sq, 0, -sq, 0, 1, 0, sq, 0, sq, 0, 0, 0].forEach((a, i) => expect(a).toBeCloseTo(m[i]));
// });
// test("rotateZ", () => {
// const sq = Math.sqrt(2) / 2;
// const m = ear.math.matrix().rotateZ(Math.PI / 4);
// [sq, sq, 0, -sq, sq, 0, 0, 0, 1, 0, 0, 0].forEach((a, i) => expect(a).toBeCloseTo(m[i]));
// });
// test("rotate", () => {
// const m = ear.math.matrix().rotate(Math.PI / 2, [1, 1, 1], [0, 0, 0]);
// expect(m[2]).toBeCloseTo(m[3]);
// expect(m[0]).toBeCloseTo(m[4]);
// expect(m[1]).toBeCloseTo(m[5]);
// });
// test("scale", () => {
// expect(ear.math.matrix().scale([0.5, 0.5, 0.5])[0]).toBe(0.5);
// });
// test("combine operations", () => {
// const ident = ear.math.matrix();
// const result = ident.rotateX(Math.PI / 2).translate(40, 20, 10);
// [1, 0, 0, 0, 0, 1, 0, -1, 0, 40, -10, 20]
// .forEach((n, i) => expect(n).toBeCloseTo(result[i]));
// });
// test("reflectZ", () => {
// const m = ear.math.matrix().reflectZ([1, 1, 1], [0, 0, 0]);
// expect(m[1]).toBeCloseTo(m[3]);
// expect(m[0]).toBeCloseTo(m[4]);
// expect(m[2]).toBeCloseTo(m[5]);
// expect(m[5]).toBeCloseTo(m[6]);
// });
// test("transform", () => {
// const matrix = ear.math.matrix().rotateZ(Math.PI / 2).translate(4, 5, 6);
// const result = matrix.transform(ear.math.segment([-1, 0], [1, 0]));
// });
// test("transformVector", () => {
// const vector = ear.math.vector(1, 2, 3);
// expect(ear.math.matrix().scale([0.5, 0.5, 0.5]).transformVector(vector).x).toBeCloseTo(0.5);
// expect(ear.math.matrix().scale([0.5, 0.5, 0.5]).transformVector(vector).y).toBeCloseTo(1);
// expect(ear.math.matrix().scale([0.5, 0.5, 0.5]).transformVector(vector).z).toBeCloseTo(1.5);
// });
// test("transformLine", () => {
// const line = ear.math.line([0.707, 0.707, 0], [1, 0, 0]);
// const result = ear.math.matrix().scale([0.5, 0.5, 0.5]).transformLine(line);
// expect(result.vector.x).toBeCloseTo(0.3535);
// expect(result.vector.y).toBeCloseTo(0.3535);
// expect(result.vector.z).toBeCloseTo(0);
// expect(result.origin.x).toBeCloseTo(0.5);
// expect(result.origin.y).toBeCloseTo(0);
// expect(result.origin.z).toBeCloseTo(0);
// });
// // test("transformLine with 2D vectors", () => {
// // const vector = ear.math.line([0.707, 0.707], [1, 0]);
// // console.log(ear.math.matrix().scale(0.5).transformLine(vector));
// // });
// const testEqualVectors = function (...args) {
// expect(ear.math.epsilonEqualVectors(...args)).toBe(true);
// };
// const sqrt05 = Math.sqrt(0.5);
// /**
// * matrices
// */
// test("matrix 2 core", () => {
// expect(ear.math.invertMatrix2([1, 0, 0, 1, 0, 0])).not.toBe(undefined);
// const r1 = ear.math.makeMatrix2Translate();
// expect(r1[0]).toBe(1);
// expect(r1[4]).toBe(0);
// expect(r1[5]).toBe(0);
// const r2 = ear.math.makeMatrix2Scale([2, -1]);
// expect(r2[0]).toBe(2);
// expect(r2[3]).toBe(-1);
// });
// test("matrix core invert", () => {
// expect(ear.math.invertMatrix2([1, 0, 0, 1, 0, 0])).not.toBe(undefined);
// expect(ear.math.invertMatrix3([1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0])).not.toBe(undefined);
// expect(ear.math.invertMatrix2([5, 5, 4, 4, 3, 3])).toBe(undefined);
// expect(ear.math.invertMatrix3([0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1])).toBe(undefined);
// });
// test("matrix 3, init with parameters", () => {
// const result1 = ear.math.matrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
// testEqualVectors(result1, [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]);
// const result2 = ear.math.matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
// testEqualVectors(result2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
// const result3 = ear.math.matrix(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
// testEqualVectors(result3, [1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15]);
// });
// // todo: test matrix3 methods (invert) with the translation component to make sure it carries over
// test("matrix 3 core, transforms", () => {
// const result1 = ear.math.makeMatrix3Translate();
// [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0].forEach((n, i) => expect(n).toBe(result1[i]));
// // rotate 360 degrees about an arbitrary axis and origin
// testEqualVectors(
// [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
// ear.math.makeMatrix3Rotate(
// Math.PI * 2,
// [Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5],
// [Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5],
// ),
// );
// testEqualVectors(
// ear.math.makeMatrix3RotateX(Math.PI / 6),
// ear.math.makeMatrix3Rotate(Math.PI / 6, [1, 0, 0]),
// );
// testEqualVectors(
// ear.math.makeMatrix3RotateY(Math.PI / 6),
// ear.math.makeMatrix3Rotate(Math.PI / 6, [0, 1, 0]),
// );
// testEqualVectors(
// ear.math.makeMatrix3RotateZ(Math.PI / 6),
// ear.math.makeMatrix3Rotate(Math.PI / 6, [0, 0, 1]),
// );
// // source wikipedia https://en.wikipedia.org/wiki/Rotation_matrix#Examples
// const exampleMat = [
// 0.35612209405955486, -0.8018106071106572, 0.47987165414043453,
// 0.47987165414043464, 0.5975763087872217, 0.6423595182829954,
// -0.8018106071106572, 0.0015183876574496047, 0.5975763087872216,
// 0, 0, 0,
// ];
// testEqualVectors(
// exampleMat,
// ear.math.makeMatrix3Rotate((-74 / 180) * Math.PI, [-1 / 3, 2 / 3, 2 / 3]),
// );
// testEqualVectors(
// exampleMat,
// ear.math.makeMatrix3Rotate((-74 / 180) * Math.PI, [-0.5, 1, 1]),
// );
// testEqualVectors(
// [1, 0, 0, 0, 0.8660254, 0.5, 0, -0.5, 0.8660254, 0, 0, 0],
// ear.math.makeMatrix3Rotate(Math.PI / 6, [1, 0, 0]),
// );
// });
// test("matrix 3 core", () => {
// expect(ear.math.determinant3([1, 2, 3, 2, 4, 8, 7, 8, 9])).toBe(12);
// expect(ear.math.determinant3([3, 2, 0, 0, 0, 1, 2, -2, 1, 0, 0, 0])).toBe(10);
// testEqualVectors(
// [4, 5, -8, -5, -6, 9, -2, -2, 3, 0, 0, 0],
// ear.math.invertMatrix3([0, 1, -3, -3, -4, 4, -2, -2, 1, 0, 0, 0]),
// );
// testEqualVectors(
// [0.2, -0.2, 0.2, 0.2, 0.3, -0.3, 0, 1, 0, 0, 0, 0],
// ear.math.invertMatrix3([3, 2, 0, 0, 0, 1, 2, -2, 1, 0, 0, 0]),
// );
// const mat_3d_ref = ear.math.makeMatrix3ReflectZ([1, -2], [12, 13]);
// testEqualVectors(
// ear.math.makeMatrix2Reflect([1, -2], [12, 13]),
// [mat_3d_ref[0], mat_3d_ref[1], mat_3d_ref[3], mat_3d_ref[4], mat_3d_ref[9], mat_3d_ref[10]],
// );
// // source wolfram alpha
// testEqualVectors(
// [-682, 3737, -5545, 2154, -549, -1951, 953, -3256, 4401, 0, 0, 0],
// ear.math.multiplyMatrices3(
// [5, -52, 85, 15, -9, -2, 32, 2, -50, 0, 0, 0],
// [-77, 25, -21, 3, 53, 42, 63, 2, 19, 0, 0, 0],
// ),
// );
// });
// // matrix 2 has been depricated as a top-level object
// //
// // test("matrix 2", () => {
// // // top level types
// // testEqualVectors([1, 2, 3, 4, 5, 6], ear.math.matrix2(1, 2, 3, 4, 5, 6));
// // testEqualVectors([1, 0, 0, 1, 6, 7], ear.math.matrix2.makeTranslation(6, 7));
// // testEqualVectors([3, 0, 0, 3, -2, 0], ear.math.matrix2.makeScale(3, 3, [1, 0]));
// // testEqualVectors([0, 1, 1, -0, -8, 8], ear.math.matrix2.makeReflection([1, 1], [-5, 3]));
// // testEqualVectors(
// // [sqrt05, sqrt05, -sqrt05, sqrt05, 1, 1],
// // ear.math.matrix2.makeRotation(Math.PI/4, [1, 1])
// // );
// // testEqualVectors(
// // [sqrt05, -sqrt05, sqrt05, sqrt05, -sqrt05, sqrt05],
// // ear.math.matrix2(sqrt05, sqrt05, -sqrt05, sqrt05, 1, 0).inverse()
// // );
// // testEqualVectors(
// // [Math.sqrt(4.5), sqrt05, -sqrt05, Math.sqrt(4.5), Math.sqrt(4.5), sqrt05],
// // ear.math.matrix2(sqrt05, -sqrt05, sqrt05, sqrt05, 0, 0)
// // .multiply(ear.math.matrix2(1, 2, -2, 1, 1, 2))
// // );
// // testEqualVectors([0, 3], ear.math.matrix2(2, 1, -1, 2, -1, 0).transform(1, 1));
// // testEqualVectors([-2, 3], ear.math.matrix2.makeScale(3, 3, [1, 0]).transform([0, 1]));
// // testEqualVectors([-1, 2], ear.math.matrix2.makeScale(3, 3, [0.5, 0.5]).transform([0, 1]));
// // testEqualVectors([1, 1], ear.math.matrix2.makeScale(0.5, 0.5, [1, 1]).transform([1, 1]));
// // testEqualVectors([0.75, 0.75], ear.math.matrix2.makeScale(0.5, 0.5, [0.5, 0.5]).transform([1, 1]));
// // });
================================================
FILE: tests/math.primitives.paths.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("excluding primitives", () => expect(true).toBe(true));
// test("segment", () => {
// expect(ear.math.segment(1, 2, 3, 4).svgPath()).toBe("M1 2L3 4");
// });
// test("line", () => {
// expect(ear.math.line(1, 2).svgPath()).toBe("M-10000 -20000l20000 40000");
// expect(ear.math.line(1, 2).svgPath(20)).toBe("M-10 -20l20 40");
// });
// test("ray", () => {
// expect(ear.math.ray(1, 2).svgPath()).toBe("M0 0l10000 20000");
// expect(ear.math.ray(1, 2).svgPath(10)).toBe("M0 0l10 20");
// });
// test("rect", () => {
// expect(ear.math.rect(1, 2).svgPath()).toBe("M0 0h1v2h-1Z");
// });
// test("circle", () => {
// expect(ear.math.circle(4).svgPath()).toBe("M4 0A4 4 0 0 1 -4 0A4 4 0 0 1 4 0");
// });
// test("ellipse", () => {
// expect(ear.math.ellipse(1, 2).svgPath()).toBe("M1 0A1 2 0 0 1 -1 0A1 2 0 0 1 1 0");
// expect(ear.math.ellipse(1, 2).svgPath(-Math.PI).slice(0, 4)).toBe("M-1 ");
// expect(ear.math.ellipse(1, 2).svgPath(-Math.PI * 2)).toBe("M1 0A1 2 0 0 1 -1 0A1 2 0 0 1 1 0");
// });
// test("polygon", () => {
// expect(ear.math.polygon([1, 0], [0, 1], [-1, 0], [0, -1]).svgPath())
// .toBe("M1 0L0 1L-1 0L0 -1z");
// });
================================================
FILE: tests/math.primitives.polygon.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("excluding primitives", () => expect(true).toBe(true));
// const equalTest = (a, b) => expect(JSON.stringify(a))
// .toBe(JSON.stringify(b));
// test("prototype member variables accessing 'this'", () => {
// expect(ear.math.makePolygonCircumradius(4).sides.length).toBe(4);
// expect(ear.math.makePolygonCircumradius(4).area()).toBeCloseTo(2);
// });
// // todo: convex
// test("isConvex", () => {
// expect(ear.math.makePolygonCircumradius(4).isConvex).toBe(undefined);
// });
// test(".segments", () => {
// const polygon = ear.math.makePolygonCircumradius(4);
// const segments = polygon.segments();
// expect(segments.length).toBe(4);
// expect(polygon.sides[0]).toBe(polygon.segments()[0]);
// });
// test("intersect", () => {
// const polygon = ear.math.makePolygonCircumradius(4);
// const segment = ear.math.intersectLineLine(polygon, [1, 1], [0, 0]).point;
// expect(Math.abs(segment[0][0])).toBe(0.5);
// expect(Math.abs(segment[0][1])).toBe(0.5);
// expect(Math.abs(segment[1][0])).toBe(0.5);
// expect(Math.abs(segment[1][1])).toBe(0.5);
// });
// test("area", () => {
// expect(ear.math.polygon([-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]).area()).toBeCloseTo(1);
// });
// test("convex Hull", () => {
// const result = ear.math.polygon.convexHull([[1, 0], [0.5, 0], [0, 1], [0, -1]]);
// expect(result.points.length).toBe(3);
// });
// test("skeleton", () => {
// const hull = ear.math.polygon.convexHull(Array.from(Array(10))
// .map(() => [Math.random(), Math.random()]));
// const skeleton = hull.straightSkeleton();
// const skeletons = skeleton.filter(el => el.type === "skeleton");
// const perpendiculars = skeleton.filter(el => el.type === "perpendicular");
// expect(skeletons.length).toBe((hull.length - 3) * 2 + 3);
// expect(perpendiculars.length).toBe(hull.length - 2);
// });
// // test("midpoint", () => {
// // const result = ear.math.polygon([-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]).midpoint();
// // expect(result[0]).toBeCloseTo(0);
// // expect(result[1]).toBeCloseTo(0);
// // });
// test("centroid", () => {
// const result = ear.math.polygon([1, 0], [0, 1], [-1, 0]).centroid();
// expect(result[0]).toBeCloseTo(0);
// expect(result[1]).toBeCloseTo(1 / 3);
// });
// test("boundingBox", () => {
// const box = ear.math.polygon([[1, 0], [0, 1], [-1, 0], [0, -1]]).boundingBox();
// expect(box.min[0]).toBe(-1);
// expect(box.min[1]).toBe(-1);
// expect(box.span[0]).toBe(2);
// expect(box.span[1]).toBe(2);
// });
// test("contains", () => {
// expect(ear.math.polygon([[1, 0], [0, 1], [-1, 0], [0, -1]]).overlap(ear.math.vector(0.49, 0.49)))
// .toBe(true);
// expect(ear.math.polygon([[1, 0], [0, 1], [-1, 0], [0, -1]]).overlap(ear.math.vector(0.5, 0.5)))
// .toBe(true);
// expect(ear.math.polygon([[1, 0], [0, 1], [-1, 0], [0, -1]]).overlap(ear.math.vector(0.51, 0.51)))
// .toBe(false);
// });
// test("scale", () => {
// const result = ear.math.polygon([-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]).scale(2);
// expect(result.points[0][0]).toBeCloseTo(-1);
// expect(result.points[0][1]).toBeCloseTo(-1);
// });
// test("rotate", () => {
// const sq = Math.sqrt(2) / 2;
// const result = ear.math.polygon([-sq, -sq], [sq, -sq], [sq, sq], [-sq, sq]).rotate(Math.PI / 4);
// expect(result.points[0][0]).toBeCloseTo(0);
// expect(result.points[0][1]).toBeCloseTo(-1);
// });
// test("translate", () => {
// const result = ear.math.polygon([[1, 0], [0, 1], [-1, 0], [0, -1]]).translate(Math.PI / 2);
// });
// test("transform", () => {
// const matrix = ear.math.matrix(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 5, 0);
// const result = ear.math.polygon([-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]).transform(matrix);
// expect(result.points[0][0]).toBeCloseTo(3.5);
// expect(result.points[0][1]).toBeCloseTo(4.5);
// });
// // test("sectors", () => {
// // const result = ear.math.polygon([[1, 0], [0, 1], [-1, 0], [0, -1]]).sectors();
// // console.log("sectors", result);
// // });
// test("nearest", () => {
// const result = ear.math.polygon([[1, 0], [0, 1], [-1, 0], [0, -1]]).nearest(10, 10);
// expect(result.point[0]).toBe(0.5);
// expect(result.point[1]).toBe(0.5);
// expect(result.distance).toBeCloseTo(13.435028842544403);
// expect(result.edge[0][0]).toBeCloseTo(1);
// expect(result.edge[0][1]).toBeCloseTo(0);
// });
// test("overlap", () => {
// const poly1 = ear.math.polygon([[1, 0], [0, 1], [-1, 0]]); // top
// const poly2 = ear.math.polygon([[0, 1], [-1, 0], [0, -1]]); // left
// const poly3 = ear.math.polygon([[1, 0], [0, 1], [0, -1]]); // right
// const poly4 = ear.math.polygon([[1, 0], [-1, 0], [0, -1]]); // bottom
// expect(poly1.overlap(poly2)).toBe(true);
// expect(poly1.overlap(poly3)).toBe(true);
// expect(poly4.overlap(poly2)).toBe(true);
// expect(poly4.overlap(poly3)).toBe(true);
// expect(poly2.overlap(poly3)).toBe(false);
// expect(poly1.overlap(poly4)).toBe(false);
// });
// test("split", () => {
// const poly = ear.math.polygon([[1, 0], [0, 1], [-1, 0]]);
// const line1 = ear.math.line([1, 0], [0, 0.5]);
// const line2 = ear.math.line([1, 0], [0, -0.5]);
// const result1 = poly.split(line1);
// expect(result1[0][0][0]).toBe(-1);
// expect(result1[0][0][1]).toBe(0);
// expect(result1[0][1][0]).toBe(1);
// expect(result1[0][1][1]).toBe(0);
// expect(result1[0][2][0]).toBe(0.5);
// expect(result1[0][2][1]).toBe(0.5);
// expect(result1[0][3][0]).toBe(-0.5);
// expect(result1[0][3][1]).toBe(0.5);
// expect(result1[1][0][0]).toBe(0);
// expect(result1[1][0][1]).toBe(1);
// expect(result1[1][1][0]).toBe(-0.5);
// expect(result1[1][1][1]).toBe(0.5);
// expect(result1[1][2][0]).toBe(0.5);
// expect(result1[1][2][1]).toBe(0.5);
// });
// test("intersectLine", () => {
// const poly = ear.math.polygon([[1, 0], [0, 1], [-1, 0], [0, -1]]);
// const line = ear.math.line([1, 0], [0, 0.5]);
// const result = poly.intersect(line);
// expect(result[0][0]).toBeCloseTo(0.5);
// expect(result[0][1]).toBeCloseTo(0.5);
// });
// test("intersectRay", () => {
// const poly = ear.math.polygon([[1, 0], [0, 1], [-1, 0], [0, -1]]);
// const ray = ear.math.ray([1, 0], [0, 0.5]);
// const result = poly.intersect(ray);
// });
// test("intersectSegment", () => {
// const poly = ear.math.polygon([[1, 0], [0, 1], [-1, 0], [0, -1]]);
// const segment = ear.math.segment([-2, 0.5], [2, 0.5]);
// const result = poly.intersect(segment);
// expect(result[0][0]).toBeCloseTo(0.5);
// expect(result[0][1]).toBeCloseTo(0.5);
// expect(result[1][0]).toBeCloseTo(-0.5);
// expect(result[1][1]).toBeCloseTo(0.5);
// });
// // test("svgPath", () => {
// // svgPath: function ()
// // });
================================================
FILE: tests/math.primitives.rect.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("excluding primitives", () => expect(true).toBe(true));
// // static
// test("static fromPoints", () => {
// const r = ear.math.rect.fromPoints([1, 1], [3, 2]);
// expect(r.width).toBe(2);
// expect(r.height).toBe(1);
// });
// // native
// test("area", () => {
// const r = ear.math.rect(2, 3, 4, 5);
// expect(r.area()).toBe(4 * 5);
// });
// test("scale", () => {
// const r = ear.math.rect(2, 3, 4, 5);
// expect(r.scale(2).area()).toBe((4 * 2) * (5 * 2));
// });
// test("segments", () => {
// const r = ear.math.rect(2, 3, 4, 5);
// const seg = r.segments();
// expect(seg.length).toBe(4);
// });
// test("center", () => {
// const r = ear.math.rect(2, 3, 4, 5);
// expect(r.center.x).toBe(2 + 4 / 2);
// expect(r.center.y).toBe(3 + 5 / 2);
// });
// test("centroid", () => {
// const r = ear.math.rect(1, 2, 3, 4);
// const centroid = r.centroid();
// expect(centroid.x).toBe(1 + 3 / 2);
// expect(centroid.y).toBe(2 + 4 / 2);
// });
// test("boundingBox", () => {
// const r = ear.math.rect(1, 2, 3, 4);
// const bounds = r.boundingBox();
// expect(bounds.min[0]).toBe(1);
// expect(bounds.min[1]).toBe(2);
// expect(bounds.span[0]).toBe(3);
// expect(bounds.span[1]).toBe(4);
// });
// test("contains", () => {
// const r = ear.math.rect(1, 2, 3, 4);
// expect(r.overlap(ear.math.vector(0, 0))).toBe(false);
// expect(r.overlap(ear.math.vector(1.5, 3))).toBe(true);
// });
// test("svg", () => {
// const r = ear.math.rect(1, 2, 3, 4);
// expect(r.svgPath()).toBe("M1 2h3v4h-3Z");
// });
// // test("rotate", () => {
// // const r = ear.math.rect(1, 2, 3, 4);
// // r.rotate();
// // });
// // test("translate", () => {
// // const r = ear.math.rect(1, 2, 3, 4);
// // r.translate();
// // });
// // test("transform", () => {
// // const r = ear.math.rect(1, 2, 3, 4);
// // r.transform();
// // });
// // test("sectors", () => {
// // const r = ear.math.rect(1, 2, 3, 4);
// // r.sectors();
// // });
// // test("nearest", () => {
// // const r = ear.math.rect(1, 2, 3, 4);
// // r.nearest();
// // });
// // test("clipSegment", () => {
// // const r = ear.math.rect(1, 2, 3, 4);
// // r.clipSegment();
// // });
// // test("clipLine", () => {
// // const r = ear.math.rect(1, 2, 3, 4);
// // r.clipLine();
// // });
// // test("clipRay", () => {
// // const r = ear.math.rect(1, 2, 3, 4);
// // r.clipRay();
// // });
// // test("split", () => {
// // const r = ear.math.rect(1, 2, 3, 4);
// // r.split();
// // });
================================================
FILE: tests/math.primitives.types.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("excluding primitives", () => expect(true).toBe(true));
// const names = [
// "vector",
// "matrix",
// "segment",
// "ray",
// "line",
// "rect",
// "circle",
// "ellipse",
// "polygon",
// // "junction",
// ];
// const primitives = names
// .map(key => ear.math[key]());
// test("primitive constructor function names", () => primitives
// .forEach((primitive, i) => expect(primitive.constructor.name)
// .toBe(names[i])));
// test("primitives Typeof", () => primitives
// .forEach((primitive, i) => expect(ear.math.typeof(primitive))
// .toBe(names[i])));
// test("primitives instanceof", () => primitives
// .forEach((primitive, i) => expect(primitive instanceof ear.math[names[i]])
// .toBe(true)));
// test("primitives constructor", () => primitives
// .forEach((primitive, i) => expect(primitive.constructor === ear.math[names[i]])
// .toBe(true)));
// test("interchangeability with get_", () => {
// const vector = ear.math.vector(1, 2, 3);
// const matrix = ear.math.matrix(1, 2, 3, 4);
// const line = ear.math.line(1, 2);
// const ray = ear.math.ray(1, 2);
// const segment = ear.math.segment([1, 2], [3, 4]);
// const circle = ear.math.circle(1);
// const rect = ear.math.rect(2, 4);
// const ellipse = ear.math.ellipse(1, 2);
// expect(ear.math.getVector(vector)[2]).toBe(3);
// // expect(ear.math.getVectorOfVectors(segment)[0]).toBe(1);
// expect(ear.math.getSegment(segment)[0][1]).toBe(2);
// expect(ear.math.getLine(line).vector[1]).toBe(2);
// expect(ear.math.getRect(rect).height).toBe(4);
// expect(ear.math.getMatrix3x4(matrix)[4]).toBe(4);
// // expect(ear.math.get_matrix2(matrix)[1]).toBe(2);
// });
================================================
FILE: tests/math.primitives.vector.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("excluding primitives", () => expect(true).toBe(true));
// test("arguments", () => {
// expect(ear.math.vector(1, 2, 3)[2]).toBe(3);
// expect(ear.math.vector([1, 2, 3])[2]).toBe(3);
// expect(ear.math.vector([[1, 2, 3]])[2]).toBe(3);
// expect(ear.math.vector([[], [1, 2, 3]])[2]).toBe(3);
// expect(ear.math.vector([[1], [2], [3]])[2]).toBe(3);
// expect(ear.math.vector({ x: 1, y: 2, z: 3 })[2]).toBe(3);
// expect(ear.math.vector([{ x: 1, y: 2, z: 3 }])[2]).toBe(3);
// expect(ear.math.vector([[{ x: 1, y: 2, z: 3 }]])[2]).toBe(3);
// expect(ear.math.vector([[], { x: 1, y: 2, z: 3 }])[2]).toBe(3);
// });
// // static
// test("static", () => {
// expect(ear.math.vector.fromAngle(Math.PI).x).toBeCloseTo(-1);
// expect(ear.math.vector.fromAngle(Math.PI).y).toBeCloseTo(0);
// expect(ear.math.vector.fromAngle(Math.PI).z).toBe(undefined);
// expect(ear.math.vector.fromAngleDegrees(90).x).toBeCloseTo(0);
// expect(ear.math.vector.fromAngleDegrees(90).y).toBeCloseTo(1);
// expect(ear.math.vector.fromAngleDegrees(90).z).toBe(undefined);
// });
// // methods
// test("magnitude", () => {
// const v = ear.math.vector(1, 2, 3).normalize();
// expect(v.magnitude()).toBe(1);
// });
// test("normalize", () => {
// const v = ear.math.vector(0).normalize();
// expect(v.magnitude()).toBe(0);
// // normalize appears so many places in these tests...
// });
// test("isEquivalent", () => {
// const v = ear.math.vector(1, 2, 3);
// expect(v.isEquivalent([1, 2, 2.99999999])).toBe(true);
// expect(v.isEquivalent([1, 2, 2.9999999])).toBe(true);
// // this is where the current epsilon is
// expect(v.isEquivalent([1, 2, 2.999999])).toBe(false);
// expect(v.isEquivalent([1, 2])).toBe(false);
// expect(v.isEquivalent([1, 2, 0])).toBe(false);
// expect(v.isEquivalent([1, 2, 3, 4])).toBe(false);
// });
// test("isParallel", () => {
// const v = ear.math.vector(1, 2, 3).normalize();
// expect(v.isParallel([-1, -2, -3])).toBe(true);
// });
// test("dot", () => {
// const v = ear.math.vector(1, 2);
// expect(v.dot([-2, 1])).toBe(0);
// });
// test("distanceTo", () => {
// const v = ear.math.vector(3, 0);
// expect(v.distanceTo([-3, 0])).toBe(6);
// });
// test("bisect", () => {
// expect(ear.math.vector(1, 0).bisect(ear.math.vector(0, 1)).x)
// .toBeCloseTo(Math.sqrt(2) / 2);
// expect(ear.math.vector(1, 0).bisect(ear.math.vector(0, 1)).y)
// .toBeCloseTo(Math.sqrt(2) / 2);
// });
// test("copy", () => {
// const v = ear.math.vector(1, 2, 3);
// expect(v.copy().z).toBe(3);
// });
// test("scale", () => {
// const v = ear.math.vector(2, -3);
// expect(v.scale(2).x).toBe(4);
// expect(v.scale(2).y).toBe(-6);
// expect(v.scale(-2).x).toBe(-4);
// expect(v.scale(-2).y).toBe(6);
// expect(v.scale(0).x).toBeCloseTo(0);
// expect(v.scale(0).y).toBeCloseTo(0);
// });
// test("cross", () => {
// const v = ear.math.vector(1, 2, 3).normalize();
// let w = ear.math.vector(3, 4).normalize();
// // [0, 0, 0.8]
// expect(0.8 - w.cross(2, 4)[2]).toBeLessThan(1e-6);
// expect(w.cross(2, -4, 5)[0]).toBe(4);
// expect(w.cross(2, -4, 5)[1]).toBe(-3);
// expect(w.cross(2, -4, 5)[2]).toBe(-4);
// expect(w.cross(2, -4)[2]).toBe(-4);
// });
// test("add", () => {
// const v = ear.math.vector(1, 2, 3);
// for (let i = 0; i < v.length; i += 1) {
// expect(v.add([-1, 2, 3])[i]).toBe([0, 4, 6][i]);
// }
// for (let i = 0; i < v.length; i += 1) {
// expect(v.add([-1, 2])[i]).toBe([0, 4, 3][i]);
// }
// });
// test("subtract", () => {
// const v = ear.math.vector(1, 2, 3);
// for (let i = 0; i < v.length; i += 1) {
// expect(v.subtract([-1, 2, 3])[i]).toBe([2, 0, 0][i]);
// }
// for (let i = 0; i < v.length; i += 1) {
// expect(v.subtract([-1, 2])[i]).toBe([2, 0, 3][i]);
// }
// });
// test("rotate90", () => {
// const v = ear.math.vector(1, 2, 3);
// expect(v.rotate90().x).toBe(-2);
// expect(v.rotate90().y).toBe(1);
// expect(v.rotate90().z).toBe(undefined);
// });
// test("rotate270", () => {
// const v = ear.math.vector(1, 2, 3);
// expect(v.rotate270().x).toBe(2);
// expect(v.rotate270().y).toBe(-1);
// expect(v.rotate270().z).toBe(undefined);
// });
// test("flip", () => {
// const v = ear.math.vector(1, 2, 3);
// expect(v.flip().x).toBe(-1);
// expect(v.flip().y).toBe(-2);
// expect(v.flip().z).toBe(-3);
// });
// test("lerp", () => {
// const v = ear.math.vector(2, 0);
// expect(v.lerp([-2, 0], 0.5)[0]).toBe(0);
// expect(v.lerp([-2, 0], 0.25)[0]).toBe(1);
// expect(v.lerp([-2, 0], 0.75)[0]).toBe(-1);
// expect(v.lerp([-2], 0.25)[0]).toBe(1);
// expect(v.lerp([-2], 0.75)[0]).toBe(-1);
// });
// test("midpoint", () => {
// const v = ear.math.vector(1, 2, 3);
// expect(v.midpoint([1, 2])[2]).toBe(1.5);
// expect(v.midpoint([1, 2, 10]).x).toBe(1);
// expect(v.midpoint([1, 2, 10]).y).toBe(2);
// expect(v.midpoint([1, 2, 10]).z).toBe(6.5);
// expect(v.midpoint([1, 2, 10, 20])[3]).toBe(10);
// expect(v.midpoint([1]).y).toBe(1);
// expect(v.midpoint([]).z).toBe(1.5);
// });
// test("transform", () => {
// const v = ear.math.vector(1, 2);
// expect(v.transform(1, 0, 0, 0, 1, 0, 0, 0, 1).x).toBe(1);
// expect(v.transform(1, 0, 0, 0, 1, 0, 0, 0, 1).y).toBe(2);
// // rotate around x
// expect(v.transform(1, 0, 0, 0, 0, -1, 0, 1, 0).x).toBe(1);
// expect(v.transform(1, 0, 0, 0, 0, -1, 0, 1, 0).y).toBe(0);
// expect(v.transform(1, 0, 0, 0, 0, -1, 0, 1, 0).z).toBe(-2);
// // rotate around z
// expect(v.transform(0, -1, 0, 1, 0, 0, 0, 0, 1).x).toBe(2);
// expect(v.transform(0, -1, 0, 1, 0, 0, 0, 0, 1).y).toBe(-1);
// expect(v.transform(0, -1, 0, 1, 0, 0, 0, 0, 1).z).toBe(0);
// // rotate 2D
// expect(v.transform(0, -1, 1, 0).x).toBe(2);
// expect(v.transform(0, -1, 1, 0).y).toBe(-1);
// });
// test("rotateZ", () => {
// const v = ear.math.vector(1);
// expect(v.rotateZ(Math.PI / 2).x).toBeCloseTo(0);
// expect(v.rotateZ(Math.PI / 2).y).toBeCloseTo(1);
// expect(v.rotateZ(-Math.PI / 2).x).toBeCloseTo(0);
// expect(v.rotateZ(-Math.PI / 2).y).toBeCloseTo(-1);
// });
================================================
FILE: tests/math.range.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("rangesOverlapExclusive", () => {
// default is exclusive
expect(ear.math.doRangesOverlap([0, 1], [1, 2])).toBe(false);
// negative epsilon is inclusive
expect(ear.math.doRangesOverlap([0, 1], [1, 2], -1e-6)).toBe(true);
// order does not matter
expect(ear.math.doRangesOverlap([1, 0], [1, 2], 1e-6)).toBe(false);
expect(ear.math.doRangesOverlap([1, 0], [2, 1], 1e-6)).toBe(false);
expect(ear.math.doRangesOverlap([1, 0], [1, 2], -1e-6)).toBe(true);
expect(ear.math.doRangesOverlap([1, 0], [2, 1], -1e-6)).toBe(true);
// negative numbers
expect(ear.math.doRangesOverlap([-10, -9], [-9, -8], 1e-6)).toBe(false);
expect(ear.math.doRangesOverlap([-10, -9], [-9, -8], -1e-6)).toBe(true);
// same ranges
expect(ear.math.doRangesOverlap([2, 3], [2, 3], 1e-6)).toBe(true);
expect(ear.math.doRangesOverlap([2, 3], [2, 3], -1e-6)).toBe(true);
expect(ear.math.doRangesOverlap([2, 3], [3, 2], 1e-6)).toBe(true);
expect(ear.math.doRangesOverlap([2, 3], [3, 2], -1e-6)).toBe(true);
expect(ear.math.doRangesOverlap([-2, -3], [-2, -3], 1e-6)).toBe(true);
expect(ear.math.doRangesOverlap([-2, -3], [-2, -3], -1e-6)).toBe(true);
expect(ear.math.doRangesOverlap([-2, -3], [-3, -2], 1e-6)).toBe(true);
expect(ear.math.doRangesOverlap([-2, -3], [-3, -2], -1e-6)).toBe(true);
});
================================================
FILE: tests/prototypes.cp.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("deprecated", () => expect(true).toBe(true));
// test("methods", () => {
// const cp = ear.cp();
// cp.ray([Math.random(), Math.random()]);
// const two = cp.clone();
// expect(two.edges_vertices.length).toBe(cp.edges_vertices.length);
// cp.segment([Math.random(), Math.random()], [Math.random(), Math.random()]);
// expect(two.edges_vertices.length).not.toBe(cp.edges_vertices.length);
// });
// test("cp draw methods", () => {
// const cp = ear.cp();
// cp.line([Math.random() - 0.5, Math.random() - 0.5], [0.5, 0.5]);
// cp.segment([Math.random(), Math.random()], [Math.random(), Math.random()]);
// cp.ray([Math.random(), Math.random()]);
// // cp.circle(Math.random());
// // cp.rect(Math.random(), Math.random(), Math.random(), Math.random());
// });
// test("cp draw methods", () => {
// const cp = ear.cp();
// const l = cp.line([Math.random() - 0.5, Math.random() - 0.5], [0.5, 0.5]);
// expect(cp.edges_assignment[cp.edges_assignment.length - 1]).toBe("U");
// l.mountain();
// expect(cp.edges_assignment[cp.edges_assignment.length - 1]).toBe("M");
// l.valley();
// expect(cp.edges_assignment[cp.edges_assignment.length - 1]).toBe("V");
// l.flat();
// expect(cp.edges_assignment[cp.edges_assignment.length - 1]).toBe("F");
// });
// test("cp.polygon", () => {
// const cp = ear.cp.fish();
// const res = cp.polygon([[0, 0], [4, 1], [1, 4]]);
// res.cut();
// expect(cp.edges_assignment.reduce((a, b) => a + (b === "C" ? 1 : 0), 0))
// .toBe(6);
// });
================================================
FILE: tests/prototypes.graph.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("all methods that return the graph itself", () => {
const graph = ear.graph.fish();
const result = graph
.populate()
.invertAssignments()
// .transform([2, 0, 0, 0, 2, 0, 0, 0, 2, 1, 2, 3])
.scaleUniform(2)
.scale([1, 2, 3])
.translate([1, 2])
.rotate(Math.PI / 2, [0, 0, 1], [0.5, 0.5])
.rotateZ(Math.PI / 2, [0.5, 0.5])
.unitize();
expect(result instanceof ear.graph).toBe(true);
});
test("all methods that return something else", () => {
const graph = ear.graph.fish();
graph.clean();
graph.subgraph({ vertices: [0, 1, 2, 3] });
graph.boundary();
graph.boundaries();
graph.planarBoundary();
graph.planarBoundaries();
graph.boundingBox();
graph.nearestVertex([0.5, 0.5]);
graph.nearestEdge([0.5, 0.5]);
graph.nearestFace([0.5, 0.5]);
graph.splitEdge(0, [0, 0.1]);
graph.svg();
graph.obj();
graph.explodeFaces();
graph.explodeEdges();
graph.validate();
expect(true).toBe(true);
});
test("copy", () => {
const graph = ear.graph({
vertices_coords: [[0, 0], [1, 0], [1, 1], [0, 1]],
edges_vertices: [[0, 1], [1, 2], [2, 3], [3, 0], [0, 2]],
faces_vertices: [[0, 1, 2], [2, 3, 0]],
faces_edges: [[0, 1, 4], [2, 3, 4]],
});
const copy = graph.clone();
graph.vertices_coords = [];
expect(copy.vertices_coords.length).toBe(4);
expect(graph.vertices_coords.length).toBe(0);
});
// "load" has been removed for now.
// test("load", () => {
// const graph = ear.graph();
// // this shouldn't do anything, but also won't throw an error
// graph.load();
// // now, load.
// graph.load({
// vertices_coords: [[0,0], [1,0], [1,1], [0,1]],
// edges_vertices: [[0, 1], [1, 2], [2, 3], [3, 0], [0, 2]],
// faces_vertices: [[0, 1, 2], [2, 3, 0]],
// faces_edges: [[0, 1, 4], [2, 3, 4]],
// });
// expect(graph.vertices_coords.length).toBe(4);
// expect(graph.vertices_coords[2][0]).toBe(1);
// expect(graph.vertices_coords[2][1]).toBe(1);
// });
// test("load, rewrite, and append", () => {
// const graph = ear.graph();
// graph.load({
// edges_assignment: ["V", "M", "U", "F"],
// });
// expect(graph.edges_assignment[3]).toBe("F");
// graph.load({
// edges_assignment: ["U", "U", "U", "U"],
// });
// expect(graph.edges_assignment[3]).toBe("U");
// graph.load({
// vertices_coords: [[0.5, 0.5], [0.25, 0.25]],
// });
// // edges_assignment has been overwritten
// expect(graph.edges_assignment).toBe(undefined);
// expect(graph.vertices_coords[0][0]).toBe(0.5);
// // now load a graph but don't overwrite
// graph.load({
// edges_assignment: ["U", "U", "U", "U"],
// }, { append: true });
// expect(graph.edges_assignment[3]).toBe("U");
// expect(graph.vertices_coords[0][0]).toBe(0.5);
// });
// test("clear", () => {
// const graph = ear.graph({
// vertices_coords: [[0, 0], [1, 0], [1, 1], [0, 1]],
// edges_vertices: [[0, 1], [1, 2], [2, 3], [3, 0], [0, 2]],
// faces_vertices: [[0, 1, 2], [2, 3, 0]],
// faces_edges: [[0, 1, 4], [2, 3, 4]],
// });
// graph.clear();
// expect(graph.vertices_coords).toBe(undefined);
// expect(graph.edges_vertices).toBe(undefined);
// expect(graph.faces_vertices).toBe(undefined);
// expect(graph.faces_edges).toBe(undefined);
// });
test("populate", () => {
const graph = ear.graph({
vertices_coords: [
[0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [4, 1], [3, 1], [2, 1], [1, 1], [0, 1],
],
edges_vertices: [
[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7],
[7, 8], [8, 9], [9, 0], [1, 8], [2, 7], [3, 6],
],
edges_foldAngle: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 90, 90, 90],
edges_assignment: ["B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "V", "V", "V", "V"],
});
const extra_keys = [
"vertices_edges", "vertices_faces", "vertices_vertices",
"edges_vertices", "edges_faces",
"faces_vertices", "faces_edges", "faces_faces",
];
// calling graph() initializer now automatically runs populate();
// extra_keys.forEach(key => expect(graph.vertices_vertices).toBe(undefined));
graph.populate();
extra_keys.forEach(key => expect(graph[key]).not.toBe(undefined));
});
test("affine transforms", () => {
const graph = ear.graph({
vertices_coords: [
[0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [4, 1], [3, 1], [2, 1], [1, 1], [0, 1],
],
edges_vertices: [
[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7],
[7, 8], [8, 9], [9, 0], [1, 8], [2, 7], [3, 6],
],
edges_foldAngle: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 90, 90, 90],
edges_assignment: ["B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "V", "V", "V", "V"],
});
graph.translate([4, 8]);
expect(graph.vertices_coords[5][0]).toBe(8);
expect(graph.vertices_coords[5][1]).toBe(9);
graph.scaleUniform(0.5);
expect(graph.vertices_coords[5][0]).toBe(4);
expect(graph.vertices_coords[5][1]).toBe(4.5);
});
================================================
FILE: tests/prototypes.static.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
// test("regular polygon bases", () => {
// const names = [
// "triangle", "square", "pentagon", "hexagon", "heptagon",
// "octagon", "nonagon", "decagon", "hendecagon", "dodecagon",
// ];
// names.forEach((name, i) => {
// let g = ear.graph[name]();
// expect(g.vertices_coords.length).toBe(i + 3);
// expect(g.edges_vertices.length).toBe(i + 3);
// expect(g.faces_vertices.length).toBe(1);
// });
// });
// test("other shapes", () => {
// const circle = ear.graph.circle();
// expect(circle.vertices_coords.length).toBe(90);
// const circle64 = ear.graph.circle(64);
// expect(circle64.vertices_coords.length).toBe(64);
// });
test("bases", () => {
const kite = ear.graph.kite();
expect(kite.vertices_coords.length).toBe(6);
expect(kite.edges_vertices.length).toBe(9);
// const bird = ear.graph.bird();
});
================================================
FILE: tests/singleVertex.degree4.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("foldDegree4", () => {
const foldAngle = Math.PI / 2;
const sixth = Math.PI / 3;
const result = ear.singleVertex.foldDegree4(
[sixth * 1, sixth * 2, sixth * 2, sixth * 1],
["M", "M", "V", "M"],
foldAngle,
);
const expected = [
0.9272952180016123,
foldAngle,
-0.9272952180016123,
foldAngle,
];
result.forEach((res, i) => expect(res).toBeCloseTo(expected[i]));
});
test("foldDegree4, does not worry about self intersection", () => {
const seventh = (Math.PI * 2) / 7;
const assignments = [
["V", "M", "M", "M"],
["M", "V", "M", "M"],
["M", "M", "V", "M"],
["M", "M", "M", "V"],
];
const result = assignments.map(assign => ear.singleVertex.foldDegree4(
[seventh * 1, seventh * 2, seventh * 2, seventh * 2],
assign,
Math.PI / 2,
));
result.forEach(res => {
expect(res).not.toBe(undefined);
expect(res.length).toBe(4);
});
});
================================================
FILE: tests/singleVertex.flatFoldable.test.js
================================================
import { expect, test } from "vitest";
import fs from "fs";
import ear from "../src/index.js";
test("verticesFlatFoldabilityMaekawa", () => {
const foldFile = fs.readFileSync("./tests/files/fold/invalid-single-vertex-2d.fold", "utf-8");
const fold = JSON.parse(foldFile);
const graphs = ear.graph.getFileFramesAsArray(fold);
expect(ear.singleVertex.verticesFlatFoldabilityMaekawa(graphs[0]))
.toMatchObject([0, 0, 0, 0, 0, 0, 0, 0, 0]);
expect(ear.singleVertex.verticesFlatFoldabilityMaekawa(graphs[1]))
.toMatchObject([0, 0, 0, 0, 0, -2, 0, 0, 0]);
expect(ear.singleVertex.verticesFlatFoldabilityMaekawa(graphs[2]))
.toMatchObject([0, 0, 0, 0, 0, 0, 0, 0, 0]);
expect(ear.singleVertex.verticesFlatFoldabilityMaekawa(graphs[3]))
.toMatchObject([0, 0, 0, 0, 0, -2, 0, 0, 0]);
expect(ear.singleVertex.verticesFlatFoldabilityMaekawa(graphs[4]))
.toMatchObject([0, 0, 0, 0, 0, 0, 0, 0, 0]);
});
test("verticesFlatFoldabilityKawasaki", () => {
const foldFile = fs.readFileSync("./tests/files/fold/invalid-single-vertex-2d.fold", "utf-8");
const fold = JSON.parse(foldFile);
const graphs = ear.graph.getFileFramesAsArray(fold);
expect(ear.singleVertex.verticesFlatFoldabilityKawasaki(graphs[0])[5])
.toBeCloseTo(0);
expect(ear.singleVertex.verticesFlatFoldabilityKawasaki(graphs[1])[5])
.toBeCloseTo(0);
expect(ear.singleVertex.verticesFlatFoldabilityKawasaki(graphs[2])[5])
.toBeCloseTo(-0.04060135259522912);
expect(ear.singleVertex.verticesFlatFoldabilityKawasaki(graphs[3])[5])
.toBeCloseTo(-0.04060135259522912);
expect(ear.singleVertex.verticesFlatFoldabilityKawasaki(graphs[4])[5])
.toBeCloseTo(0);
});
test("verticesFlatFoldableMaekawa", () => {
const foldFile = fs.readFileSync("./tests/files/fold/invalid-single-vertex-2d.fold", "utf-8");
const fold = JSON.parse(foldFile);
const graphs = ear.graph.getFileFramesAsArray(fold);
expect(ear.singleVertex.verticesFlatFoldableMaekawa(graphs[0]))
.toMatchObject([true, true, true, true, true, true, true, true, true]);
expect(ear.singleVertex.verticesFlatFoldableMaekawa(graphs[1]))
.toMatchObject([true, true, true, true, true, false, true, true, true]);
expect(ear.singleVertex.verticesFlatFoldableMaekawa(graphs[2]))
.toMatchObject([true, true, true, true, true, true, true, true, true]);
expect(ear.singleVertex.verticesFlatFoldableMaekawa(graphs[3]))
.toMatchObject([true, true, true, true, true, false, true, true, true]);
expect(ear.singleVertex.verticesFlatFoldableMaekawa(graphs[4]))
.toMatchObject([true, true, true, true, true, true, true, true, true]);
});
test("verticesFlatFoldableKawasaki", () => {
const foldFile = fs.readFileSync("./tests/files/fold/invalid-single-vertex-2d.fold", "utf-8");
const fold = JSON.parse(foldFile);
const graphs = ear.graph.getFileFramesAsArray(fold);
expect(ear.singleVertex.verticesFlatFoldableKawasaki(graphs[0]))
.toMatchObject([true, true, true, true, true, true, true, true, true]);
expect(ear.singleVertex.verticesFlatFoldableKawasaki(graphs[1]))
.toMatchObject([true, true, true, true, true, true, true, true, true]);
expect(ear.singleVertex.verticesFlatFoldableKawasaki(graphs[2]))
.toMatchObject([true, true, true, true, true, false, true, true, true]);
expect(ear.singleVertex.verticesFlatFoldableKawasaki(graphs[3]))
.toMatchObject([true, true, true, true, true, false, true, true, true]);
expect(ear.singleVertex.verticesFlatFoldableKawasaki(graphs[4]))
.toMatchObject([true, true, true, true, true, true, true, true, true]);
});
test("verticesFlatFoldability", () => {
const foldFile = fs.readFileSync("./tests/files/fold/invalid-single-vertex-2d.fold", "utf-8");
const fold = JSON.parse(foldFile);
const graphs = ear.graph.getFileFramesAsArray(fold);
expect(ear.singleVertex.verticesFlatFoldability(graphs[0]))
.toMatchObject([0, 0, 0, 0, 0, 0, 0, 0, 0]);
expect(ear.singleVertex.verticesFlatFoldability(graphs[1]))
.toMatchObject([0, 0, 0, 0, 0, 1, 0, 0, 0]);
expect(ear.singleVertex.verticesFlatFoldability(graphs[2]))
.toMatchObject([0, 0, 0, 0, 0, 2, 0, 0, 0]);
expect(ear.singleVertex.verticesFlatFoldability(graphs[3]))
.toMatchObject([0, 0, 0, 0, 0, 3, 0, 0, 0]);
expect(ear.singleVertex.verticesFlatFoldability(graphs[4]))
.toMatchObject([0, 0, 0, 0, 0, 0, 0, 0, 0]);
});
test("verticesFlatFoldable", () => {
const foldFile = fs.readFileSync("./tests/files/fold/invalid-single-vertex-2d.fold", "utf-8");
const fold = JSON.parse(foldFile);
const graphs = ear.graph.getFileFramesAsArray(fold);
expect(ear.singleVertex.verticesFlatFoldable(graphs[0]))
.toMatchObject([true, true, true, true, true, true, true, true, true]);
expect(ear.singleVertex.verticesFlatFoldable(graphs[1]))
.toMatchObject([true, true, true, true, true, false, true, true, true]);
expect(ear.singleVertex.verticesFlatFoldable(graphs[2]))
.toMatchObject([true, true, true, true, true, false, true, true, true]);
expect(ear.singleVertex.verticesFlatFoldable(graphs[3]))
.toMatchObject([true, true, true, true, true, false, true, true, true]);
expect(ear.singleVertex.verticesFlatFoldable(graphs[4]))
.toMatchObject([true, true, true, true, true, true, true, true, true]);
});
================================================
FILE: tests/singleVertex.foldable.test.js
================================================
import fs from "fs";
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("verticesFoldability", () => {
const foldFile = fs.readFileSync("./tests/files/fold/invalid-single-vertex-2d.fold", "utf-8");
const fold = JSON.parse(foldFile);
const graphs = ear.graph.getFileFramesAsArray(fold);
ear.singleVertex.verticesFoldability(graphs[0])
.forEach((value, i) => expect(value)
.toBeCloseTo([0, 0, 0, 0, 0, 0, 0, 0, 0][i]));
ear.singleVertex.verticesFoldability(graphs[1])
.forEach((value, i) => expect(value)
.toBeCloseTo([0, 0, 0, 0, 0, 0, 0, 0, 0][i]));
ear.singleVertex.verticesFoldability(graphs[2])
.forEach((value, i) => expect(value)
.toBeCloseTo([0, 0, 0, 0, 0, 0.082828, 0, 0, 0][i]));
ear.singleVertex.verticesFoldability(graphs[3])
.forEach((value, i) => expect(value)
.toBeCloseTo([0, 0, 0, 0, 0, 0.082828, 0, 0, 0][i]));
ear.singleVertex.verticesFoldability(graphs[4])
.forEach((value, i) => expect(value)
.toBeCloseTo([0, 0, 0, 0, 0, 0, 0, 0, 0][i]));
});
test("verticesFoldable", () => {
const foldFile = fs.readFileSync("./tests/files/fold/invalid-single-vertex-2d.fold", "utf-8");
const fold = JSON.parse(foldFile);
const graphs = ear.graph.getFileFramesAsArray(fold);
ear.singleVertex.verticesFoldable(graphs[0])
.forEach((value, i) => expect(value)
.toBeCloseTo([true, true, true, true, true, true, true, true, true][i]));
ear.singleVertex.verticesFoldable(graphs[1])
.forEach((value, i) => expect(value)
.toBeCloseTo([true, true, true, true, true, true, true, true, true][i]));
ear.singleVertex.verticesFoldable(graphs[2])
.forEach((value, i) => expect(value)
.toBeCloseTo([true, true, true, true, true, false, true, true, true][i]));
ear.singleVertex.verticesFoldable(graphs[3])
.forEach((value, i) => expect(value)
.toBeCloseTo([true, true, true, true, true, false, true, true, true][i]));
ear.singleVertex.verticesFoldable(graphs[4])
.forEach((value, i) => expect(value)
.toBeCloseTo([true, true, true, true, true, true, true, true, true][i]));
});
test("verticesFoldability", () => {
const testfile = fs.readFileSync("./tests/files/fold/invalid-box-pleat-3d.fold", "utf-8");
const graph = JSON.parse(testfile);
const verts = ear.singleVertex.verticesFoldability(graph);
// one vertex is not foldable
[0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0]
.forEach((value, i) => expect(verts[i]).toBeCloseTo(value));
});
test("verticesFoldable", () => {
const testfile = fs.readFileSync("./tests/files/fold/invalid-box-pleat-3d.fold", "utf-8");
const graph = JSON.parse(testfile);
const verts = ear.singleVertex.verticesFoldable(graph);
// one vertex is not foldable
const expected = [
true, true, true, true, true, true, true, false, true, true, true, true,
];
expected.forEach((valid, i) => expect(verts[i]).toBe(valid));
});
test("verticesFoldable", () => {
const testfile = fs.readFileSync("./tests/files/fold/invalid-single-vertex-3d.fold", "utf-8");
const graph = JSON.parse(testfile);
const verts = ear.singleVertex.verticesFoldable(graph);
// expect(verts).toMatchObject([true, true, true, false, true, true]);
expect(verts).toMatchObject([true, true, true, true, true, true]);
});
test("verticesFoldable", () => {
const testfile = fs.readFileSync("./tests/files/fold/invalid-self-intersect.fold", "utf-8");
const graph = JSON.parse(testfile);
const verts = ear.singleVertex.verticesFoldable(graph);
// expect(verts).toMatchObject([
// true, true, true, true, true, false, true, true, true, true, true
// ]);
expect(verts).toMatchObject([
true, true, true, true, true, true, true, true, true, true, true
]);
});
================================================
FILE: tests/singleVertex.kawasaki.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
const testArrays = (a, b) => {
a.forEach((_, i) => {
if (typeof a[i] === "number") {
expect(a[i]).toBeCloseTo(b[i]);
} else if (typeof a[i] === "object" && a[i].constructor === Array) {
expect(ear.math.epsilonEqualVectors(a[i], b[i])).toBe(true);
} else {
expect(a[i]).toBe(b[i]);
}
});
expect(a.length).toBe(b.length);
};
test("alternating sum", () => {
testArrays([0, 0], ear.singleVertex.alternatingSum([]));
testArrays([1, 0], ear.singleVertex.alternatingSum([1]));
testArrays([16, 20], ear.singleVertex.alternatingSum([1, 2, 3, 4, 5, 6, 7, 8]));
});
test("alternating deviation, equal pairs", () => {
const equal2 = [Math.PI, Math.PI];
const equal4 = Array(4).fill(Math.PI / 2);
testArrays([0, 0], ear.singleVertex.alternatingSumDifference(equal2));
testArrays([0, 0], ear.singleVertex.alternatingSumDifference(equal4));
testArrays(
[0, 0],
ear.singleVertex.alternatingSumDifference(
ear.math.counterClockwiseSectors2([[1, 0], [0, 1], [-1, 0], [0, -1]]),
),
);
});
test("alternating deviation, non-equal pairs", () => {
// two Math.PI +/- 1
const arr2 = Array(2).fill(Math.PI).map((v, i) => v + (i % 2 ? 1 : -1));
// four Math.PI/2 +/- 1/2
const arr4 = Array(4).fill(Math.PI / 2).map((v, i) => v + (i % 2 ? 1 / 2 : -1 / 2));
testArrays([-1, 1], ear.singleVertex.alternatingSumDifference(arr2));
testArrays([-1, 1], ear.singleVertex.alternatingSumDifference(arr4));
});
test("kawasaki solutions radians", () => {
testArrays(
[undefined, undefined, 1.25 * Math.PI],
ear.singleVertex.kawasakiSolutionsRadians([
0, Math.PI / 2, (Math.PI / 4) * 3,
]),
);
});
test("kawasaki solutions", () => {
testArrays(
[
[Math.cos(Math.PI * (1 / 3)), Math.sin(Math.PI * (1 / 3))],
[Math.cos(Math.PI * (3 / 3)), Math.sin(Math.PI * (3 / 3))],
[Math.cos(Math.PI * (5 / 3)), Math.sin(Math.PI * (5 / 3))],
],
ear.singleVertex.kawasakiSolutionsVectors([
[Math.cos(0), Math.sin(0)],
[Math.cos(Math.PI * (2 / 3)), Math.sin(Math.PI * (2 / 3))],
[Math.cos(Math.PI * (4 / 3)), Math.sin(Math.PI * (4 / 3))],
]),
);
const sqrt05 = Math.sqrt(1 / 2);
testArrays(
[undefined, undefined, [-sqrt05, -sqrt05]],
ear.singleVertex.kawasakiSolutionsVectors([
[Math.cos(0), Math.sin(0)],
[Math.cos(Math.PI / 4), Math.sin(Math.PI / 4)],
[Math.cos(Math.PI / 2), Math.sin(Math.PI / 2)],
]),
);
});
================================================
FILE: tests/singleVertex.maekawa.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("maekawaSolver, no U", () => {
const result = ear.singleVertex.maekawaSolver(Array.from("MMVM"));
expect(result.length).toBe(1);
expect(result[0].join("")).toBe("MMVM");
});
test("maekawaSolver one solution", () => {
const result = ear.singleVertex.maekawaSolver(Array.from("MMVMUVMV"));
expect(result.length).toBe(1);
expect(result[0].join("")).toBe("MMVMMVMV");
});
test("maekawaSolver two solutions", () => {
const result = ear.singleVertex.maekawaSolver(Array.from("MMVUUVMV"));
expect(result.length).toBe(2);
expect(result[0].join("")).toBe("MMVVVVMV");
expect(result[1].join("")).toBe("MMVMMVMV");
});
test("maekawaSolver with boundary", () => {
const result = ear.singleVertex.maekawaSolver(Array.from("UUBV"));
expect(result.length).toBe(4);
expect(result[0].join("")).toBe("VVBV");
expect(result[3].join("")).toBe("MMBV");
});
test("maekawaSolver with cut", () => {
const result = ear.singleVertex.maekawaSolver(Array.from("UUCV"));
expect(result.length).toBe(4);
expect(result[0].join("")).toBe("VVCV");
expect(result[3].join("")).toBe("MMCV");
});
test("maekawaSolver various", () => {
// if the set contains a boundary ("B" or "C"), then it returns all possible
// permutations, including just the one. if it doesn't incude a boundary it
// runs maekawa and if M-V=+/-2 is not satisfied it returns an empty array.
expect(ear.singleVertex.maekawaSolver(Array.from("BBBB"))[0].join("")).toBe("BBBB");
expect(ear.singleVertex.maekawaSolver(Array.from("CCCC"))[0].join("")).toBe("CCCC");
expect(ear.singleVertex.maekawaSolver(Array.from("JJJJ")).length).toBe(0);
expect(ear.singleVertex.maekawaSolver(Array.from("FFFF")).length).toBe(0);
expect(ear.singleVertex.maekawaSolver(Array.from("BCJF"))[0].join("")).toBe("BCJF");
});
================================================
FILE: tests/svg.arrow.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
test("arrow", () => {
// svg.size(2.5, 1)
// .strokeWidth(0.01)
// .padding(0.25);
// const options = {
// bend: 0.3,
// head: {
// width: 0.1,
// height: 0.13,
// },
// fill: "red",
// };
// const layer = svg.g();
// svg.controls(2)
// .svg(() => svg.circle(0.04).fill("blue"))
// .position(() => [Math.random(), Math.random()])
// .onChange((p, i, pts) => {
// layer.removeChildren();
// const arrow = layer.arrow(options)
// .points(...pts)
// arrow.getLine()
// .strokeWidth(0.03)
// .stroke("black");
// }, true);
expect(true).toBe(true);
});
test("arrow object", () => {
expect(true).toBe(true);
});
================================================
FILE: tests/svg.attributes.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
const toCamel = s => s
.replace(/([-_][a-z])/ig, $1 => $1
.toUpperCase()
.replace("-", "")
.replace("_", ""));
const Attributes = {
svg: ["viewBox", "color", "color-interpolation", "cursor", "direction", "display", "fill", "fill-opacity", "fill-rule", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "image-rendering", "letter-spacing", "opacity", "overflow", "paint-order", "pointer-events", "preserveAspectRatio", "shape-rendering", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "tabindex", "transform-origin", "user-select", "vector-effect", "visibility"],
line: ["x1", "y1", "x2", "y2", "color", "color-interpolation", "cursor", "direction", "display", "fill", "fill-opacity", "fill-rule", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "image-rendering", "letter-spacing", "opacity", "overflow", "paint-order", "pointer-events", "preserveAspectRatio", "shape-rendering", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "tabindex", "transform-origin", "user-select", "vector-effect", "visibility"],
rect: ["x", "y", "width", "height", "color", "color-interpolation", "cursor", "direction", "display", "fill", "fill-opacity", "fill-rule", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "image-rendering", "letter-spacing", "opacity", "overflow", "paint-order", "pointer-events", "preserveAspectRatio", "shape-rendering", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "tabindex", "transform-origin", "user-select", "vector-effect", "visibility"],
circle: ["cx", "cy", "r", "color", "color-interpolation", "cursor", "direction", "display", "fill", "fill-opacity", "fill-rule", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "image-rendering", "letter-spacing", "opacity", "overflow", "paint-order", "pointer-events", "preserveAspectRatio", "shape-rendering", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "tabindex", "transform-origin", "user-select", "vector-effect", "visibility"],
ellipse: ["cx", "cy", "rx", "ry", "color", "color-interpolation", "cursor", "direction", "display", "fill", "fill-opacity", "fill-rule", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "image-rendering", "letter-spacing", "opacity", "overflow", "paint-order", "pointer-events", "preserveAspectRatio", "shape-rendering", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "tabindex", "transform-origin", "user-select", "vector-effect", "visibility"],
polygon: ["points", "color", "color-interpolation", "cursor", "direction", "display", "fill", "fill-opacity", "fill-rule", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "image-rendering", "letter-spacing", "opacity", "overflow", "paint-order", "pointer-events", "preserveAspectRatio", "shape-rendering", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "tabindex", "transform-origin", "user-select", "vector-effect", "visibility"],
polyline: ["points", "color", "color-interpolation", "cursor", "direction", "display", "fill", "fill-opacity", "fill-rule", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "image-rendering", "letter-spacing", "opacity", "overflow", "paint-order", "pointer-events", "preserveAspectRatio", "shape-rendering", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "tabindex", "transform-origin", "user-select", "vector-effect", "visibility"],
path: ["d", "color", "color-interpolation", "cursor", "direction", "display", "fill", "fill-opacity", "fill-rule", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "image-rendering", "letter-spacing", "opacity", "overflow", "paint-order", "pointer-events", "preserveAspectRatio", "shape-rendering", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "tabindex", "transform-origin", "user-select", "vector-effect", "visibility"],
mask: ["id"],
symbol: ["id"],
clipPath: ["id", "clip-rule"],
marker: ["id", "markerHeight", "markerUnits", "markerWidth", "orient", "refX", "refY"],
linearGradient: ["x1", "x2", "y1", "y2"],
radialGradient: ["cx", "cy", "r", "fr", "fx", "fy"],
stop: ["offset", "stop-color", "stop-opacity", "gradientTransform", "gradientUnits", "spreadMethod"],
pattern: ["patternContentUnits", "patternTransform", "patternUnits"],
defs: ["color", "color-interpolation", "cursor", "direction", "display", "fill", "fill-opacity", "fill-rule", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "image-rendering", "letter-spacing", "opacity", "overflow", "paint-order", "pointer-events", "preserveAspectRatio", "shape-rendering", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "tabindex", "transform-origin", "user-select", "vector-effect", "visibility"],
desc: [],
filter: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
metadata: [],
style: [],
script: [],
title: [],
view: [],
cdata: [],
g: ["color", "color-interpolation", "cursor", "direction", "display", "fill", "fill-opacity", "fill-rule", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "image-rendering", "letter-spacing", "opacity", "overflow", "paint-order", "pointer-events", "preserveAspectRatio", "shape-rendering", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "tabindex", "transform-origin", "user-select", "vector-effect", "visibility"],
text: ["x", "y", "dx", "dy", "alignment-baseline", "baseline-shift", "dominant-baseline", "lengthAdjust", "method", "overline-position", "overline-thickness", "rotate", "spacing", "startOffset", "strikethrough-position", "strikethrough-thickness", "text-anchor", "text-decoration", "text-rendering", "textLength", "underline-position", "underline-thickness", "word-spacing", "writing-mode"],
textPath: ["dx", "dy", "alignment-baseline", "baseline-shift", "dominant-baseline", "lengthAdjust", "method", "overline-position", "overline-thickness", "rotate", "spacing", "startOffset", "strikethrough-position", "strikethrough-thickness", "text-anchor", "text-decoration", "text-rendering", "textLength", "underline-position", "underline-thickness", "word-spacing", "writing-mode"],
tspan: ["dx", "dy", "alignment-baseline", "baseline-shift", "dominant-baseline", "lengthAdjust", "method", "overline-position", "overline-thickness", "rotate", "spacing", "startOffset", "strikethrough-position", "strikethrough-thickness", "text-anchor", "text-decoration", "text-rendering", "textLength", "underline-position", "underline-thickness", "word-spacing", "writing-mode"],
feBlend: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feColorMatrix: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feComponentTransfer: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feComposite: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feConvolveMatrix: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feDiffuseLighting: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feDisplacementMap: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feDistantLight: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feDropShadow: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feFlood: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feFuncA: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feFuncB: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feFuncG: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feFuncR: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feGaussianBlur: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feImage: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feMerge: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feMergeNode: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feMorphology: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feOffset: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
fePointLight: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feSpecularLighting: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feSpotLight: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feTile: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
feTurbulence: ["azimuth", "baseFrequency", "bias", "color-interpolation-filters", "diffuseConstant", "divisor", "edgeMode", "elevation", "exponent", "filter", "filterRes", "filterUnits", "flood-color", "flood-opacity", "in", "in2", "intercept", "k1", "k2", "k3", "k4", "kernelMatrix", "lighting-color", "limitingConeAngle", "mode", "numOctaves", "operator", "order", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha", "primitiveUnits", "radius", "result", "seed", "specularConstant", "specularExponent", "stdDeviation", "stitchTiles", "surfaceScale", "targetX", "targetY", "type", "xChannelSelector", "yChannelSelector"],
};
test("attributes test", () => {
Object.keys(Attributes).forEach(nodeName => {
const element = ear.svg[nodeName]();
Attributes[nodeName]
// .filter(attr => typeof element[attr] === "function")
.forEach((attr, i) => element[toCamel(attr)](String(i)));
// some attributes are being set without the user.
// svg: "xmlns" and "version"
// style: "type" (text/css)
let countMod = 0;
switch (nodeName) {
case "svg": countMod = 2; break;
case "style": countMod = 1; break;
default: countMod = 0; break;
}
expect(element.attributes.length)
.toBe(Attributes[nodeName].length + countMod);
});
});
================================================
FILE: tests/svg.circle.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("circle arguments", () => {
expect(ear.svg.circle(1).getAttribute("r")).toBe("1");
expect(ear.svg.circle(5).getAttribute("r")).toBe("5");
expect(ear.svg.circle(2, 3).getAttribute("cx")).toBe("2");
expect(ear.svg.circle(2, 3).getAttribute("cy")).toBe("3");
expect(ear.svg.circle(2, 3).getAttribute("r") === null
|| ear.svg.circle(2, 3).getAttribute("r") === "").toBe(true);
expect(ear.svg.circle(1, 2, 3).getAttribute("cx")).toBe("1");
expect(ear.svg.circle(1, 2, 3).getAttribute("cy")).toBe("2");
expect(ear.svg.circle(1, 2, 3).getAttribute("r")).toBe("3");
expect(parseFloat(ear.svg.circle(1, 2, 3, 4).getAttribute("r")))
.toBeCloseTo(2 * Math.sqrt(2));
expect(ear.svg.circle(1, 2, 3, 4).getAttribute("cx")).toBe("1");
expect(ear.svg.circle(1, 2, 3, 4).getAttribute("cy")).toBe("2");
});
test("circle setters", () => {
expect(ear.svg.circle().radius(5).getAttribute("r")).toBe("5");
expect(ear.svg.circle().setRadius(5).getAttribute("r")).toBe("5");
expect(ear.svg.circle().origin(2, 3).getAttribute("cx")).toBe("2");
expect(ear.svg.circle().origin(2, 3).getAttribute("cy")).toBe("3");
expect(ear.svg.circle().setOrigin(2, 3).getAttribute("cx")).toBe("2");
expect(ear.svg.circle().setOrigin(2, 3).getAttribute("cy")).toBe("3");
expect(ear.svg.circle().center(2, 3).getAttribute("cx")).toBe("2");
expect(ear.svg.circle().center(2, 3).getAttribute("cy")).toBe("3");
expect(ear.svg.circle().setCenter(2, 3).getAttribute("cx")).toBe("2");
expect(ear.svg.circle().setCenter(2, 3).getAttribute("cy")).toBe("3");
expect(ear.svg.circle().position(2, 3).getAttribute("cx")).toBe("2");
expect(ear.svg.circle().position(2, 3).getAttribute("cy")).toBe("3");
expect(ear.svg.circle().setPosition(2, 3).getAttribute("cx")).toBe("2");
expect(ear.svg.circle().setPosition(2, 3).getAttribute("cy")).toBe("3");
const attrs = ["cx", "cy"];
let c = ear.svg.circle();
c.setCenter(1, 2, 3, 4);
attrs.forEach((attr, i) => expect(c.getAttribute(attr)).toBe(String([1, 2][i])));
expect(c.attributes.length).toBe(2);
c.setRadius(10);
attrs.forEach((attr, i) => expect(c.getAttribute(attr)).toBe(String([1, 2][i])));
expect(c.getAttribute("r")).toBe("10");
expect(c.attributes.length).toBe(3);
});
================================================
FILE: tests/svg.class.id.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("class", () => {
const svg = ear.svg();
if (typeof svg.classList === "undefined") {
expect(true).toBe(true);
return;
}
svg.classList.add("big");
expect(svg.getAttribute("class")).toBe("big");
svg.classList.add("medium");
expect(svg.getAttribute("class")).toBe("big medium");
svg.classList.remove("big");
expect(svg.getAttribute("class")).toBe("medium");
svg.className = "small";
expect(svg.getAttribute("class")).toBe("small");
const line = ear.svg.line();
line.id = "five";
expect(line.getAttribute("id")).toBe("five");
const circle = ear.svg.circle();
circle.classList.remove("apple");
expect(circle.getAttribute("class")).toBe("");
});
================================================
FILE: tests/svg.colors.test.js
================================================
import { expect, test } from "vitest";
import ear from "../src/index.js";
// anything involving hsl is within 1 unit
test("all conversions with alpha", () => {
const rgbaValues = [17, 85, 136, 0.25];
const hslaValues = [206, 77.777, 30, 0.25];
const hex = "#11558840";
const rgb = "rgba(17, 85, 136)";
const rgba = "rgba(17, 85, 136, 0.25)";
const hsl = "hsla(206, 77.777%, 30%)";
const hsla = "hsla(206, 77.777%, 30%, 0.25)";
// core conversion methods
expect(ear.svg.rgbToHex(...rgbaValues)).toBe(hex);
ear.svg.hexToRgb(hex)
.forEach((n, i) => expect(n).toBe(rgbaValues[i]));
ear.svg.hslToRgb(...hslaValues)
.map((n, i) => Math.abs(n - rgbaValues[i]))
.forEach(diff => expect(diff < 1).toBe(true));
// parser methods
ear.svg.parseColorToRgb(hex)
.forEach((n, i) => expect(n).toBe(rgbaValues[i]));
ear.svg.parseColorToRgb(rgb)
.forEach((n, i) => expect(n).toBe(rgbaValues[i]));
ear.svg.parseColorToRgb(rgba)
.forEach((n, i) => expect(n).toBe(rgbaValues[i]));
ear.svg.parseColorToRgb(hsl)
.map((n, i) => Math.abs(n - rgbaValues[i]))
.forEach(diff => expect(diff < 1).toBe(true));
ear.svg.parseColorToRgb(hsla)
.map((n, i) => Math.abs(n - rgbaValues[i]))
.forEach(diff => expect(diff < 1).toBe(true));
expect(ear.svg.parseColorToHex(hex)).toBe(hex);
expect(ear.svg.parseColorToHex(rgb)).toBe("#115588");
expect(ear.svg.parseColorToHex(rgba)).toBe(hex);
// these are off by one. 54 instead of 55. unfortunately,
// I think we just have to deal with this error in conversion.
expect(ear.svg.parseColorToHex(hsl)).toBe("#115488");
expect(ear.svg.parseColorToHex(hsla)).toBe("#11548840");
expect(ear.svg.parseColorToHex("red")).toBe("#FF0000");
expect(ear.svg.parseColorToHex("blue")).toBe("#0000FF");
expect(ear.svg.parseColorToHex("")).toBe(undefined);
});
test("colors hexToRgb", () => {
const rgb1 = ear.svg.hexToRgb("#158");
const rgb2 = ear.svg.hexToRgb("#115588");
expect(JSON.stringify(rgb1)).toBe(JSON.stringify(rgb2));
[17, 85, 136]
.forEach((value, i) => expect(value).toBeCloseTo(rgb1[i]));
});
test("colors hslToRgb", () => {
const rgb1 = ear.svg.hslToRgb(0, 0, 100);
const rgb2 = ear.svg.hslToRgb(0, 100, 100);
expect(JSON.stringify(rgb1)).toBe(JSON.stringify(rgb2));
});
test("colors hslToRgb 2", () => {
const colorR = ear.svg.hslToRgb(0, 100, 50);
[255, 0, 0].forEach((value, i) => expect(value).toBeCloseTo(colorR[i]));
const colorG = ear.svg.hslToRgb(120, 100, 50);
[0, 255, 0].forEach((value, i) => expect(value).toBeCloseTo(colorG[i]));
const colorB = ear.svg.hslToRgb(240, 100, 50);
[0, 0, 255].forEach((value, i) => expect(value).toBeCloseTo(colorB[i]));
});
test("parseColorToRgb", () => {
const color1 = ear.svg.parseColorToRgb("red");
const color2 = ear.svg.parseColorToRgb("#f00");
const color3 = ear.svg.parseColorToRgb("#ff0000");
const color4 = ear.svg.parseColorToRgb("rgb(255, 0, 0)");
const color5 = ear.svg.parseColorToRgb("hsl(0, 100%, 50%)");
const colorAlpha1 = ear.svg.parseColorToRgb("rgba(255, 0, 0, 1)");
const colorAlpha2 = ear.svg.parseColorToRgb("hsla(0, 100%, 50%, 1)");
expect(JSON.stringify(color1)).toBe(JSON.stringify(color2));
expect(JSON.stringify(color1)).toBe(JSON.stringify(color3));
expect(JSON.stringify(color1)).toBe(JSON.stringify(color4));
expect(JSON.stringify(color1)).toBe(JSON.stringify(color5));
expect(JSON.stringify(colorAlpha1)).toBe(JSON.stringify(colorAlpha2));
expect(JSON.stringify(color1)).not.toBe(JSON.stringify(colorAlpha1));
});
test("empty parseColorToRgb", () => {
const color1 = ear.svg.parseColorToRgb("rgb()");
const color2 = ear.svg.parseColorToRgb("hsl()");
const colorAlpha1 = ear.svg.parseColorToRgb("rgba()");
const colorAlpha2 = ear.svg.parseColorToRgb("hsla()");
expect(JSON.stringify(color1)).toBe(JSON.stringify(color2));
expect(JSON.stringify(color1)).toBe(JSON.stringify(colorAlpha1));
expect(JSON.stringify(color1)).toBe(JSON.stringify(colorAlpha2));
});
test("invalid parseColorToRgb", () => {
const notacolor = ear.svg.parseColorToRgb("notacolor");
expect(notacolor).toBe(undefined);
});
================================================
FILE: tests/svg.coordinates.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("", () => expect(true).toBe(true));
// test("coordinates, two points", () => {
// ear.svg.makeCoordinates(1, 2, 3, 4)
// .forEach((n, i) => expect(n).toBe([1, 2, 3, 4][i]));
// ear.svg.makeCoordinates([1, 2], [3, 4])
// .forEach((n, i) => expect(n).toBe([1, 2, 3, 4][i]));
// ear.svg.makeCoordinates([1, 2, 3], [4, 5, 6])
// .forEach((n, i) => expect(n).toBe([1, 2, 4, 5][i]));
// ear.svg.makeCoordinates([1], [2])
// .forEach((n, i) => expect(n).toBe([1, undefined, 2, undefined][i]));
// });
// test("coordinates, not two points", () => {
// expect(ear.svg.makeCoordinates().length).toBe(0);
// expect(ear.svg.makeCoordinates([]).length).toBe(0);
// expect(ear.svg.makeCoordinates([[]]).length).toBe(0);
// expect(ear.svg.makeCoordinates([], []).length).toBe(0);
// ear.svg.makeCoordinates([1, 2], [3, 4], [5, 6])
// .forEach((n, i) => expect(n).toBe([1, 2, 3, 4, 5, 6][i]));
// });
================================================
FILE: tests/svg.dom.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("removeChildren()", () => {
const svg = ear.svg();
svg.line(1, 2, 3, 4);
expect(svg.childNodes.length).toBe(1);
svg.removeChildren();
expect(svg.childNodes.length).toBe(0);
});
// test("appendTo()", () => {
// const svg = ear.svg();
// expect(svg.childNodes.length).toBe(0);
// const line = ear.svg.line();
// const circle = ear.svg.circle();
// const ellipse = ear.svg.ellipse();
// const rect = ear.svg.rect();
// const path = ear.svg.path();
// const polygon = ear.svg.polygon();
// const polyline = ear.svg.polyline();
// const group = ear.svg.g();
// [line, circle, ellipse, rect, path, polygon, polyline, group]
// .forEach(primitive => primitive.appendTo(svg));
// expect(svg.childNodes.length).toBe(8);
// });
// test("setAttributes()", () => {
// const props = { a: "10", display: "block", style: "color:red" };
// const line = ear.svg.line();
// line.setAttributes(props);
// expect(line.getAttribute("display")).toBe("block");
// const group = ear.svg.g();
// group.setAttributes(props);
// expect(group.getAttribute("style")).toBe("color:red");
// const svg = ear.svg();
// svg.setAttributes(props);
// expect(svg.getAttribute("display")).toBe("block");
// });
================================================
FILE: tests/svg.ellipse.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("ellipse setters", () => {
expect(ear.svg.ellipse().radius(5, 6).getAttribute("rx")).toBe("5");
expect(ear.svg.ellipse().radius(5, 6).getAttribute("ry")).toBe("6");
expect(ear.svg.ellipse().setRadius(5, 6).getAttribute("rx")).toBe("5");
expect(ear.svg.ellipse().setRadius(5, 6).getAttribute("ry")).toBe("6");
expect(ear.svg.ellipse().origin(2, 3).getAttribute("cx")).toBe("2");
expect(ear.svg.ellipse().origin(2, 3).getAttribute("cy")).toBe("3");
expect(ear.svg.ellipse().setOrigin(2, 3).getAttribute("cx")).toBe("2");
expect(ear.svg.ellipse().setOrigin(2, 3).getAttribute("cy")).toBe("3");
expect(ear.svg.ellipse().center(2, 3).getAttribute("cx")).toBe("2");
expect(ear.svg.ellipse().center(2, 3).getAttribute("cy")).toBe("3");
expect(ear.svg.ellipse().setCenter(2, 3).getAttribute("cx")).toBe("2");
expect(ear.svg.ellipse().setCenter(2, 3).getAttribute("cy")).toBe("3");
expect(ear.svg.ellipse().position(2, 3).getAttribute("cx")).toBe("2");
expect(ear.svg.ellipse().position(2, 3).getAttribute("cy")).toBe("3");
expect(ear.svg.ellipse().setPosition(2, 3).getAttribute("cx")).toBe("2");
expect(ear.svg.ellipse().setPosition(2, 3).getAttribute("cy")).toBe("3");
// incomplete info
expect(ear.svg.ellipse().setRadius(5).getAttribute("rx")).toBe("5");
// expect(ear.svg.ellipse().setRadius(5).getAttribute("ry")).toBe("");
});
================================================
FILE: tests/svg.environment.test.js
================================================
import { expect, test } from "vitest";
test("environment", () => {
expect(true).toBe(true);
// console.log("window", window);
// console.log("window.document", window.document);
});
================================================
FILE: tests/svg.line.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("argument parsing, line", () => {
const lines = [
ear.svg.line(1, 2, 3, 4),
ear.svg.line([1, 2, 3, 4]),
ear.svg.line([[1, 2, 3, 4]]),
ear.svg.line([1, 2], [3, 4]),
ear.svg.line({ x: 1, y: 2 }, { x: 3, y: 4 }),
ear.svg.line([{ x: 1, y: 2 }, { x: 3, y: 4 }]),
ear.svg.line([1, 2, 9], [3, 4, 9]),
ear.svg.line([[1, 2, 9], [3, 4, 9]]),
ear.svg.line({ x: 1, y: 2, z: 9 }, { x: 3, y: 4, z: 9 }),
];
// ear.svg.line([1], [2], [3], [4]),
// ear.svg.line([{x:1, y:2}], [{x:3, y:4}]),
// ear.svg.line([[{x:1, y:2}], [{x:3, y:4}]]),
const result = lines
.map(el => ["x1", "y1", "x2", "y2"]
.map(attr => el.getAttribute(attr))
.map((value, i) => value === String(i + 1))
.reduce((a, b) => a && b, true))
.reduce((a, b) => a && b, true);
expect(result).toBe(true);
});
test("line arguments, missing arguments", () => {
const result1 = ear.svg.line(1, 2, 3);
expect(result1.getAttribute("x2")).toBe("3");
expect(result1.getAttribute("y2")).toBe("");
const result2 = ear.svg.line({ x: 1, y: 2 }, { x: 3 });
expect(result2.getAttribute("x2")).toBe("3");
// expect(result2.getAttribute("y2")).toBe("");
});
test("line setters", () => {
const attrs = ["x1", "y1", "x2", "y2"];
let l = ear.svg.line();
l.setPoints(1, 2, 3, 4);
attrs.forEach((attr, i) => expect(l.getAttribute(attr)).toBe(String([1, 2, 3, 4][i])));
l.setPoints([[1, 2, 3, 4]]);
attrs.forEach((attr, i) => expect(l.getAttribute(attr)).toBe(String([1, 2, 3, 4][i])));
l.setPoints([[1, 2], [3, 4]]);
attrs.forEach((attr, i) => expect(l.getAttribute(attr)).toBe(String([1, 2, 3, 4][i])));
expect(l.attributes.length).toBe(4);
// this will not work
l.setPoints([[1, 2], [3, 4], 5, [6, 7]]);
// attrs.forEach((attr, i) => expect(l.getAttribute(attr)).toBe(String([1, 2, 3, 4][i])));
// expect(l.attributes.length).toBe(4);
// this will not work
l.setPoints("9", "8", "7", "6");
// attrs.forEach((attr, i) => expect(l.getAttribute(attr)).toBe(String([1, 2, 3, 4][i])));
l.setPoints({ x: 5, y: 6 }, { x: 7, y: 8 }, { x: 9, y: 10 });
attrs.forEach((attr, i) => expect(l.getAttribute(attr)).toBe(String([5, 6, 7, 8][i])));
expect(l.attributes.length).toBe(4);
});
================================================
FILE: tests/svg.nodes.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
const NodeAndChildren = {
svg: ["svg", "defs", "desc", "filter", "metadata", "style", "script", "title", "view", "linearGradient", "radialGradient", "pattern", "marker", "symbol", "clipPath", "mask", "g", "circle", "ellipse", "line", "path", "polygon", "polyline", "rect", "text"],
g: ["g", "circle", "ellipse", "line", "path", "polygon", "polyline", "rect", "text"],
// text: ["textPath", "tspan"], // text has another "text" child node that doesn't match
linearGradient: ["stop"],
radialGradient: ["stop"],
defs: ["desc", "filter", "metadata", "style", "script", "title", "view", "linearGradient", "radialGradient", "pattern", "marker", "symbol", "clipPath", "mask"],
filter: ["feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence"],
marker: ["g", "circle", "ellipse", "line", "path", "polygon", "polyline", "rect", "text"],
symbol: ["g", "circle", "ellipse", "line", "path", "polygon", "polyline", "rect", "text"],
clipPath: ["g", "circle", "ellipse", "line", "path", "polygon", "polyline", "rect", "text"],
mask: ["g", "circle", "ellipse", "line", "path", "polygon", "polyline", "rect", "text"],
};
const NodesNames = [
"svg",
"line",
"rect",
"circle",
"ellipse",
"polygon",
"polyline",
"path",
"mask",
"symbol",
"clipPath",
"marker",
"linearGradient",
"radialGradient",
"stop",
"pattern",
"defs",
"desc",
"filter",
"metadata",
"style",
"script",
"title",
"view",
"cdata",
"g",
"text",
"textPath",
"tspan",
"feBlend",
"feColorMatrix",
"feComponentTransfer",
"feComposite",
"feConvolveMatrix",
"feDiffuseLighting",
"feDisplacementMap",
"feDistantLight",
"feDropShadow",
"feFlood",
"feFuncA",
"feFuncB",
"feFuncG",
"feFuncR",
"feGaussianBlur",
"feImage",
"feMerge",
"feMergeNode",
"feMorphology",
"feOffset",
"fePointLight",
"feSpecularLighting",
"feSpotLight",
"feTile",
"feTurbulence",
];
test("node test", () => {
const svg = ear.svg();
Object.keys(NodeAndChildren).forEach(parent => {
const node = svg[parent]();
NodeAndChildren[parent].forEach(child => node[child]());
expect(node.childNodes.length).toBe(NodeAndChildren[parent].length);
NodeAndChildren[parent].forEach((child, i) => expect(node.childNodes[i].nodeName)
.toBe(child));
});
expect(svg.childNodes.length).toBe(Object.keys(NodeAndChildren).length);
Object.keys(NodeAndChildren).forEach((child, i) => expect(svg.childNodes[i].nodeName)
.toBe(child));
});
test("node names", () => {
const createElements = NodesNames.map(nodeName => ear.svg[nodeName]())
.map((node, i) => node.nodeName === NodesNames[i])
.reduce((a, b) => a && b, true);
expect(createElements).toBe(true);
});
================================================
FILE: tests/svg.object.assign.test.js
================================================
import { expect, test } from "vitest";
const test1 = {
a: {
one: {
what: true,
},
two: {
whatagain: true,
},
},
b: {
a: {
what: true,
},
},
};
const test2 = {
a: {
three: {
hi: true,
},
four: {
whatagain: true,
},
},
b: {
b: {
okay: true,
},
},
};
test("object assign", () => {
Object.assign(test1, test2);
expect(test1.a.one == null).toBe(true);
expect(test1.a.two == null).toBe(true);
expect(test1.a.three != null).toBe(true);
expect(test1.a.four != null).toBe(true);
expect(test1.b.a == null).toBe(true);
expect(test1.b.b != null).toBe(true);
});
================================================
FILE: tests/svg.path.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("path", () => {
const p = ear.svg.path();
p.Move(20, 20);
expect(p.getAttribute("d")).toBe("M20 20");
p.line(50, 50);
expect(p.getAttribute("d")).toBe("M20 20l50 50");
p.vertical(30);
expect(p.getAttribute("d")).toBe("M20 20l50 50v30");
p.Curve(50, 0, 0, 50, 10, 10);
expect(p.getAttribute("d")).toBe("M20 20l50 50v30C50 0 0 50 10 10");
p.clear();
// specification around getAttribute when it doesn't exist is "" or null
expect(p.getAttribute("d") === "" || p.getAttribute("d") === null).toBe(true);
});
const path_commands = [
"m", // move
"l", // line
"v", // vertical
"h", // horizontal
"a", // ellipse
"c", // curve
"s", // smoothCurve
"q", // quadCurve
"t", // smoothQuadCurve
"z", // close
];
test("path init from args", () => {
const pathString = "M20 40V60l10 10";
expect(ear.svg.path(pathString).getAttribute("d")).toBe(pathString);
// expect(ear.svg.path({command:"M", values: [20, 40]}).getAttribute("d")).toBe("M20 40");
});
test("path commands", () => {
const pathString = "M20 40V60l10 10";
const path = ear.svg.path(pathString);
path.Line(50, 50);
expect(path.getAttribute("d")).toBe(`${pathString}L50 50`);
const commands = path.getCommands();
const expected = [
{ command: "M", values: [20, 40] },
{ command: "V", values: [60] },
{ command: "l", values: [10, 10] },
{ command: "L", values: [50, 50] },
];
expected.forEach((el, i) => {
expect(commands[i].command).toBe(expected[i].command);
expect(JSON.stringify(commands[i].values))
.toBe(JSON.stringify(expected[i].values));
});
// path.add("H20V60");
// expect(path.getAttribute("d")).toBe(pathString + "L50 50" + "H20V60");
// path.set("H20V60");
// expect(path.getAttribute("d")).toBe("H20V60");
});
test("path commands", () => {
const path = ear.svg.path("M50 50h200");
expect(path.getD()).toBe("M50 50h200");
const path2 = ear.svg.path();
expect(path2.getD()).toBe("");
});
test("path commands", () => {
const path = ear.svg.path("M50 50");
path.addCommand("L", 100, 100);
expect(path.getAttribute("d")).toBe("M50 50L100 100");
path.appendCommand("V", 66);
expect(path.getAttribute("d")).toBe("M50 50L100 100V66");
path.clear();
expect(path.getAttribute("d") === null || path.getAttribute("d") === "").toBe(true);
});
// test("bezier", () => {
// let bez = ear.svg.bezier(0, 0, 25, 75, 75, 25, 100, 100);
// const d = Array.from(bez.attributes).filter(a => a.nodeName === "d").shift();
// expect(d.nodeValue).toBe("M 0,0 C 25,75 75,25 100,100");
// bez.setBezier(0, 0, 100, 0, 100, 100, 0, 100);
// const d2 = Array.from(bez.attributes).filter(a => a.nodeName === "d").shift();
// expect(d2.nodeValue).toBe("M 0,0 C 100,0 100,100 0,100");
// expect(true).toBe(true);
// });
================================================
FILE: tests/svg.polygon.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("argument parsing, polygon", () => {
let poly = ear.svg.polygon([0, 0, 0, 1, 1, 1, 1, 0]);
expect(poly.getAttribute("points")).toBe("0,0 0,1 1,1 1,0");
const polygons = [
ear.svg.polygon(0, 1, 2, 3, 4, 5),
ear.svg.polygon([0, 1], [2, 3], [4, 5]),
ear.svg.polygon([[0, 1], [2, 3], [4, 5]]),
ear.svg.polygon([[0, 1]], [[2, 3]], [[4, 5]]),
ear.svg.polygon({ x: 0, y: 1 }, { x: 2, y: 3 }, { x: 4, y: 5 }),
ear.svg.polygon([{ x: 0, y: 1 }, { x: 2, y: 3 }, { x: 4, y: 5 }]),
ear.svg.polygon([0, 1, 9], [2, 3, 9], [4, 5, 9]),
ear.svg.polygon([[0, 1, 9], [2, 3, 9], [4, 5, 9]]),
ear.svg.polygon([[0, 1, 9]], [[2, 3, 9]], [[4, 5, 9]]),
ear.svg.polygon({ x: 0, y: 1, z: 9 }, { x: 2, y: 3, z: 9 }, { x: 4, y: 5, z: 9 }),
// ear.svg.polygon([{x:0, y:1}], [{x:2, y:3}], [{x:4, y:5}]),
// ear.svg.polygon([[{x:0, y:1}], [{x:2, y:3}], [{x:4, y:5}]]),
];
const result = polygons
.map(p => p.getAttribute("points"))
.map(points => points === "0,1 2,3 4,5")
.reduce((a, b) => a && b, true);
expect(result).toBe(true);
});
test("polygon point methods", () => {
const poly = ear.svg.polygon([0, 0, 0, 1, 1, 1, 1, 0]);
expect(poly.getAttribute("points")).toBe("0,0 0,1 1,1 1,0");
poly.addPoint(6, 7);
expect(poly.getAttribute("points")).toBe("0,0 0,1 1,1 1,0 6,7");
poly.addPoint([3, 4]);
expect(poly.getAttribute("points")).toBe("0,0 0,1 1,1 1,0 6,7 3,4");
});
================================================
FILE: tests/svg.primitives.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("svg and group", () => {
const svg = ear.svg();
svg.appendChild(ear.svg.g());
expect(svg.childNodes.length).toBe(1);
});
test("all primitives", () => {
const group = ear.svg.g();
group.appendChild(ear.svg.line(0, 1, 2, 3));
group.appendChild(ear.svg.rect(0, 1, 2, 3));
group.appendChild(ear.svg.circle(0, 1, 2));
group.appendChild(ear.svg.ellipse(0, 1, 2));
group.appendChild(ear.svg.polygon([[0, 1], [2, 3], [4, 5]]));
group.appendChild(ear.svg.polyline([[0, 1], [2, 3], [4, 5]]));
group.appendChild(ear.svg.text("abc", 0, 1));
const nodeNames = ["line", "rect", "circle", "ellipse", "polygon", "polyline", "text"];
Array.from(group.childNodes).forEach((el, i) => {
expect(el.nodeName).toBe(nodeNames[i]);
});
expect(group.childNodes.length).toBe(7);
});
test("init from SVG", () => {
const svg = ear.svg();
svg.line(0, 1, 2, 3);
svg.rect(0, 1, 2, 3);
svg.circle(0, 1, 2);
svg.ellipse(0, 1, 2);
svg.polygon([[0, 1], [2, 3], [4, 5]]);
svg.polyline([[0, 1], [2, 3], [4, 5]]);
svg.text("abc", 0, 1);
const nodeNames = ["line", "rect", "circle", "ellipse", "polygon", "polyline", "text"];
Array.from(svg.childNodes).forEach((el, i) => {
expect(el.nodeName).toBe(nodeNames[i]);
});
expect(svg.childNodes.length).toBe(7);
});
test("method chaining", () => {
const svg = ear.svg();
expect(svg.line().setPoints(1, 2, 3, 4).getAttribute("x1")).toBe("1");
expect(svg.rect().setSize(3, 4).setOrigin(1, 2).getAttribute("width")).toBe("3");
expect(svg.circle().setCenter(3, 4).getAttribute("cx")).toBe("3");
expect(svg.ellipse().setRadius(1, 2).getAttribute("rx")).toBe("1");
expect(svg.polygon().setPoints(1, 2, 3, 4).getAttribute("points")).toBe("1,2 3,4");
expect(svg.polyline().setPoints(1, 2, 3, 4).getAttribute("points")).toBe("1,2 3,4");
// expect(svg.text().setPoints(1, 2, 3, 4).getAttribute("x")).toBe("1")
});
test("primitives, argument order", () => {
const line0 = ear.svg.line();
const line1 = ear.svg.line(1);
const line2 = ear.svg.line(1, 2);
const line3 = ear.svg.line(1, 2, 3);
const line4 = ear.svg.line(1, 2, 3, 4);
expect(line0.getAttribute("x1") === null || line0.getAttribute("x1") === "")
.toBe(true);
expect(line1.getAttribute("x1") === null || line1.getAttribute("x1") === "")
.toBe(false);
expect(line1.getAttribute("y1") === null || line1.getAttribute("y1") === "")
.toBe(true);
expect(line2.getAttribute("y1") === null || line2.getAttribute("y1") === "")
.toBe(false);
expect(line2.getAttribute("x2") === null || line2.getAttribute("x2") === "")
.toBe(true);
expect(line3.getAttribute("x2") === null || line3.getAttribute("x2") === "")
.toBe(false);
expect(line3.getAttribute("y2") === null || line3.getAttribute("y2") === "")
.toBe(true);
expect(line4.getAttribute("y2") === null || line4.getAttribute("y2") === "")
.toBe(false);
const rect0 = ear.svg.rect();
const rect1 = ear.svg.rect(1);
const rect2 = ear.svg.rect(1, 2);
const rect3 = ear.svg.rect(1, 2, 3);
const rect4 = ear.svg.rect(1, 2, 3, 4);
expect(rect0.getAttribute("x") === null || rect0.getAttribute("x") === "")
.toBe(true);
expect(rect0.getAttribute("width") === null || rect0.getAttribute("width") === "")
.toBe(true);
expect(rect1.getAttribute("x") === null || rect1.getAttribute("x") === "")
.toBe(true);
expect(rect1.getAttribute("y") === null || rect1.getAttribute("y") === "")
.toBe(true);
expect(rect1.getAttribute("width") === null || rect1.getAttribute("width") === "")
.toBe(false);
expect(rect1.getAttribute("height") === null || rect1.getAttribute("height") === "")
.toBe(true);
expect(rect2.getAttribute("x") === null || rect2.getAttribute("x") === "")
.toBe(true);
expect(rect2.getAttribute("y") === null || rect2.getAttribute("y") === "")
.toBe(true);
expect(rect2.getAttribute("width") === null || rect2.getAttribute("width") === "")
.toBe(false);
expect(rect2.getAttribute("height") === null || rect2.getAttribute("height") === "")
.toBe(false);
expect(rect3.getAttribute("x") === null || rect3.getAttribute("x") === "")
.toBe(true);
expect(rect3.getAttribute("y") === null || rect3.getAttribute("y") === "")
.toBe(true);
expect(rect3.getAttribute("width") === null || rect3.getAttribute("width") === "")
.toBe(false);
expect(rect3.getAttribute("height") === null || rect3.getAttribute("height") === "")
.toBe(false);
expect(rect4.getAttribute("x") === null || rect4.getAttribute("x") === "")
.toBe(false);
expect(rect4.getAttribute("y") === null || rect4.getAttribute("y") === "")
.toBe(false);
expect(rect4.getAttribute("width") === null || rect4.getAttribute("width") === "")
.toBe(false);
expect(rect4.getAttribute("height") === null || rect4.getAttribute("height") === "")
.toBe(false);
const circle0 = ear.svg.circle();
const circle1 = ear.svg.circle(1);
const circle2 = ear.svg.circle(1, 2);
const circle3 = ear.svg.circle(1, 2, 3);
expect(circle0.getAttribute("cx") === null || circle0.getAttribute("cx") === "")
.toBe(true);
expect(circle0.getAttribute("cy") === null || circle0.getAttribute("cy") === "")
.toBe(true);
expect(circle0.getAttribute("r") === null || circle0.getAttribute("r") === "")
.toBe(true);
expect(circle1.getAttribute("cx") === null || circle1.getAttribute("cx") === "")
.toBe(true);
expect(circle1.getAttribute("cy") === null || circle1.getAttribute("cy") === "")
.toBe(true);
expect(circle1.getAttribute("r") === null || circle1.getAttribute("r") === "")
.toBe(false);
expect(circle2.getAttribute("cx") === null || circle2.getAttribute("cx") === "")
.toBe(false);
expect(circle2.getAttribute("cy") === null || circle2.getAttribute("cy") === "")
.toBe(false);
expect(circle2.getAttribute("r") === null || circle2.getAttribute("r") === "")
.toBe(true);
expect(circle3.getAttribute("cx") === null || circle3.getAttribute("cx") === "")
.toBe(false);
expect(circle3.getAttribute("cy") === null || circle3.getAttribute("cy") === "")
.toBe(false);
expect(circle3.getAttribute("r") === null || circle3.getAttribute("r") === "")
.toBe(false);
const ellipse1 = ear.svg.ellipse(1);
const ellipse2 = ear.svg.ellipse(1, 2);
const ellipse3 = ear.svg.ellipse(1, 2, 3);
const ellipse4 = ear.svg.ellipse(1, 2, 3, 4);
const text1s = ear.svg.text("abc", 0, 1);
});
// test("custom primitives", () => {
// const group = ear.svg.g();
// group.appendChild(ear.svg.bezier(0, 1, 2, 3, 4, 5, 6, 7));
// group.appendChild(ear.svg.arc(0, 1, 2, 3, 4));
// group.appendChild(ear.svg.wedge(0, 1, 2, 3, 4));
// group.appendChild(ear.svg.arcEllipse(0, 1, 2, 3, 4, 5));
// group.appendChild(ear.svg.wedgeEllipse(0, 1, 2, 3, 4, 5));
// group.appendChild(ear.svg.arrow([0, 1], [2, 3]));
// const nodeNames = ["path", "path", "path", "path", "path", "g"];
// Array.from(group.childNodes).forEach((el, i) => {
// expect(el.nodeName).toBe(nodeNames[i]);
// });
// expect(group.childNodes.length).toBe(6);
// });
================================================
FILE: tests/svg.rect.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("rect", () => {
const rect = ear.svg.rect(1, 2, 3, 4);
expect(rect.getAttribute("x")).toBe("1");
expect(rect.getAttribute("y")).toBe("2");
expect(rect.getAttribute("width")).toBe("3");
expect(rect.getAttribute("height")).toBe("4");
const rect2 = ear.svg.rect(3, 4);
expect(rect2.getAttribute("y") === null || rect2.getAttribute("y") === "")
.toBe(true);
expect(rect2.getAttribute("y") === null || rect2.getAttribute("y") === "")
.toBe(true);
expect(rect2.getAttribute("width")).toBe("3");
expect(rect2.getAttribute("height")).toBe("4");
});
test("rect, args, negative width height", () => {
const rect = ear.svg.rect(300, 200, -300, -200);
expect(rect.getAttribute("x")).toBe("0");
expect(rect.getAttribute("y")).toBe("0");
expect(rect.getAttribute("width")).toBe("300");
expect(rect.getAttribute("height")).toBe("200");
const rect2 = ear.svg.rect(300, 200, -320, -220);
expect(rect2.getAttribute("x")).toBe("-20");
expect(rect2.getAttribute("y")).toBe("-20");
expect(rect2.getAttribute("width")).toBe("320");
expect(rect2.getAttribute("height")).toBe("220");
const rect3 = ear.svg.rect(300, 200, 320, -220);
expect(rect3.getAttribute("x")).toBe("300");
expect(rect3.getAttribute("y")).toBe("-20");
expect(rect3.getAttribute("width")).toBe("320");
expect(rect3.getAttribute("height")).toBe("220");
const rect4 = ear.svg.rect(300, 200, -320, 220);
expect(rect4.getAttribute("x")).toBe("-20");
expect(rect4.getAttribute("y")).toBe("200");
expect(rect4.getAttribute("width")).toBe("320");
expect(rect4.getAttribute("height")).toBe("220");
const rect5 = ear.svg.rect(-320, -220);
expect(rect5.getAttribute("x")).toBe("-320");
expect(rect5.getAttribute("y")).toBe("-220");
expect(rect5.getAttribute("width")).toBe("320");
expect(rect5.getAttribute("height")).toBe("220");
const rect6 = ear.svg.rect(-320, 220);
expect(rect6.getAttribute("x")).toBe("-320");
expect(rect6.getAttribute("y") === null || rect6.getAttribute("y") === "")
.toBe(true);
expect(rect6.getAttribute("width")).toBe("320");
expect(rect6.getAttribute("height")).toBe("220");
});
================================================
FILE: tests/svg.stylesheet.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("style", () => {
const styleString = "line{stroke:purple};";
const svg = ear.svg();
svg.stylesheet(styleString);
const style = Array.from(svg.childNodes).filter(a => a.nodeName === "style").shift();
expect(style.childNodes[0].textContent).toBe(styleString);
});
test("style setTextContent", () => {
const styleString = "line{stroke:purple};";
const styleString2 = "circle { fill: '#000' }";
const svg = ear.svg();
const stylesheet = svg.stylesheet(styleString);
stylesheet.setTextContent(styleString2);
const style = Array.from(svg.childNodes).filter(a => a.nodeName === "style").shift();
expect(style.childNodes[0].textContent).toBe(styleString2);
});
================================================
FILE: tests/svg.svg.animation.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("animation", () => {
const svg = ear.svg();
svg.play = e => {};
svg.stop();
});
================================================
FILE: tests/svg.svg.args.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
const { DOMParser } = xmldom;
test("argument parsing, svg", () => {
const svg0 = ear.svg();
const vb0 = svg0.getAttribute("viewBox");
expect(vb0 == null || vb0 === "").toBe(true);
const svg1 = ear.svg(400, 500);
expect(svg1.getAttribute("viewBox")).toBe("0 0 400 500");
const svg2 = ear.svg(1, 2, 400, 500);
expect(svg2.getAttribute("viewBox")).toBe("1 2 400 500");
const svg3 = ear.svg(1, 400, 500);
const vb3 = svg3.getAttribute("viewBox");
expect(vb3 == null || vb3 === "").toBe(true);
});
test("no parent", () => {
const svg = ear.svg(600, 600);
expect(svg.parentNode).toBe(null);
});
test("parent element", () => {
const parent = (new DOMParser()).parseFromString("", "text/xml").documentElement;
const svg = ear.svg(600, 600, parent);
expect(svg.parentNode.nodeName).toBe("div");
});
// test("svg embed as string", () => {
// // this string contains \n newlines, the load method targets and removes them
// // by testing the element at [0] this is also testing the newline removal
// const svgString = ``;
// const svg = ear.svg(svgString);
// expect(svg.childNodes.length).toBe(1);
// expect(svg.childNodes[0].nodeName).toBe("line");
// });
================================================
FILE: tests/svg.svg.background.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("set background", () => {
const svg = ear.svg();
svg.background("black", true);
svg.background("#332698", false);
expect(svg.childNodes.length).toBe(1);
});
================================================
FILE: tests/svg.svg.controls.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("deprecated", () => expect(true).toBe(true));
// test("controls", () => {
// const svg = ear.svg();
// const controlLayer = svg.g();
// svg.controls(3)
// .svg(() => ear.svg.circle(svg.getWidth() * 0.1).fill("gray"))
// .position(() => [svg.getWidth() * 0.5, svg.getHeight() * 0.5])
// .parent(controlLayer)
// .onChange((point) => {
// point.svg.setRadius(Math.random() * 10);
// }, true);
// });
================================================
FILE: tests/svg.svg.load.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("", () => expect(true).toBe(true));
// const path = "./tests/dragon.svg";
// const testSVG = ``;
// test("loading callback", done => {
// ear.svg(400, 400, () => {
// done();
// });
// });
// // test("async attempt promises", () => {
// // const svg = ear.svg();
// // svg.load(path)
// // .then(() => {});
// // expect(svg.childNodes.length).toBe(0);
// // });
// test("async using fs", (done) => {
// const svg = ear.svg();
// fs.readFile(path, { encoding: "utf8" }, (err, data) => {
// svg.load(data);
// const polyline = Array.from(svg.childNodes)
// .filter(a => a.nodeName === "polyline")
// .shift();
// expect(polyline !== undefined).toBe(true);
// done();
// });
// });
// test("async attempt with node", () => {
// const svg = ear.svg();
// svg.load(path);
// expect(svg.childNodes.length).toBe(0);
// });
// test("sync", () => {
// const svg = ear.svg();
// svg.load(testSVG);
// const circle = Array.from(svg.childNodes)
// .filter(a => a.nodeName === "circle")
// .shift();
// expect(circle !== undefined).toBe(true);
// });
// test("import load()", () => {
// const svgString = ``;
// const svgFromString = ear.svg();
// expect(svgFromString.childNodes.length).toBe(0);
// svgFromString.load(svgString);
// expect(svgFromString.childNodes.length).toBe(1);
// // console.log("svgFromString.childNodes", svgFromString.childNodes);
// // console.log("window", window);
// // console.log("window.document", window.document);
// });
// test("import string in argument", () => {
// const svgString = ``;
// const svg = ear.svg(svgString);
// expect(svg.childNodes.length).toBe(1);
// // console.log("svg.childNodes", svg.childNodes);
// // console.log("window", window);
// // console.log("window.document", window.document);
// });
// test("import string in argument with attributes", () => {
// const svgString = ``;
// const svg = ear.svg(svgString);
// expect(svg.getAttribute("viewBox")).toBe("10 20 800 600");
// expect(svg.getAttribute("display")).toBe("none");
// });
================================================
FILE: tests/svg.svg.save.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("", () => expect(true).toBe(true));
// test("export options", () => {
// const svg = ear.svg();
// const save0 = svg.save();
// const save1 = svg.save({ output: "string" });
// const save2 = svg.save({ output: "svg" });
// const save3 = svg.save({ windowStyle: true });
// expect(typeof save0).toBe("string");
// expect(typeof save1).toBe("string");
// expect(typeof save2).toBe("object");
// expect(typeof save3).toBe("string");
// });
// test("svg export", () => {
// const svg = ear.svg();
// svg.line(0, 0, 300, 150).stroke("black").strokeWidth(5);
// const asString = svg.save();
// const asSvg = svg.save({ output: "svg" });
// const expectedString = ``;
// // const expectedString = ``;
// expect(asString).toBe(expectedString);
// expect(asSvg.childNodes.length).toBe(1);
// expect(asSvg.childNodes[0].nodeName).toBe("line");
// });
// test("svg export with comments", () => {
// const svgString = ``;
// const svg = ear.svg(svgString);
// const asSvg = svg.save({ output: "svg" });
// expect(asSvg.childNodes.length).toBe(3);
// expect(asSvg.childNodes[0].nodeName).toBe("#comment");
// expect(asSvg.childNodes[1].nodeName).toBe("line");
// expect(asSvg.childNodes[2].nodeName).toBe("#comment");
// });
================================================
FILE: tests/svg.svg.viewbox.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("viewBox get and set", () => {
const svg = ear.svg();
svg.setViewBox(1, 2, 3, 4);
expect(svg.getAttribute("viewBox")).toBe("1 2 3 4");
svg.setViewBox("-10 -10 400 500");
expect(svg.getAttribute("viewBox")).toBe("-10 -10 400 500");
svg.setViewBox(300, 200);
expect(svg.getAttribute("viewBox")).toBe("0 0 300 200");
});
test("get width and height", () => {
const svg = ear.svg();
expect(svg.getWidth()).toBe(undefined);
expect(svg.getHeight()).toBe(undefined);
const svg2 = ear.svg(400, 300);
expect(svg2.getWidth()).toBe(400);
expect(svg2.getHeight()).toBe(300);
const svg3 = ear.svg(0, 0, 800, 600);
expect(svg3.getWidth()).toBe(800);
expect(svg3.getHeight()).toBe(600);
});
================================================
FILE: tests/svg.transforms.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("parseTransform", () => {
const transformString = "translate(20 100) rotate(45) scale(2 1) matrix(0 -1 1 0 0 0)";
const result = ear.svg.parseTransform(transformString);
["translate", "rotate", "scale", "matrix"]
.forEach((name, i) => expect(result[i].transform).toBe(name));
});
test("transformStringToMatrix", () => {
const transformString = "translate(20 100) rotate(45) scale(2 1) matrix(0 -1 1 0 0 0)";
expect(ear.svg.transformStringToMatrix(transformString).length).toBe(6);
const transformString2 = "translate(20) skewX(4) rotate(45 2 3) skewY(2) scale(2)";
expect(ear.svg.transformStringToMatrix(transformString2).length).toBe(6);
});
test("transformStringToMatrix bad input", () => {
const transformString = "translate() rotate() scale() skewX() skewY()";
expect(ear.svg.transformStringToMatrix(transformString).length).toBe(6);
});
test("transforms", () => {
const svg = ear.svg();
const transformString = "translate(20 100) rotate(45) translate(50 50) matrix(0 -1 1 0 0 0)";
["svg", "g", "circle", "ellipse", "line", "path", "polygon", "polyline", "rect"]
// , "text"
.map(node => svg[node]()
.translate("20 100")
.rotate(45)
.translate(50, 50)
.matrix(0, -1, 1, 0, 0, 0))
.forEach(p => expect(p.getAttribute("transform"))
.toBe(transformString));
});
test("clear transform", () => {
const svg = ear.svg();
const l = svg.line(0, 0, 400, 400)
.rotate(45)
.translate(50, 50)
.clearTransform();
const transform = l.getAttribute("transform");
expect(transform == null || transform === "").toBe(true);
});
================================================
FILE: tests/svg.types.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
const primitives = [
"line",
"circle",
"ellipse",
"rect",
"polygon",
"polyline",
"text",
];
const groupLevel = ["g"];
const defsLevel = [
"style",
"clipPath",
"mask",
"script",
];
const rootLevel = [
"defs",
"style",
// "clipPath", // conflict, clipPath is a constructor AND an assigner
// "mask",
];
const customPrimitives = [
"bezier",
"wedge",
"arc",
"parabola",
"regularPolygon",
"arrow",
];
test("svg and group", () => {
const svg = ear.svg();
primitives.forEach(p => expect(typeof svg[p]).toBe("function"));
groupLevel.forEach(g => expect(typeof svg[g]).toBe("function"));
rootLevel.forEach(r => expect(typeof svg[r]).toBe("function"));
const group = ear.svg.g();
primitives.forEach(p => expect(typeof group[p]).toBe("function"));
groupLevel.forEach(g => expect(typeof group[g]).toBe("function"));
rootLevel.forEach(r => expect(typeof group[r]).not.toBe("function"));
const defs = ear.svg.defs();
// primitives.forEach(p => expect(typeof defs[p]).toBe("function"));
// groupLevel.forEach(g => expect(typeof defs[g]).toBe("function"));
// defsLevel.forEach(r => expect(typeof defs[r]).toBe("function"));
});
================================================
FILE: tests/svg.urls.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("custom id names", () => {
["clipPath", "symbol", "mask", "marker"].forEach(nodeName => {
const svg = ear.svg();
const test1 = svg[nodeName]();
const test2 = svg[nodeName]("what is");
expect(test1.getAttribute("id").length).toBe(5);
expect(test2.getAttribute("id")).toBe("what is");
});
});
test("assign to types", () => {
const svg = ear.svg();
const things = ["clipPath", "symbol", "mask", "marker", "marker", "marker"]
.map(nodeName => svg[nodeName]());
const line = svg.line(1, 2, 3, 4);
["clipPath", "mask", "symbol", "markerEnd", "markerMid", "markerStart"]
.forEach((method, i) => line[method](things[i]));
// these should be the attributes
["x1", "y1", "x2", "y2", "clip-path", "mask", "symbol", "marker-end", "marker-mid", "marker-start"]
.forEach((attr, i) => expect(line.attributes[i].name).toBe(attr));
});
================================================
FILE: tests/svg.use.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
// const ear = require("./ear");
test("", () => expect(true).toBe(true));
// test("use with rabbit ear", () => {
// ear.use(SVG);
// expect(typeof ear.segment.svg).toBe("function");
// expect(typeof ear.segment.svg).toBe("function");
// expect(typeof ear.circle.svg).toBe("function");
// expect(typeof ear.ellipse.svg).toBe("function");
// expect(typeof ear.rect.svg).toBe("function");
// expect(typeof ear.polygon.svg).toBe("function");
// ear.segment.svg();
// ear.circle.svg();
// ear.ellipse.svg();
// ear.rect.svg();
// ear.polygon.svg();
// });
================================================
FILE: tests/svg.window.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.svg.window = xmldom;
test("environment", () => {
expect(true).toBe(true);
});
================================================
FILE: tests/webgl.initialize.test.js
================================================
import { expect, test } from "vitest";
import xmldom from "@xmldom/xmldom";
import ear from "../src/index.js";
ear.window = xmldom;
test("webgl cannot be tested server side", () => expect(true).toBe(true));
// here is a test that can be done in the browser.
// test("initialize webgl", () => {
// const FOLD = ear.graph.bird();
// const canvas = window.document.createElement("canvas");
// document.body.appendChild(canvas);
// // gl is the WebGL context. version is either 1 or 2.
// const { gl, version } = ear.webgl.initializeWebGL(canvas);
// // Initialize a WebGL viewport based on the dimensions of the canvas
// ear.webgl.rebuildViewport(gl, canvas);
// // draw creasePattern style, or foldedForm style
// const models = ear.webgl.creasePattern(gl, version, FOLD);
// // program = ear.webgl.foldedForm(gl, version, FOLD);
// const projectionMatrix = ear.webgl.makeProjectionMatrix(canvas, "orthographic");
// const modelViewMatrix = ear.webgl.makeModelMatrix(FOLD);
// gl.enable(gl.BLEND);
// gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
// gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// models.forEach(model => {
// ear.webgl.drawModel(gl, version, model, model.makeUniforms(gl, {
// projectionMatrix,
// modelViewMatrix
// }));
// });
// models.forEach(model => ear.webgl.deallocModel(gl, model));
// });
================================================
FILE: tsconfig.json
================================================
{
"include": ["src/**/*"],
"compilerOptions": {
// changes the first line of index.d.ts to declare a module name
"esModuleInterop": true,
"target": "ES2022", // "ES2015",
"module": "nodenext", // "es2015",
"lib": ["ES2022", "DOM"], // ["es2015", "DOM"],
"moduleResolution": "nodenext", // "node",
// Tells TypeScript to read JS files, as
// normally they are ignored as source files
"allowJs": true,
"checkJs": true,
// Generate d.ts files
"declaration": true,
// Types should go into this directory.
// Removing this would place the .d.ts files
// next to the .js files
"declarationDir": "./types", // "./module"
"outDir": "./types", // "./module"
"rootDir": "./src",
// This compiler run should
// only output d.ts files
"emitDeclarationOnly": true,
// go to js file when using IDE functions like
// "Go to Definition" in VSCode
"declarationMap": true
}
}
================================================
FILE: typedoc.config.json
================================================
{
"entryPoints": ["./src"],
"out": "docs",
"name": "Rabbit Ear",
"includeVersion": true,
"entryPointStrategy": "expand",
"exclude": ["**/index.js"], // "**/*.d.ts"
"customCss": "docs-style.css"
}