diff --git a/docs/en/graphics/background/sky.mdx b/docs/en/graphics/background/sky.mdx index e72d673465..e30ce0b8d6 100644 --- a/docs/en/graphics/background/sky.mdx +++ b/docs/en/graphics/background/sky.mdx @@ -43,13 +43,13 @@ Procedural sky is the default background in 3D projects in the editor. You can a ### Code to Set Procedural Sky ```typescript -// 创建大气散射材质 +// Create the atmospheric scattering material const skyMaterial = new SkyProceduralMaterial(engine); -// 设置天空盒 +// Set the procedural sky background const background = scene.background; background.mode = BackgroundMode.Sky; background.sky.material = skyMaterial; -background.sky.mesh = PrimitiveMesh.createSphere(engine); +background.sky.mesh = PrimitiveMesh.createSphere(engine, 0.5); ``` ### Properties diff --git a/docs/en/graphics/mesh/primitiveMesh.mdx b/docs/en/graphics/mesh/primitiveMesh.mdx index c7feaea26f..a19599b16f 100644 --- a/docs/en/graphics/mesh/primitiveMesh.mdx +++ b/docs/en/graphics/mesh/primitiveMesh.mdx @@ -12,19 +12,31 @@ label: Graphics/Mesh The editor has built-in basic geometries such as `Cube`, `Sphere`, and `Cylinder`, which can be directly placed in the model by clicking `+` on the left node tree: -image-20231009111916680 +image-20231009111916680 Of course, we can also click `1` in the component panel to add the `Mesh Renderer` component, and click `2` to bind the desired basic geometry: -image-20231009112014068 +image-20231009112014068 Built-in geometries not meeting your needs? You can create a `Mesh` asset in the **[Asset Panel](/en/docs/assets/interface)** by **right-clicking** → **Create** → **PrimitiveMesh**, and adjust the parameters of the `Mesh` to meet your requirements. -image-20231009111916680 +image-20231009111916680 ## Script Usage -The currently provided geometries are as follows: +The following examples show common geometries. The complete factory list appears under [Procedural geometry](#procedural-geometry). - [createCuboid](/apis/core/#PrimitiveMesh-createCuboid) **Cuboid** @@ -32,7 +44,7 @@ The currently provided geometries are as follows: const entity = rootEntity.createChild("cuboid"); entity.transform.setPosition(0, 1, 0); const renderer = entity.addComponent(MeshRenderer); -renderer.mesh = PrimitiveMesh.createCuboid(engine); +renderer.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); // Create material const material = new BlinnPhongMaterial(engine); material.emissiveColor.set(1, 1, 1, 1); @@ -45,7 +57,7 @@ renderer.setMaterial(material); const entity = rootEntity.createChild("sphere"); entity.transform.setPosition(0, 1, 0); const renderer = entity.addComponent(MeshRenderer); -renderer.mesh = PrimitiveMesh.createSphere(engine); +renderer.mesh = PrimitiveMesh.createSphere(engine, 0.5); // Create material const material = new BlinnPhongMaterial(engine); material.emissiveColor.set(1, 1, 1, 1); @@ -58,7 +70,7 @@ renderer.setMaterial(material); const entity = rootEntity.createChild("plane"); entity.transform.setPosition(0, 1, 0); const renderer = entity.addComponent(MeshRenderer); -renderer.mesh = PrimitiveMesh.createPlane(engine); +renderer.mesh = PrimitiveMesh.createPlane(engine, 1, 1); // Create material const material = new BlinnPhongMaterial(engine); material.emissiveColor.set(1, 1, 1, 1); @@ -71,7 +83,7 @@ renderer.setMaterial(material); const entity = rootEntity.createChild("cylinder"); entity.transform.setPosition(0, 1, 0); const renderer = entity.addComponent(MeshRenderer); -renderer.mesh = PrimitiveMesh.createCylinder(engine); +renderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); // Create material const material = new BlinnPhongMaterial(engine); material.emissiveColor.set(1, 1, 1, 1); @@ -84,7 +96,7 @@ renderer.setMaterial(material); const entity = rootEntity.createChild("torus"); entity.transform.setPosition(0, 1, 0); const renderer = entity.addComponent(MeshRenderer); -renderer.mesh = PrimitiveMesh.createTorus(engine); +renderer.mesh = PrimitiveMesh.createTorus(engine, 0.5, 0.1); // Create material const material = new BlinnPhongMaterial(engine); material.emissiveColor.set(1, 1, 1, 1); @@ -97,7 +109,7 @@ renderer.setMaterial(material); const entity = rootEntity.createChild("cone"); entity.transform.setPosition(0, 1, 0); const renderer = entity.addComponent(MeshRenderer); -renderer.mesh = PrimitiveMesh.createCone(engine); +renderer.mesh = PrimitiveMesh.createCone(engine, 0.5, 2); // Create material const material = new BlinnPhongMaterial(engine); material.emissiveColor.set(1, 1, 1, 1); @@ -110,9 +122,240 @@ renderer.setMaterial(material); const entity = rootEntity.createChild("capsule"); entity.transform.setPosition(0, 1, 0); const renderer = entity.addComponent(MeshRenderer); -renderer.mesh = PrimitiveMesh.createCapsule(engine); +renderer.mesh = PrimitiveMesh.createCapsule(engine, 0.5, 2); // Create material const material = new BlinnPhongMaterial(engine); material.emissiveColor.set(1, 1, 1, 1); renderer.setMaterial(material); ``` + +## Procedural geometry + +Each factory takes its required shape inputs first, followed by an optional named settings object. Dimensions, radii, contours and paths must be explicit. Options contain subdivisions, angular ranges and mesh settings; omit the object or its fields to use their documented defaults. For example, `createSphere` takes a radius followed by `SphereMeshOptions`: + +```ts +const smallSphere = PrimitiveMesh.createSphere(engine, 0.5); +const sphere = PrimitiveMesh.createSphere(engine, 1); +const smoothSphere = PrimitiveMesh.createSphere(engine, 1, { subdivisionLevel: 4 }); +const cube = PrimitiveMesh.createCuboid(engine, 2, 2, 2); +const box = PrimitiveMesh.createCuboid(engine, 2, 3, 4); +const ground = PrimitiveMesh.createPlane(engine, 10, 10); +const cylinder = PrimitiveMesh.createCylinder(engine, 0.5, 2); +const frustum = PrimitiveMesh.createTruncatedCone(engine, 0.25, 0.5, 2); +const mirroredKnot = PrimitiveMesh.createTorusKnot(engine, 1, 0.1, 2, -3); +``` + +Cuboid width, height and depth are separate required arguments. Plane width and depth are also required. Subsequent subdivision counts for planes and cuboids default to the first direction. Spheres use one subdivision level, defaulting to 3 and clamped to 1 through 6. Cylinders have one radius; use `createTruncatedCone` for different top and bottom radii. Rings take the required outer radius first, followed by the required inner radius. + +For torus knots, `axisTurns` counts revolutions around the central axis and `crossSectionTurns` counts revolutions around the torus cross-section. Both are signed integers, independent of mesh subdivisions. Negative values reverse the corresponding winding direction; zero keeps that angle fixed. At least one must be nonzero. + +| Capability | Methods | +| --- | --- | +| Plane, cuboid, sphere | `createPlane`, `createCuboid`, `createSphere` | +| Cylinder, frustum, cone, capsule | `createCylinder`, `createTruncatedCone`, `createCone`, `createCapsule` | +| Disk, annulus, torus, torus knot | `createCircle`, `createRing`, `createTorus`, `createTorusKnot` | +| Regular polyhedra | `createTetrahedron`, `createOctahedron`, `createIcosahedron`, `createDodecahedron` | +| Revolved surface, path tube, polygon, extruded polygon, rounded cuboid | `createRevolvedSurface`, `createTube`, `createPolygon`, `createExtrudedPolygon`, `createRoundedCuboid` | + +### Subdivisions, angles and caps + +Dimensions are required arguments; subdivision counts remain in the optional settings object. For tubes and torus knots, `pathSegments` controls subdivisions along the path. Tori use `ringSegments` around the ring. `radialSegments` controls the tube cross-section. Capsule `capSegments` controls each pole-to-equator section independently; `cylinderHeight` describes the straight section. Regular polyhedra use `edgeSegments`, and rounded cuboids use `roundingSegments`. + +Angle ranges belong to the options object. Angles use **degrees**. Ranges use `Vector2`, with `x` as the start angle and `y` as the end angle. Use continuous angles across a full turn, such as `new Vector2(350, 370)`. Cylinders, truncated cones and cones rotate around Y from -Z towards -X; revolved surfaces start from +Z towards +X. A sphere's vertical angle starts at +Y. + +```ts +import { PrimitiveMeshCapMode, Vector2 } from "@galacean/engine"; + +const hemisphere = PrimitiveMesh.createSphere(engine, 1, { verticalAngleRange: new Vector2(0, 90) }); +const openCylinder = PrimitiveMesh.createCylinder(engine, 0.5, 2, { caps: PrimitiveMeshCapMode.None }); +const cupWall = PrimitiveMesh.createCylinder(engine, 0.5, 2, { caps: PrimitiveMeshCapMode.Bottom }); +const halfRing = PrimitiveMesh.createRing(engine, 1, 0.5, { angleRange: new Vector2(0, 180) }); +``` + +Cylinder and frustum `caps` use `PrimitiveMeshCapMode`: `Both` (default), `Top`, `Bottom` or `None`. Top faces +Y and bottom faces -Y. Angular cut boundaries remain open. A cone uses the boolean `cap` for its base. Circles, rings and polygons lie in XY facing +Z. Ground planes lie in XZ facing +Y. + +`createSphere` projects a subdivided cube onto a sphere and accepts `horizontalAngleRange` and `verticalAngleRange`. Horizontal angles start at -X towards +Z; vertical angles start at +Y. Sections retain the subdivided surface and leave their cut boundaries open. A range such as `new Vector2(350, 370)` crosses the horizontal seam. Changing subdivisions controls the surface resolution, including the cut boundaries. + +### Contours and paths + +Polygon contours use `Vector2` arrays. Pass a point array for a simple polygon. Use `{ points, holes }` for a polygon containing holes, or an array of these objects for multiple polygons. Polygon contours close automatically, so the first point need not be repeated. + +`createPolygon` creates a zero-thickness surface in XY facing +Z, without side walls. `createExtrudedPolygon` gives the contour depth or sweeps it along a path, generating side walls and any end caps. + +`createRevolvedSurface` revolves a `Vector2` profile around Y: `x` is the radius from the Y axis and `y` is the height, both in local units. Consecutive profile points are connected in order; repeat the first point to close a profile loop. End caps and wall thickness are not added automatically. A profile can include inner and outer walls, or end on the axis to close the surface when revolved through a full turn. Path points for tubes and extrusions use `Vector3` arrays in local coordinates. + +```ts +import { Vector2, Vector3 } from "@galacean/engine"; + +const profile = [new Vector2(0, 0), new Vector2(0.8, 0), new Vector2(0.4, 1), new Vector2(0.5, 1.5)]; +const revolvedSurface = PrimitiveMesh.createRevolvedSurface(engine, profile, { segments: 32 }); + +const outline = [new Vector2(-2, -2), new Vector2(2, -2), new Vector2(2, 2), new Vector2(-2, 2)]; +const hole = [new Vector2(-1, -1), new Vector2(-1, 1), new Vector2(1, 1), new Vector2(1, -1)]; +const face = PrimitiveMesh.createPolygon(engine, { points: outline, holes: [hole] }); +const solid = PrimitiveMesh.createExtrudedPolygon(engine, { points: outline, holes: [hole] }, 0.5); +const beveled = PrimitiveMesh.createExtrudedPolygon(engine, outline, 0.5, { + bevelWidth: 0.05, + contourOffset: 0.02, + depthSegments: 1 +}); +const path = Array.from({ length: 65 }, (_, i) => { + const t = i / 64; + return new Vector3(4 * t, Math.sin(t * Math.PI * 2), 0); +}); +const tube = PrimitiveMesh.createTube(engine, path, 0.1, { pathSegments: 64 }); +const swept = PrimitiveMesh.createExtrudedPolygon(engine, outline, path, { pathSegments: 64 }); +const loop = [new Vector3(-4, 0, -4), new Vector3(4, 0, -4), new Vector3(4, 0, 4), new Vector3(-4, 0, 4)]; +const closedPath = PrimitiveMesh.createExtrudedPolygon(engine, outline, loop, { closedPath: true, pathSegments: 32 }); +``` + +`createExtrudedPolygon` provides two overloads: + +- `depth: number` extrudes along +Z with side walls and both end caps. `LinearExtrudedPolygonMeshOptions` controls `depthSegments`, bevels and material grouping. +- `path: readonly Vector3[]` extrudes along a spatial path. `PathExtrudedPolygonMeshOptions` controls `pathSegments`, `closedPath` and material grouping. Open paths have both end caps; closed paths join the end cross-sections without caps. + +Linear extrusion defaults to no bevels. A positive `bevelWidth` enables beveling, with `bevelDepth` defaulting to the same value. Path extrusion has no bevel settings. Paths are sampled at equal distances along their line segments. Sample curves into points before creating the mesh, as shown above. + +For tubes and path extrusions, `closedPath` defaults to `false`. Set it to `true` to join the path ends and align the first and last cross-sections; the closing point need not be repeated. Closed extrusions use at least three path segments and have no end caps. Open extrusions have two end caps; tubes have no end caps in either mode. + +`contourOffset` defaults to `0` and shifts the side-wall outline: positive values expand the solid and contract holes, while negative values do the reverse. It also applies when `bevelWidth` is `0`. Bevels are cut into this outline and included in `depth`, so they do not increase the total depth. + +### UV mapping + +The directions below describe increasing UV0 values in local space, assuming positive dimensions and default angle ranges. + +| Geometry | UV mapping | +| --- | --- | +| Plane | U increases along +X and V along +Z; both span 0–1. | +| Cuboid and rounded cuboid | Each face uses its own 0–1 square, with the directions listed below. Rounded cuboids account for rounded edge length. | +| Sphere | U follows the requested horizontal interval, starting at -X towards +Z by default. V follows the requested vertical interval from its upper to lower boundary. Each interval maps to 0–1. | +| Cylinder, truncated cone and cone sides | U spans the selected angular range from 0 to 1, starting at -Z towards -X by default. V is 0 at the top and 1 at the bottom. | +| Cylinder, truncated cone and cone caps | U increases along +X and V along -Z on both ends. The center is (0.5, 0.5), and each cap's diameter spans 0–1. | +| Capsule | U wraps around Y from -Z towards -X. V runs from 0 at the top to 1 at the bottom, proportional to surface length along the hemispheres and cylinder. | +| Torus | U spans `ringAngleRange` and V spans `tubeAngleRange`, each from 0 to 1. | +| Circle and flat ring | U increases along +X and V along +Y. The full outer disk's bounding square maps to 0–1; angular cuts keep these coordinates. | +| Four regular polyhedra | U wraps around Y from +X towards -Z, with its seam at +X. V runs from 0 at +Y to 1 at -Y. | +| Revolved surface | U spans the revolution from 0 to 1. V advances from 0 to 1 in equal steps per profile point, following input order. | +| Tube | U measures normalized path distance; V runs around the generated cross-section from 0 to 1. | +| Torus knot | U follows the knot parameter from 0 to 1; V runs around the generated cross-section from 0 to 1. | +| Polygon | U = local X and V = local Y, without normalization. | +| Extruded polygon | Caps use cross-section X/Y directly. Wall U measures the original contour length; V advances from 0 to 1 through the extrusion layers, including bevel layers. | + +Cuboid face directions also apply to rounded cuboids: + +| Face normal | Increasing U | Increasing V | +| --- | --- | --- | +| +Y | +X | +Z | +| -Y | +X | -Z | +| -X | +Z | -Y | +| +X | -Z | -Y | +| +Z | +X | -Y | +| -Z | -X | -Y | + +Tube and torus-knot cross-section seams follow the generated path frame rather than a fixed world axis. On extruded walls, U increases counterclockwise around outer contours and clockwise around holes, viewed from cross-section +Z. Each contour starts its own distance count at 0. + +Seam and pole vertices may use adjusted UVs to avoid interpolating across a wrap. Regular-polyhedron U values can exceed 1. Polygon coordinates, extrusion cap coordinates and wall distances can also lie outside 0–1; these mappings are not normalized to the shape bounds. + +### Mesh data and materials + +Mesh settings and subdivision counts belong to the optional settings object: + +```ts +const editable = PrimitiveMesh.createSphere(engine, 1, { keepMeshData: true, subdivisionLevel: 3 }); +const sixMaterials = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { + separateMaterialSlots: true, + widthSegments: 1, + heightSegments: 1, + depthSegments: 1 +}); +``` + +`keepMeshData` defaults to false. Set it to true to retain vertex attributes and indices for reading or editing after upload. + +Automatic device restoration uses the original creation parameters. Edits made after creation are not backed up, even when `keepMeshData` is true. + +`separateMaterialSlots` is available for cuboids, cylinders, truncated cones, cones, polygons, extrusions and rounded cuboids. It defaults to false, which creates one SubMesh. When enabled, the generated SubMeshes correspond to material slots in this order: + +| Geometry | Material slot order | +| --- | --- | +| Cuboid and rounded cuboid | +Y, -Y, -X, +X, +Z, -Z | +| Cylinder and truncated cone | Side, top cap, bottom cap | +| Cone | Side, bottom cap | +| Polygon | One slot per shape, in input order; holes share their outer contour's slot | +| Extruded polygon | Both end caps, then all walls and bevels, per shape; closed paths have one wall slot per shape | + +Only generated parts occupy slots. Disabled or zero-radius caps do not reserve a slot, so a cylinder with only its bottom cap uses slot 0 for the side and slot 1 for the bottom. When rebuilding a mesh with different parts or shapes, update the material array to match the resulting slot order. + +Assign materials through `renderer.setMaterials(materials)`. To use one material across all slots, pass `mesh.subMeshes.map(() => material)`. + +Input data is copied at creation. Later changes to the original data do not alter the mesh or its device-restoration result. Recreate a mesh to change its parameters. + +### Serializable primitive assets + +`PrimitiveMeshAsset` is exported from both `@galacean/engine` and `@galacean/engine-loader`. Use it to type the JSON saved by an editor: + +```ts +import type { PrimitiveMeshAsset } from "@galacean/engine"; + +const asset = { + type: "sphere", + sphereRadius: 1, + sphereOptions: { subdivisionLevel: 3, keepMeshData: true } +} satisfies PrimitiveMeshAsset; +``` + +Each `type` selects the matching `PrimitiveMesh.createX` method. Type-prefixed fields store the required shape inputs, and `Options` stores only that factory's optional settings. Angular ranges are stored as `{ x: startAngle, y: endAngle }`, and the loader constructs `Vector2` instances. For example, `circleOptions: { angleRange: { x: 30, y: 180 } }` creates a sector from 30 to 180 degrees. Omitted option fields use the creation API's defaults, including defaults derived from another option. Angles remain in degrees. + +TypeScript assets use `PrimitiveMeshCapMode` for cylinder and frustum `caps`; JSON stores its string values: `"both"`, `"top"`, `"bottom"` or `"none"`. + +| Asset type | Required geometry fields | +| --- | --- | +| `sphere`, `circle` | `Radius` | +| `cuboid` | `cuboidWidth`, `cuboidHeight`, `cuboidDepth` | +| `plane` | `planeWidth`, `planeDepth` | +| `cylinder`, `cone` | `Radius`, `Height` | +| `capsule` | `capsuleRadius`, `capsuleCylinderHeight` | +| `truncatedCone` | `truncatedConeTopRadius`, `truncatedConeBottomRadius`, `truncatedConeHeight` | +| `torus` | `torusRadius`, `torusTubeRadius` | +| `ring` | `ringOuterRadius`, `ringInnerRadius` | +| `tetrahedron`, `octahedron`, `icosahedron`, `dodecahedron` | `Radius` | +| `revolvedSurface` | `revolvedSurfaceProfile` | +| `tube` | `tubePath`, `tubeRadius` | +| `polygon` | `polygonShapes` | +| `extrudedPolygon` | `extrudedPolygonShapes`, plus `extrudedPolygonDepth` or `extrudedPolygonPath` | +| `torusKnot` | `torusKnotRadius`, `torusKnotTubeRadius`, `torusKnotAxisTurns`, `torusKnotCrossSectionTurns` | +| `roundedCuboid` | `roundedCuboidWidth`, `roundedCuboidHeight`, `roundedCuboidDepth`, `roundedCuboidCornerRadius` | + +`sphere` creates a subdivided cube projected onto a sphere; `sphereOptions.subdivisionLevel` controls its subdivision level. `cylinder` has one radius; `truncatedCone` has independent `truncatedConeTopRadius` and `truncatedConeBottomRadius`. + +Profiles and polygon contours store `{ x, y }` points; paths store `{ x, y, z }` points. The loader constructs the corresponding vectors. Polygon and extrusion assets use one array of shapes, each with `points` and optional `holes`: + +```json +{ + "type": "extrudedPolygon", + "extrudedPolygonShapes": [ + { + "points": [ + { "x": -2, "y": -2 }, + { "x": 2, "y": -2 }, + { "x": 2, "y": 2 }, + { "x": -2, "y": 2 } + ], + "holes": [ + [ + { "x": -1, "y": -1 }, + { "x": -1, "y": 1 }, + { "x": 1, "y": 1 }, + { "x": 1, "y": -1 } + ] + ] + } + ], + "extrudedPolygonDepth": 2, + "extrudedPolygonOptions": { "bevelWidth": 0.1, "contourOffset": 0.2, "separateMaterialSlots": true } +} +``` + +Path extrusion uses the required `extrudedPolygonPath` field instead of `extrudedPolygonDepth`. Its options follow `PathExtrudedPolygonMeshOptions`; bevel settings belong only to linear extrusion. Set `extrudedPolygonOptions.closedPath` to `true` for a closed path without end caps. Save path points as `{ x, y, z }`. + +When integrating an editor, use an Engine package version that exposes these APIs. Previews and saved assets should select the same creation method and parameters. diff --git a/docs/zh/graphics/background/sky.mdx b/docs/zh/graphics/background/sky.mdx index 5e178e0307..cc4bf4c72b 100644 --- a/docs/zh/graphics/background/sky.mdx +++ b/docs/zh/graphics/background/sky.mdx @@ -45,11 +45,11 @@ label: Graphics/Background ```typescript // 创建大气散射材质 const skyMaterial = new SkyProceduralMaterial(engine); -// 设置天空盒 +// 设置程序化天空背景 const background = scene.background; background.mode = BackgroundMode.Sky; background.sky.material = skyMaterial; -background.sky.mesh = PrimitiveMesh.createSphere(engine); +background.sky.mesh = PrimitiveMesh.createSphere(engine, 0.5); ``` ### 属性 diff --git a/docs/zh/graphics/mesh/primitiveMesh.mdx b/docs/zh/graphics/mesh/primitiveMesh.mdx index 3f5fb7c428..34b322c775 100644 --- a/docs/zh/graphics/mesh/primitiveMesh.mdx +++ b/docs/zh/graphics/mesh/primitiveMesh.mdx @@ -12,27 +12,39 @@ label: Graphics/Mesh 编辑器已经内置了`立方体`、`球`、`圆柱体` 等基础几何体,可以直接在左侧节点树点击 `+` 置入模型: -image-20231009111916680 +image-20231009111916680 当然,我们也可以在组件面板点击 `1` 添加 `Mesh Renderer`组件,点击 `2` 绑定想要的基础几何体: -image-20231009112014068 +image-20231009112014068 内置几何体无法满足需求?您可以在 **[资产面板](/docs/assets/interface)** 中 **右键** → **Create** → **PrimitiveMesh** 创建一个 `Mesh` 资产,并通过调整 `Mesh` 的各项参数来满足需求。 -image-20231009111916680 +image-20231009111916680 ## 脚本使用 -目前提供的几何体如下: +以下展示常见几何体的用法,完整创建方法见[程序化几何](#程序化几何)。 -- [createCuboid](/apis/core/#PrimitiveMesh-createCuboid) **立方体** +- [createCuboid](/apis/core/#PrimitiveMesh-createCuboid) **长方体** ```typescript const entity = rootEntity.createChild("cuboid"); entity.transform.setPosition(0, 1, 0); const renderer = entity.addComponent(MeshRenderer); -renderer.mesh = PrimitiveMesh.createCuboid(engine); +renderer.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); // Create material const material = new BlinnPhongMaterial(engine); material.emissiveColor.set(1, 1, 1, 1); @@ -45,7 +57,7 @@ renderer.setMaterial(material); const entity = rootEntity.createChild("sphere"); entity.transform.setPosition(0, 1, 0); const renderer = entity.addComponent(MeshRenderer); -renderer.mesh = PrimitiveMesh.createSphere(engine); +renderer.mesh = PrimitiveMesh.createSphere(engine, 0.5); // Create material const material = new BlinnPhongMaterial(engine); material.emissiveColor.set(1, 1, 1, 1); @@ -58,7 +70,7 @@ renderer.setMaterial(material); const entity = rootEntity.createChild("plane"); entity.transform.setPosition(0, 1, 0); const renderer = entity.addComponent(MeshRenderer); -renderer.mesh = PrimitiveMesh.createPlane(engine); +renderer.mesh = PrimitiveMesh.createPlane(engine, 1, 1); // Create material const material = new BlinnPhongMaterial(engine); material.emissiveColor.set(1, 1, 1, 1); @@ -71,20 +83,20 @@ renderer.setMaterial(material); const entity = rootEntity.createChild("cylinder"); entity.transform.setPosition(0, 1, 0); const renderer = entity.addComponent(MeshRenderer); -renderer.mesh = PrimitiveMesh.createCylinder(engine); +renderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); // Create material const material = new BlinnPhongMaterial(engine); material.emissiveColor.set(1, 1, 1, 1); renderer.setMaterial(material); ``` -- [createTorus](/apis/core/#PrimitiveMesh-createTorus) **圆环** +- [createTorus](/apis/core/#PrimitiveMesh-createTorus) **环面** ```typescript const entity = rootEntity.createChild("torus"); entity.transform.setPosition(0, 1, 0); const renderer = entity.addComponent(MeshRenderer); -renderer.mesh = PrimitiveMesh.createTorus(engine); +renderer.mesh = PrimitiveMesh.createTorus(engine, 0.5, 0.1); // Create material const material = new BlinnPhongMaterial(engine); material.emissiveColor.set(1, 1, 1, 1); @@ -97,7 +109,7 @@ renderer.setMaterial(material); const entity = rootEntity.createChild("cone"); entity.transform.setPosition(0, 1, 0); const renderer = entity.addComponent(MeshRenderer); -renderer.mesh = PrimitiveMesh.createCone(engine); +renderer.mesh = PrimitiveMesh.createCone(engine, 0.5, 2); // Create material const material = new BlinnPhongMaterial(engine); material.emissiveColor.set(1, 1, 1, 1); @@ -110,9 +122,246 @@ renderer.setMaterial(material); const entity = rootEntity.createChild("capsule"); entity.transform.setPosition(0, 1, 0); const renderer = entity.addComponent(MeshRenderer); -renderer.mesh = PrimitiveMesh.createCapsule(engine); +renderer.mesh = PrimitiveMesh.createCapsule(engine, 0.5, 2); // Create material const material = new BlinnPhongMaterial(engine); material.emissiveColor.set(1, 1, 1, 1); renderer.setMaterial(material); ``` + +## 程序化几何 + +每个工厂方法先接收必填的形状参数,再接收可选的具名配置对象。尺寸、半径、轮廓和路径必须明确指定;细分、角度范围和网格设置保留在 options 中,省略时使用注释说明的默认值。例如,`createSphere` 先接收半径,再接收 `SphereMeshOptions`: + +```ts +const smallSphere = PrimitiveMesh.createSphere(engine, 0.5); +const sphere = PrimitiveMesh.createSphere(engine, 1); +const smoothSphere = PrimitiveMesh.createSphere(engine, 1, { subdivisionLevel: 4 }); + +const cube = PrimitiveMesh.createCuboid(engine, 2, 2, 2); +const box = PrimitiveMesh.createCuboid(engine, 2, 3, 4); +const ground = PrimitiveMesh.createPlane(engine, 10, 10); + +const cylinder = PrimitiveMesh.createCylinder(engine, 0.5, 2); +const frustum = PrimitiveMesh.createTruncatedCone(engine, 0.25, 0.5, 2); +const mirroredKnot = PrimitiveMesh.createTorusKnot(engine, 1, 0.1, 2, -3); +``` + +`createCuboid` 的宽、高、深是三个独立的必填参数;`createPlane` 的宽、深也必须分别指定。平面和长方体的后续分段数默认沿用第一个方向的分段数。球体使用一个细分层级,默认为 3,限制在 1 到 6 之间。`createCylinder` 只有一个半径;上下半径不同的圆台使用 `createTruncatedCone`。`createRing` 先接收外半径,再接收内半径,两者都必须指定。 + +尺寸必须显式传入;分段和网格设置使用具名字段,可以只指定需要调整的可选项。 + +环面结的 `axisTurns` 表示绕中心轴的圈数,`crossSectionTurns` 表示绕环面截面的圈数。两者都是有符号整数,与网格分段数无关。负值反转对应方向的缠绕,`0` 表示该方向的角度保持不变,两者至少有一个非零。 + +| 能力 | 创建方法 | +| --- | --- | +| 平面、长方体、球 | `createPlane`、`createCuboid`、`createSphere` | +| 圆柱、圆台、圆锥、胶囊 | `createCylinder`、`createTruncatedCone`、`createCone`、`createCapsule` | +| 圆盘、平面圆环、环面、环面结 | `createCircle`、`createRing`、`createTorus`、`createTorusKnot` | +| 四面体、八面体、二十面体、十二面体 | `createTetrahedron`、`createOctahedron`、`createIcosahedron`、`createDodecahedron` | +| 旋转曲面、路径管道、平面多边形、挤出多边形、圆角长方体 | `createRevolvedSurface`、`createTube`、`createPolygon`、`createExtrudedPolygon`、`createRoundedCuboid` | + +### 分段、角度和端盖 + +管道和环面结用 `pathSegments` 控制沿路径的分段,环面用 `ringSegments` 控制环向分段,`radialSegments` 控制管截面的周向分段。胶囊的 `capSegments` 控制每个半球从极点到赤道的分段,`cylinderHeight` 表示直筒部分的高度。正多面体用 `edgeSegments`,圆角长方体用 `roundingSegments`。 + +角度范围统一放在配置对象中。所有角度均使用**度数**,范围使用 `Vector2`,`x` 表示起始角,`y` 表示结束角。跨越 360 度时使用连续角度,例如 `new Vector2(350, 370)`。圆柱、圆台和圆锥围绕 Y 轴,从 -Z 朝 -X 方向开始;旋转曲面从 +Z 朝 +X 方向开始。球体的垂直角度从 +Y 极点开始。 + +```ts +import { PrimitiveMeshCapMode, Vector2 } from "@galacean/engine"; + +const hemisphere = PrimitiveMesh.createSphere(engine, 1, { verticalAngleRange: new Vector2(0, 90) }); +const openCylinder = PrimitiveMesh.createCylinder(engine, 0.5, 2, { caps: PrimitiveMeshCapMode.None }); +const cupWall = PrimitiveMesh.createCylinder(engine, 0.5, 2, { caps: PrimitiveMeshCapMode.Bottom }); +const halfRing = PrimitiveMesh.createRing(engine, 1, 0.5, { angleRange: new Vector2(0, 180) }); +``` + +圆柱和圆台的 `caps` 使用 `PrimitiveMeshCapMode`:`Both`(默认)、`Top`、`Bottom`、`None`。顶盖朝 +Y,底盖朝 -Y,角度裁切产生的侧面切口保持开放。圆锥用布尔值 `cap` 控制底盖。`createCircle`、`createRing` 和多边形位于 XY 平面、正面朝 +Z;地面用的 `createPlane` 位于 XZ 平面、正面朝 +Y。 + +`createSphere` 将细分后的立方体投影到球面,支持 `horizontalAngleRange` 和 `verticalAngleRange`。水平角度从 -X 朝 +Z 开始,垂直角度从 +Y 极点开始。裁切保留细分表面,切口不生成端盖;水平范围 `new Vector2(350, 370)` 可跨越接缝。细分层级控制表面及裁切边界的精细程度。 + +### 轮廓与路径 + +多边形轮廓使用 `Vector2` 数组。一个简单多边形直接传入点数组;有孔洞时使用 `{ points, holes }`,多个多边形使用这种对象的数组。多边形轮廓会自动闭合,不必重复首点。 + +`createPolygon` 创建位于 XY 平面、正面朝 +Z 的零厚度表面,不生成侧壁。`createExtrudedPolygon` 为轮廓增加厚度或沿路径挤出,生成侧壁和相应的端盖。 + +`createRevolvedSurface` 将 `Vector2` 轮廓绕 Y 轴旋转:`x` 表示到 Y 轴的半径,`y` 表示高度,两者均使用局部单位。相邻轮廓点按输入顺序连接,闭合轮廓需要重复首点。它不会自动添加端盖或壁厚;轮廓可以同时描述内外壁,也可以将端点延伸到旋转轴,在完整旋转一圈后形成封闭端部。管道和挤出的路径点使用局部坐标下的 `Vector3` 数组。 + +```ts +import { Vector2, Vector3 } from "@galacean/engine"; + +const profile = [new Vector2(0, 0), new Vector2(0.8, 0), new Vector2(0.4, 1), new Vector2(0.5, 1.5)]; +const revolvedSurface = PrimitiveMesh.createRevolvedSurface(engine, profile, { segments: 32 }); + +const outline = [new Vector2(-2, -2), new Vector2(2, -2), new Vector2(2, 2), new Vector2(-2, 2)]; +const hole = [new Vector2(-1, -1), new Vector2(-1, 1), new Vector2(1, 1), new Vector2(1, -1)]; +const face = PrimitiveMesh.createPolygon(engine, { points: outline, holes: [hole] }); + +const solid = PrimitiveMesh.createExtrudedPolygon(engine, { points: outline, holes: [hole] }, 0.5); +const beveled = PrimitiveMesh.createExtrudedPolygon(engine, outline, 0.5, { + bevelWidth: 0.05, + contourOffset: 0.02, + depthSegments: 1 +}); + +const path = Array.from({ length: 65 }, (_, i) => { + const t = i / 64; + return new Vector3(4 * t, Math.sin(t * Math.PI * 2), 0); +}); +const tube = PrimitiveMesh.createTube(engine, path, 0.1, { pathSegments: 64 }); +const swept = PrimitiveMesh.createExtrudedPolygon(engine, outline, path, { pathSegments: 64 }); +const loop = [new Vector3(-4, 0, -4), new Vector3(4, 0, -4), new Vector3(4, 0, 4), new Vector3(-4, 0, 4)]; +const closedPath = PrimitiveMesh.createExtrudedPolygon(engine, outline, loop, { closedPath: true, pathSegments: 32 }); +``` + +`createExtrudedPolygon` 提供两个重载: + +- `depth: number` 沿 +Z 直线挤出,生成侧壁和两端封盖。`LinearExtrudedPolygonMeshOptions` 控制 `depthSegments`、倒角和材质分组。 +- `path: readonly Vector3[]` 沿空间路径挤出。`PathExtrudedPolygonMeshOptions` 控制 `pathSegments`、`closedPath` 和材质分组。开放路径生成两端封盖;闭合路径连接首尾截面,不生成封盖。 + +直线挤出默认不倒角;`bevelWidth > 0` 时开启倒角,`bevelDepth` 默认等于 `bevelWidth`。路径挤出不提供倒角设置。路径按折线长度均匀采样;使用曲线时,在外层采样成点数组后传入,如上例所示。 + +管道和路径挤出的 `closedPath` 默认关闭;开启后自动连接路径首尾并对齐截面,不必重复首点。闭合挤出至少使用三段,不生成端盖。开放挤出保留两端端盖;管道在两种模式下都不生成端盖。 + +`contourOffset` 默认是 `0`,用于偏移侧壁轮廓:正值外扩实体并缩小孔洞,负值内缩实体并扩大孔洞。`bevelWidth` 为 `0` 时偏移仍然生效。倒角从偏移后的轮廓向内削边,厚度包含在 `depth` 内,不会增加总厚度。 + +### UV 映射 + +以下方向按局部坐标和 UV0 数值递增方向定义,以正的尺寸和半径、默认角度范围为准。 + +| 几何体 | UV 映射 | +| --- | --- | +| 平面 | U 沿 +X、V 沿 +Z 增加,两者均为 0~1。 | +| 长方体、圆角长方体 | 每个面独立使用 0~1 的方形区域,具体方向见下表;圆角长方体按圆角边长调整映射。 | +| 球体 | U 沿指定的水平角度区间,默认从 -X 朝 +Z 开始;V 从指定垂直区间的上边界到下边界。两个区间分别映射为 0~1。 | +| 圆柱、圆台、圆锥侧面 | U 沿指定角度范围从 0 到 1,默认从 -Z 朝 -X 开始;V 顶部为 0、底部为 1。 | +| 圆柱、圆台、圆锥端盖 | 两端均为 U 沿 +X、V 沿 -Z 增加;中心为 (0.5, 0.5),各端盖的直径映射为 0~1。 | +| 胶囊 | U 绕 Y 轴从 -Z 朝 -X 增加;V 顶部为 0、底部为 1,按半球和直筒的连续表面长度分配。 | +| 环面 | U 沿 `ringAngleRange`、V 沿 `tubeAngleRange`,分别从 0 到 1。 | +| 圆盘、平面圆环 | U 沿 +X、V 沿 +Y 增加;完整外圆的包围方形映射为 0~1,角度裁切保留这些坐标。 | +| 四种正多面体 | U 绕 Y 轴从 +X 朝 -Z 增加,接缝位于 +X;V 在 +Y 为 0、-Y 为 1。 | +| 旋转曲面 | U 沿旋转方向从 0 到 1;V 按轮廓点的输入顺序等步长从 0 到 1。 | +| 管道 | U 为归一化的路径距离;V 沿生成截面的周向从 0 到 1。 | +| 环面结 | U 沿环面结的曲线参数从 0 到 1;V 沿生成截面的周向从 0 到 1。 | +| 平面多边形 | U = 局部 X、V = 局部 Y,不做归一化。 | +| 挤出多边形 | 端盖直接使用截面 X/Y;侧壁 U 为原始轮廓的累计长度,V 按挤出层从 0 到 1,包含倒角层。 | + +长方体各面的递增方向如下,圆角长方体沿用相同方向: + +| 面法线 | U 递增方向 | V 递增方向 | +| --- | --- | --- | +| +Y | +X | +Z | +| -Y | +X | -Z | +| -X | +Z | -Y | +| +X | -Z | -Y | +| +Z | +X | -Y | +| -Z | -X | -Y | + +管道和环面结的截面接缝跟随生成的路径坐标架,不固定在某个世界轴上。从截面 +Z 方向看,挤出侧壁的 U 沿外轮廓逆时针增加、沿孔洞顺时针增加,每条轮廓分别从 0 累计。 + +接缝和极点的顶点可能调整 UV,以避免跨接缝插值。正多面体的 U 可能大于 1。多边形坐标、挤出端盖坐标和侧壁累计长度也可能超出 0~1,这些映射不会按形状包围盒归一化。 + +### 网格数据和材质 + +网格设置与分段设置放在同一个可选配置对象中: + +```ts +const editable = PrimitiveMesh.createSphere(engine, 1, { keepMeshData: true, subdivisionLevel: 3 }); +const sixMaterials = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { + separateMaterialSlots: true, + widthSegments: 1, + heightSegments: 1, + depthSegments: 1 +}); +``` + +`keepMeshData` 默认关闭,设为 `true` 时保留顶点属性和索引,供上传后读取或修改。 + +设备自动恢复使用初始创建参数。即使 `keepMeshData` 为 `true`,也不会额外备份创建后的网格修改。 + +`separateMaterialSlots` 适用于长方体、圆柱、圆台、圆锥、多边形、挤出和圆角长方体。默认关闭,生成一个 SubMesh;开启后,生成的 SubMesh 按以下顺序对应材质槽: + +| 几何体 | 材质槽顺序 | +| ------------------ | ---------------------------------------------------------------------------- | +| 长方体、圆角长方体 | +Y、-Y、-X、+X、+Z、-Z | +| 圆柱、圆台 | 侧面、顶盖、底盖 | +| 圆锥 | 侧面、底盖 | +| 多边形 | 按输入顺序,每个形状一个槽;孔洞与外轮廓共用该槽 | +| 挤出 | 按输入形状顺序,端盖一个槽、侧壁和倒角一个槽;闭合路径每个形状只有一个侧壁槽 | + +只有实际生成的部位占用槽位。关闭或半径为零的端盖不保留空槽,因此只有底盖的圆柱使用槽 0 绘制侧面、槽 1 绘制底盖。改变部位或形状后重建网格时,需要按新的槽位顺序更新材质数组。 + +通过 `renderer.setMaterials(materials)` 分配材质。如果所有槽使用同一个材质,可以传入 `mesh.subMeshes.map(() => material)`。 + +创建时会复制输入数据,修改原始点数组不会改变已创建的网格或其设备恢复结果。修改参数时重新创建网格即可。 + +### 可序列化的基础网格资产 + +`PrimitiveMeshAsset` 从 `@galacean/engine` 和 `@galacean/engine-loader` 导出,Editor 可以直接用它约束保存的 JSON: + +```ts +import type { PrimitiveMeshAsset } from "@galacean/engine"; + +const asset = { + type: "sphere", + sphereRadius: 1, + sphereOptions: { subdivisionLevel: 3, keepMeshData: true } +} satisfies PrimitiveMeshAsset; +``` + +每个 `type` 对应同名的 `PrimitiveMesh.createX` 方法。带类型前缀的字段保存必填形状参数,`Options` 仅保存该工厂的可选设置。角度范围保存为 `{ x: 起始角, y: 结束角 }`,由 Loader 构造 `Vector2`。例如 `circleOptions: { angleRange: { x: 30, y: 180 } }` 创建从 30 度到 180 度的扇形。省略可选设置时采用创建 API 的默认值,包括由其他可选设置决定的默认值;角度仍使用度数。 + +TypeScript 资产使用 `PrimitiveMeshCapMode` 表达圆柱和圆台的 `caps`;JSON 中保存对应的字符串值:`"both"`、`"top"`、`"bottom"` 或 `"none"`。 + +| 资产类型 | 必填几何字段 | +| --- | --- | +| `sphere`、`circle` | `Radius` | +| `cuboid` | `cuboidWidth`、`cuboidHeight`、`cuboidDepth` | +| `plane` | `planeWidth`、`planeDepth` | +| `cylinder`、`cone` | `Radius`、`Height` | +| `capsule` | `capsuleRadius`、`capsuleCylinderHeight` | +| `truncatedCone` | `truncatedConeTopRadius`、`truncatedConeBottomRadius`、`truncatedConeHeight` | +| `torus` | `torusRadius`、`torusTubeRadius` | +| `ring` | `ringOuterRadius`、`ringInnerRadius` | +| `tetrahedron`、`octahedron`、`icosahedron`、`dodecahedron` | `Radius` | +| `revolvedSurface` | `revolvedSurfaceProfile` | +| `tube` | `tubePath`、`tubeRadius` | +| `polygon` | `polygonShapes` | +| `extrudedPolygon` | `extrudedPolygonShapes`,以及 `extrudedPolygonDepth` 或 `extrudedPolygonPath` | +| `torusKnot` | `torusKnotRadius`、`torusKnotTubeRadius`、`torusKnotAxisTurns`、`torusKnotCrossSectionTurns` | +| `roundedCuboid` | `roundedCuboidWidth`、`roundedCuboidHeight`、`roundedCuboidDepth`、`roundedCuboidCornerRadius` | + +`sphere` 创建立方体细分后投影得到的球体,`sphereOptions.subdivisionLevel` 控制细分层级。`cylinder` 使用一个半径;`truncatedCone` 分别使用 `truncatedConeTopRadius` 和 `truncatedConeBottomRadius`。 + +轮廓和旋转截面保存为 `{ x, y }` 点数组,路径保存为 `{ x, y, z }` 点数组,由 Loader 构造对应向量。多边形与拉伸统一使用形状数组,每个形状包含 `points` 和可选的 `holes`: + +```json +{ + "type": "extrudedPolygon", + "extrudedPolygonShapes": [ + { + "points": [ + { "x": -2, "y": -2 }, + { "x": 2, "y": -2 }, + { "x": 2, "y": 2 }, + { "x": -2, "y": 2 } + ], + "holes": [ + [ + { "x": -1, "y": -1 }, + { "x": -1, "y": 1 }, + { "x": 1, "y": 1 }, + { "x": 1, "y": -1 } + ] + ] + } + ], + "extrudedPolygonDepth": 2, + "extrudedPolygonOptions": { "bevelWidth": 0.1, "contourOffset": 0.2, "separateMaterialSlots": true } +} +``` + +沿路径挤出通过必填的 `extrudedPolygonPath` 代替 `extrudedPolygonDepth`。可选设置遵循 `PathExtrudedPolygonMeshOptions`,倒角设置仅属于直线挤出。`extrudedPolygonOptions.closedPath` 设为 `true` 时闭合路径且不生成端盖。路径点保存为 `{ x, y, z }`。 + +编辑器对接时,需要使用包含这些 API 的 Engine 包版本。预览应使用与保存资产相同的创建方法和参数。 diff --git a/e2e/case/.primitiveMeshGallery.ts b/e2e/case/.primitiveMeshGallery.ts new file mode 100644 index 0000000000..d5bcc063ed --- /dev/null +++ b/e2e/case/.primitiveMeshGallery.ts @@ -0,0 +1,188 @@ +import { + BlinnPhongMaterial, + Camera, + DirectLight, + Entity, + Font, + MeshRenderer, + MeshTopology, + ModelMesh, + TextRenderer, + Texture2D, + TextureFilterMode, + TextureFormat, + UnlitMaterial, + Vector3, + WebGLEngine +} from "@galacean/engine"; +import { initScreenshot, updateForE2E } from "./.mockForE2E"; + +export interface PrimitiveMeshExample { + label: string; + detail: string; + mesh: ModelMesh; + rotation?: Vector3; + wireframe?: boolean; + appearance?: "checker" | "solid" | "groups"; +} + +/** + * Shared presentation for the primitive mesh visual regression cases. + */ +export class PrimitiveMeshGallery { + private readonly _root: Entity; + private readonly _camera: Camera; + private readonly _font: Font; + + constructor(readonly engine: WebGLEngine) { + const scene = engine.sceneManager.activeScene!; + scene.background.solidColor.set(0.035, 0.045, 0.065, 1); + scene.ambientLight.diffuseSolidColor.set(0.3, 0.3, 0.3, 1); + this._root = scene.createRootEntity("Primitive features"); + const cameraEntity = this._root.createChild("Camera"); + cameraEntity.transform.setPosition(0, 0, 30); + this._camera = cameraEntity.addComponent(Camera); + this._camera.isOrthographic = true; + this._camera.farClipPlane = 100; + const light = this._root.createChild("Light"); + light.transform.setRotation(35, -35, 0); + light.addComponent(DirectLight).color.set(0.8, 0.8, 0.8, 1); + this._font = Font.createFromOS(engine, "AlibabaSans")!; + } + + static async create(): Promise { + await document.fonts.load('26px "AlibabaSans"'); + const engine = await WebGLEngine.create({ canvas: "canvas" }); + engine.canvas.setAutoResolution(2); + return new PrimitiveMeshGallery(engine); + } + + show(title: string, examples: PrimitiveMeshExample[], columns: number): void { + const rows = Math.ceil(examples.length / columns); + this._camera.orthographicSize = Math.max((rows * 3.3) / 2 + 1, (columns * 3.5) / 3 + 0.1); + const checker = new BlinnPhongMaterial(this.engine); + checker.baseTexture = this._createChecker(); + checker.specularColor.set(0.15, 0.15, 0.15, 1); + const solid = new BlinnPhongMaterial(this.engine); + solid.baseColor.set(0.45, 0.69, 0.85, 1); + solid.specularColor.set(0.15, 0.15, 0.15, 1); + const wire = new UnlitMaterial(this.engine); + wire.baseColor.set(0.025, 0.07, 0.1, 1); + wire.isTransparent = true; + const groupColors = [ + [0.3, 0.65, 0.95], + [1, 0.65, 0.25], + [0.55, 0.85, 0.45], + [0.95, 0.4, 0.5], + [0.75, 0.5, 0.95], + [0.3, 0.85, 0.8] + ]; + const groups = groupColors.map(([r, g, b]) => { + const material = solid.clone(); + material.baseColor.set(r, g, b, 1); + return material; + }); + + this._createLabel(title, 0, ((rows - 1) / 2) * 3.3 + 1.85, 34); + examples.forEach(({ label, detail, mesh, rotation, wireframe, appearance = "checker" }, index) => { + const { min, max } = mesh.bounds; + if (mesh.vertexCount === 0 || ![min.x, min.y, min.z, max.x, max.y, max.z].every(Number.isFinite)) { + throw new Error(`Invalid primitive in gallery: ${label}`); + } + const row = Math.floor(index / columns); + const rowColumns = Math.min(columns, examples.length - row * columns); + const x = ((index % columns) - (rowColumns - 1) / 2) * 3.5; + const y = ((rows - 1) / 2 - row) * 3.3; + const pivot = this._root.createChild(label); + pivot.transform.setPosition(x, y + 0.25, 0); + pivot.transform.rotation = rotation ?? new Vector3(22, -28, 0); + const scale = 1.7 / Math.max(max.x - min.x, max.y - min.y, max.z - min.z); + pivot.transform.setScale(scale, scale, scale); + const entity = pivot.createChild("Surface"); + entity.transform.setPosition(-(min.x + max.x) / 2, -(min.y + max.y) / 2, -(min.z + max.z) / 2); + const renderer = entity.addComponent(MeshRenderer); + renderer.mesh = mesh; + renderer.setMaterials( + mesh.subMeshes.map((_, slot) => + wireframe + ? solid + : appearance === "groups" + ? groups[slot % groups.length] + : appearance === "solid" + ? solid + : checker + ) + ); + if (wireframe) { + const lines = entity.createChild("Triangle edges").addComponent(MeshRenderer); + lines.mesh = this._createWireframe(mesh); + lines.setMaterial(wire); + } + this._createLabel(label, x, y - 1.1, 26); + this._createLabel(detail, x, y - 1.45, 19); + }); + updateForE2E(this.engine); + initScreenshot(this.engine, this._camera, 1800, Math.max(1200, rows * 300)); + } + + private _createWireframe(mesh: ModelMesh): ModelMesh { + const indices = mesh.getIndices()!; + const lines: number[] = []; + const edges = new Set(); + for (let i = 0; i < indices.length; i += 3) { + for (let edge = 0; edge < 3; edge++) { + const a = indices[i + edge]; + const b = indices[i + ((edge + 1) % 3)]; + const key = `${Math.min(a, b)}:${Math.max(a, b)}`; + if (!edges.has(key)) { + edges.add(key); + lines.push(a, b); + } + } + } + const wireframe = new ModelMesh(this.engine); + const normals = mesh.getNormals()!; + const { min, max } = mesh.bounds; + const offset = Math.max(max.x - min.x, max.y - min.y, max.z - min.z) * 0.001; + wireframe.setPositions( + mesh.getPositions()!.map((point, index) => { + const normal = normals[index]; + return new Vector3(point.x + normal.x * offset, point.y + normal.y * offset, point.z + normal.z * offset); + }) + ); + wireframe.setIndices(new Uint32Array(lines)); + wireframe.addSubMesh(0, lines.length, MeshTopology.Lines); + wireframe.bounds.min.copyFrom(mesh.bounds.min); + wireframe.bounds.max.copyFrom(mesh.bounds.max); + wireframe.uploadData(true); + return wireframe; + } + + private _createChecker(): Texture2D { + const size = 64; + const pixels = new Uint8Array(size * size * 4); + for (let y = 0; y < size; y++) { + for (let x = 0; x < size; x++) { + const dark = ((x >> 3) + (y >> 3)) % 2 === 0; + const color = x < 2 ? [240, 82, 85] : y < 2 ? [246, 187, 62] : dark ? [40, 110, 165] : [225, 238, 248]; + const offset = (y * size + x) * 4; + pixels.set([...color, 255], offset); + } + } + const texture = new Texture2D(this.engine, size, size, TextureFormat.R8G8B8A8, true); + texture.setPixelBuffer(pixels); + texture.generateMipmaps(); + texture.filterMode = TextureFilterMode.Trilinear; + return texture; + } + + private _createLabel(text: string, x: number, y: number, fontSize: number): void { + const entity = this._root.createChild(text); + entity.transform.setPosition(x, y, 0); + const renderer = entity.addComponent(TextRenderer); + renderer.font = this._font; + renderer.fontSize = fontSize; + renderer.text = text; + renderer.color.set(0.86, 0.91, 0.98, 1); + } +} diff --git a/e2e/case/camera-ssao.ts b/e2e/case/camera-ssao.ts index d38998ef58..8fbdfeb6f8 100644 --- a/e2e/case/camera-ssao.ts +++ b/e2e/case/camera-ssao.ts @@ -61,7 +61,7 @@ WebGLEngine.create({ sphere.transform.setPosition(0, 1, 0); sphere.transform.setRotation(45, 45, 0); const meshRenderer = sphere.addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createSubdivisionSurfaceSphere(engine); + meshRenderer.mesh = PrimitiveMesh.createSphere(engine, 0.5); meshRenderer.setMaterial(sphereMaterial); // Box @@ -71,7 +71,7 @@ WebGLEngine.create({ box.transform.setPosition(1, 0.9, 0.1); box.transform.setRotation(30, 30, 0); const boxMeshRenderer = box.addComponent(MeshRenderer); - boxMeshRenderer.mesh = PrimitiveMesh.createCuboid(engine); + boxMeshRenderer.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); boxMeshRenderer.setMaterial(boxMaterial); // Capsule (transparent) @@ -83,7 +83,7 @@ WebGLEngine.create({ capsule.transform.setPosition(1, 0.9, 0.1); capsule.transform.setRotation(30, 30, 0); const capsuleMeshRenderer = capsule.addComponent(MeshRenderer); - capsuleMeshRenderer.mesh = PrimitiveMesh.createCapsule(engine); + capsuleMeshRenderer.mesh = PrimitiveMesh.createCapsule(engine, 0.5, 2); capsuleMeshRenderer.setMaterial(capsuleMaterial); engine.resourceManager diff --git a/e2e/case/canvas-transparency.ts b/e2e/case/canvas-transparency.ts index f140cb0334..b9b22c71c9 100644 --- a/e2e/case/canvas-transparency.ts +++ b/e2e/case/canvas-transparency.ts @@ -111,7 +111,7 @@ function createMainScene(engine: Engine, transparencyTexture: Texture2D): Textur planeEntity.transform.setPosition(0, 0, 0); planeEntity.transform.rotate(new Vector3(90, 0, 0)); const planeRenderer = planeEntity.addComponent(MeshRenderer); - planeRenderer.mesh = PrimitiveMesh.createPlane(engine, 1); + planeRenderer.mesh = PrimitiveMesh.createPlane(engine, 1, 1); const planeMaterial = new UnlitMaterial(engine); planeMaterial.baseTexture = transparencyTexture; @@ -124,7 +124,7 @@ function createMainScene(engine: Engine, transparencyTexture: Texture2D): Textur cubeEntity.transform.setPosition(-1, 0, 0); cubeEntity.transform.rotate(new Vector3(0, 0, 15)); const sphereRenderer = cubeEntity.addComponent(MeshRenderer); - sphereRenderer.mesh = PrimitiveMesh.createCuboid(engine, 1); + sphereRenderer.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); const sphereMaterial = new UnlitMaterial(engine); sphereRenderer.setMaterial(sphereMaterial); diff --git a/e2e/case/material-white-furnace.ts b/e2e/case/material-white-furnace.ts index 00baa80276..286e8b587a 100644 --- a/e2e/case/material-white-furnace.ts +++ b/e2e/case/material-white-furnace.ts @@ -95,7 +95,7 @@ WebGLEngine.create({ canvas: "canvas" }).then((engine) => { entity.transform.setPosition(col * spacing - offsetX, (rows - 1 - row) * spacing - offsetY, 0); const renderer = entity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createSphere(engine, 0.5, 32); + renderer.mesh = PrimitiveMesh.createSphere(engine, 0.5, { subdivisionLevel: 4 }); const material = new PBRMaterial(engine); material.baseColor = rowConfigs[row].baseColor; diff --git a/e2e/case/multi-camera-no-clear.ts b/e2e/case/multi-camera-no-clear.ts index 6215088fc2..2bec9eefd4 100644 --- a/e2e/case/multi-camera-no-clear.ts +++ b/e2e/case/multi-camera-no-clear.ts @@ -54,7 +54,7 @@ function initFirstScene(engine: Engine): Scene { const cubeEntity = rootEntity.createChild("cube"); cubeEntity.transform.setPosition(-3, 0, 3); const renderer = cubeEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createSphere(engine, 2, 24); + renderer.mesh = PrimitiveMesh.createSphere(engine, 2, { subdivisionLevel: 3 }); const material = new BlinnPhongMaterial(engine); material.baseColor = new Color(1, 0, 0, 1); renderer.setMaterial(material); @@ -83,7 +83,7 @@ function initFirstScene(engine: Engine): Scene { cubeEntity.layer = Layer.Layer1; cubeEntity.transform.setPosition(-2, 0, 3); const renderer = cubeEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createSphere(engine, 2, 24); + renderer.mesh = PrimitiveMesh.createSphere(engine, 2, { subdivisionLevel: 3 }); const material = new BlinnPhongMaterial(engine); material.baseColor = new Color(1, 0, 0, 1); material.emissiveColor.set(1, 0, 0, 1); diff --git a/e2e/case/particleRenderer-emit-billboard-stretched.ts b/e2e/case/particleRenderer-emit-billboard-stretched.ts index 5aead90270..9e2dce0234 100644 --- a/e2e/case/particleRenderer-emit-billboard-stretched.ts +++ b/e2e/case/particleRenderer-emit-billboard-stretched.ts @@ -67,7 +67,7 @@ WebGLEngine.create({ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture2D, glTFModel: GLTFResource): Entity { const meshRenderer = rootEntity.createChild("Mesh").addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCylinder(engine); + meshRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const unlitMaterial = new UnlitMaterial(engine); unlitMaterial.baseTexture = glTFModel.textures[0]; meshRenderer.setMaterial(unlitMaterial); diff --git a/e2e/case/particleRenderer-emit-mesh-cone-scale-3d-rotation-life-seperate.ts b/e2e/case/particleRenderer-emit-mesh-cone-scale-3d-rotation-life-seperate.ts index c468303d06..a75db250f8 100644 --- a/e2e/case/particleRenderer-emit-mesh-cone-scale-3d-rotation-life-seperate.ts +++ b/e2e/case/particleRenderer-emit-mesh-cone-scale-3d-rotation-life-seperate.ts @@ -67,7 +67,7 @@ WebGLEngine.create({ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture2D, glTFModel: GLTFResource): Entity { const meshRenderer = rootEntity.createChild("Mesh").addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCylinder(engine); + meshRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const unlitMaterial = new UnlitMaterial(engine); unlitMaterial.baseTexture = glTFModel.textures[0]; meshRenderer.setMaterial(unlitMaterial); @@ -87,7 +87,7 @@ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture particleRenderer.renderMode = ParticleRenderMode.Mesh; // particleRenderer.mesh = glTFModel.meshes[0][0]; - particleRenderer.mesh = PrimitiveMesh.createCylinder(engine); + particleRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const generator = particleRenderer.generator; generator.useAutoRandomSeed = false; diff --git a/e2e/case/particleRenderer-emit-mesh-cone-scale-3d-rotation.ts b/e2e/case/particleRenderer-emit-mesh-cone-scale-3d-rotation.ts index b6b93f8858..f0ed4bb821 100644 --- a/e2e/case/particleRenderer-emit-mesh-cone-scale-3d-rotation.ts +++ b/e2e/case/particleRenderer-emit-mesh-cone-scale-3d-rotation.ts @@ -67,7 +67,7 @@ WebGLEngine.create({ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture2D, glTFModel: GLTFResource): Entity { const meshRenderer = rootEntity.createChild("Mesh").addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCylinder(engine); + meshRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const unlitMaterial = new UnlitMaterial(engine); unlitMaterial.baseTexture = glTFModel.textures[0]; meshRenderer.setMaterial(unlitMaterial); @@ -87,7 +87,7 @@ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture particleRenderer.renderMode = ParticleRenderMode.Mesh; // particleRenderer.mesh = glTFModel.meshes[0][0]; - particleRenderer.mesh = PrimitiveMesh.createCylinder(engine); + particleRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const generator = particleRenderer.generator; generator.useAutoRandomSeed = false; diff --git a/e2e/case/particleRenderer-emit-mesh-cone-scale-rotation-life-seperate.ts b/e2e/case/particleRenderer-emit-mesh-cone-scale-rotation-life-seperate.ts index 947c5e9323..01a11ad11a 100644 --- a/e2e/case/particleRenderer-emit-mesh-cone-scale-rotation-life-seperate.ts +++ b/e2e/case/particleRenderer-emit-mesh-cone-scale-rotation-life-seperate.ts @@ -67,7 +67,7 @@ WebGLEngine.create({ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture2D, glTFModel: GLTFResource): Entity { const meshRenderer = rootEntity.createChild("Mesh").addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCylinder(engine); + meshRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const unlitMaterial = new UnlitMaterial(engine); unlitMaterial.baseTexture = glTFModel.textures[0]; meshRenderer.setMaterial(unlitMaterial); @@ -87,7 +87,7 @@ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture particleRenderer.renderMode = ParticleRenderMode.Mesh; // particleRenderer.mesh = glTFModel.meshes[0][0]; - particleRenderer.mesh = PrimitiveMesh.createCylinder(engine); + particleRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const generator = particleRenderer.generator; generator.useAutoRandomSeed = false; diff --git a/e2e/case/particleRenderer-emit-mesh-cone-scale-rotation-life.ts b/e2e/case/particleRenderer-emit-mesh-cone-scale-rotation-life.ts index 1f166514be..9d78c938d8 100644 --- a/e2e/case/particleRenderer-emit-mesh-cone-scale-rotation-life.ts +++ b/e2e/case/particleRenderer-emit-mesh-cone-scale-rotation-life.ts @@ -67,7 +67,7 @@ WebGLEngine.create({ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture2D, glTFModel: GLTFResource): Entity { const meshRenderer = rootEntity.createChild("Mesh").addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCylinder(engine); + meshRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const unlitMaterial = new UnlitMaterial(engine); unlitMaterial.baseTexture = glTFModel.textures[0]; meshRenderer.setMaterial(unlitMaterial); @@ -87,7 +87,7 @@ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture particleRenderer.renderMode = ParticleRenderMode.Mesh; // particleRenderer.mesh = glTFModel.meshes[0][0]; - particleRenderer.mesh = PrimitiveMesh.createCylinder(engine); + particleRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const generator = particleRenderer.generator; generator.useAutoRandomSeed = false; diff --git a/e2e/case/particleRenderer-emit-mesh-cone-scale-rotation-world.ts b/e2e/case/particleRenderer-emit-mesh-cone-scale-rotation-world.ts index dcda6ea142..da203bc015 100644 --- a/e2e/case/particleRenderer-emit-mesh-cone-scale-rotation-world.ts +++ b/e2e/case/particleRenderer-emit-mesh-cone-scale-rotation-world.ts @@ -67,7 +67,7 @@ WebGLEngine.create({ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture2D, glTFModel: GLTFResource): Entity { const meshRenderer = rootEntity.createChild("Mesh").addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCylinder(engine); + meshRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const unlitMaterial = new UnlitMaterial(engine); unlitMaterial.baseTexture = glTFModel.textures[0]; meshRenderer.setMaterial(unlitMaterial); @@ -87,7 +87,7 @@ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture particleRenderer.renderMode = ParticleRenderMode.Mesh; // particleRenderer.mesh = glTFModel.meshes[0][0]; - particleRenderer.mesh = PrimitiveMesh.createCylinder(engine); + particleRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const generator = particleRenderer.generator; generator.useAutoRandomSeed = false; diff --git a/e2e/case/particleRenderer-emit-mesh-cone-scale-rotation.ts b/e2e/case/particleRenderer-emit-mesh-cone-scale-rotation.ts index 912dd62913..7f202cfedb 100644 --- a/e2e/case/particleRenderer-emit-mesh-cone-scale-rotation.ts +++ b/e2e/case/particleRenderer-emit-mesh-cone-scale-rotation.ts @@ -67,7 +67,7 @@ WebGLEngine.create({ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture2D, glTFModel: GLTFResource): Entity { const meshRenderer = rootEntity.createChild("Mesh").addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCylinder(engine); + meshRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const unlitMaterial = new UnlitMaterial(engine); unlitMaterial.baseTexture = glTFModel.textures[0]; meshRenderer.setMaterial(unlitMaterial); @@ -93,7 +93,7 @@ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture particleRenderer.renderMode = ParticleRenderMode.Mesh; // particleRenderer.mesh = glTFModel.meshes[0][0]; - particleRenderer.mesh = PrimitiveMesh.createCylinder(engine); + particleRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const generator = particleRenderer.generator; generator.useAutoRandomSeed = false; diff --git a/e2e/case/particleRenderer-emit-mesh-cone.ts b/e2e/case/particleRenderer-emit-mesh-cone.ts index 265d10699e..b5f94c55ef 100644 --- a/e2e/case/particleRenderer-emit-mesh-cone.ts +++ b/e2e/case/particleRenderer-emit-mesh-cone.ts @@ -79,7 +79,7 @@ WebGLEngine.create({ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture2D, glTFModel: GLTFResource): Entity { const meshRenderer = rootEntity.createChild("Mesh").addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCylinder(engine); + meshRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const unlitMaterial = new UnlitMaterial(engine); unlitMaterial.baseTexture = glTFModel.textures[0]; meshRenderer.setMaterial(unlitMaterial); @@ -97,7 +97,7 @@ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture particleRenderer.renderMode = ParticleRenderMode.Mesh; // particleRenderer.mesh = glTFModel.meshes[0][0]; - particleRenderer.mesh = PrimitiveMesh.createCylinder(engine); + particleRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const generator = particleRenderer.generator; generator.useAutoRandomSeed = false; diff --git a/e2e/case/particleRenderer-emit-mesh-no-shape-world.ts b/e2e/case/particleRenderer-emit-mesh-no-shape-world.ts index 77ca228968..8369baae4e 100644 --- a/e2e/case/particleRenderer-emit-mesh-no-shape-world.ts +++ b/e2e/case/particleRenderer-emit-mesh-no-shape-world.ts @@ -66,7 +66,7 @@ WebGLEngine.create({ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture2D, glTFModel: GLTFResource): Entity { const meshRenderer = rootEntity.createChild("Mesh").addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCylinder(engine); + meshRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const unlitMaterial = new UnlitMaterial(engine); unlitMaterial.baseTexture = glTFModel.textures[0]; meshRenderer.setMaterial(unlitMaterial); @@ -85,7 +85,7 @@ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture particleRenderer.renderMode = ParticleRenderMode.Mesh; // particleRenderer.mesh = glTFModel.meshes[0][0]; - particleRenderer.mesh = PrimitiveMesh.createCylinder(engine); + particleRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const generator = particleRenderer.generator; generator.useAutoRandomSeed = false; diff --git a/e2e/case/particleRenderer-emit-mesh-no-shape.ts b/e2e/case/particleRenderer-emit-mesh-no-shape.ts index c47e03d989..a9fbea42db 100644 --- a/e2e/case/particleRenderer-emit-mesh-no-shape.ts +++ b/e2e/case/particleRenderer-emit-mesh-no-shape.ts @@ -66,7 +66,7 @@ WebGLEngine.create({ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture2D, glTFModel: GLTFResource): Entity { const meshRenderer = rootEntity.createChild("Mesh").addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCylinder(engine); + meshRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const unlitMaterial = new UnlitMaterial(engine); unlitMaterial.baseTexture = glTFModel.textures[0]; meshRenderer.setMaterial(unlitMaterial); @@ -85,7 +85,7 @@ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture particleRenderer.renderMode = ParticleRenderMode.Mesh; // particleRenderer.mesh = glTFModel.meshes[0][0]; - particleRenderer.mesh = PrimitiveMesh.createCylinder(engine); + particleRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const generator = particleRenderer.generator; generator.useAutoRandomSeed = false; diff --git a/e2e/case/particleRenderer-emit-mesh-size-over-lifetime.ts b/e2e/case/particleRenderer-emit-mesh-size-over-lifetime.ts index 7bebc27712..58c4ec7733 100644 --- a/e2e/case/particleRenderer-emit-mesh-size-over-lifetime.ts +++ b/e2e/case/particleRenderer-emit-mesh-size-over-lifetime.ts @@ -55,7 +55,7 @@ function createSizeOverLifetimeParticle(engine: Engine): Entity { particleRenderer.setMaterial(material); particleRenderer.renderMode = ParticleRenderMode.Mesh; - particleRenderer.mesh = PrimitiveMesh.createCuboid(engine); + particleRenderer.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); const generator = particleRenderer.generator; generator.useAutoRandomSeed = false; diff --git a/e2e/case/primitive-all.ts b/e2e/case/primitive-all.ts new file mode 100644 index 0000000000..b4c0baaf07 --- /dev/null +++ b/e2e/case/primitive-all.ts @@ -0,0 +1,244 @@ +/** + * @title All Primitive Meshes + * @category Primitive + */ +import { + BlinnPhongMaterial, + Camera, + DirectLight, + Entity, + Font, + Logger, + MeshRenderer, + ModelMesh, + PrimitiveMesh, + TextRenderer, + Texture2D, + TextureFilterMode, + TextureFormat, + Vector2, + Vector3, + WebGLEngine +} from "@galacean/engine"; +import type { PrimitiveMeshAsset } from "@galacean/engine"; +import { initScreenshot, updateForE2E } from "./.mockForE2E"; + +class PrimitiveMeshGallery { + static async create(): Promise { + await document.fonts.load('24px "AlibabaSans"'); + const engine = await WebGLEngine.create({ canvas: "canvas" }); + engine.canvas.setAutoResolution(2); + const scene = engine.sceneManager.activeScene; + scene.background.solidColor.set(0.035, 0.045, 0.065, 1); + scene.ambientLight.diffuseSolidColor.set(0.6, 0.6, 0.6, 1); + + const root = scene.createRootEntity("PrimitiveMeshGallery"); + const cameraEntity = root.createChild("Camera"); + cameraEntity.transform.setPosition(0, 0, 30); + const camera = cameraEntity.addComponent(Camera); + camera.isOrthographic = true; + camera.orthographicSize = 6.8; + camera.farClipPlane = 100; + + const light = root.createChild("Light"); + light.transform.setRotation(35, -35, 0); + light.addComponent(DirectLight).color.set(0.9, 0.9, 0.9, 1); + + const texture = PrimitiveMeshGallery._createChecker(engine); + const material = new BlinnPhongMaterial(engine); + material.baseTexture = texture; + material.specularColor.set(0.18, 0.18, 0.18, 1); + material.shininess = 32; + const capMaterial = new BlinnPhongMaterial(engine); + capMaterial.baseTexture = texture; + capMaterial.baseColor.set(0.8, 0.9, 1, 1); + capMaterial.specularColor.set(0.18, 0.18, 0.18, 1); + const font = Font.createFromOS(engine, "AlibabaSans"); + + const profile = [ + new Vector2(0, -1), + new Vector2(0.7, -1), + new Vector2(0.85, -0.65), + new Vector2(0.45, 0), + new Vector2(0.6, 0.65), + new Vector2(0.7, 1) + ]; + const path = [ + new Vector3(-1, -0.6, 0), + new Vector3(-0.5, 0.6, 0.4), + new Vector3(0.3, -0.3, 0), + new Vector3(1, 0.6, -0.2) + ]; + const polygon = { + points: [ + new Vector2(-1, -0.7), + new Vector2(-0.7, -1), + new Vector2(0.7, -1), + new Vector2(1, -0.7), + new Vector2(1, 0.7), + new Vector2(0.7, 1), + new Vector2(-0.7, 1), + new Vector2(-1, 0.7) + ], + holes: [[new Vector2(-0.35, -0.35), new Vector2(-0.35, 0.35), new Vector2(0.35, 0.35), new Vector2(0.35, -0.35)]] + }; + const cases: Record = { + cuboid: { + label: "Cuboid", + mesh: PrimitiveMesh.createCuboid(engine, 1, 1, 1, { + separateMaterialSlots: true, + widthSegments: 2, + heightSegments: 2, + depthSegments: 2 + }) + }, + plane: { + label: "Plane", + mesh: PrimitiveMesh.createPlane(engine, 2, 2, { widthSegments: 4, depthSegments: 4 }), + rotation: new Vector3(90, 0, 0) + }, + sphere: { label: "Sphere", mesh: PrimitiveMesh.createSphere(engine, 1, { subdivisionLevel: 3 }) }, + cylinder: { + label: "Cylinder", + mesh: PrimitiveMesh.createCylinder(engine, 0.65, 1.5, { + separateMaterialSlots: true, + radialSegments: 24, + heightSegments: 2 + }) + }, + cone: { + label: "Cone", + mesh: PrimitiveMesh.createCone(engine, 0.8, 1.8, { + separateMaterialSlots: true, + radialSegments: 24, + heightSegments: 2 + }) + }, + truncatedCone: { + label: "Truncated Cone", + mesh: PrimitiveMesh.createTruncatedCone(engine, 0.35, 0.8, 1.6, { + separateMaterialSlots: true, + radialSegments: 24, + heightSegments: 2 + }) + }, + capsule: { + label: "Capsule", + mesh: PrimitiveMesh.createCapsule(engine, 0.5, 1, { radialSegments: 24, capSegments: 8, heightSegments: 2 }) + }, + torus: { + label: "Torus", + mesh: PrimitiveMesh.createTorus(engine, 0.75, 0.25, { ringSegments: 32, radialSegments: 12 }) + }, + torusKnot: { + label: "Torus Knot", + mesh: PrimitiveMesh.createTorusKnot(engine, 0.65, 0.17, 2, 3, { pathSegments: 96, radialSegments: 10 }) + }, + circle: { + label: "Circle", + mesh: PrimitiveMesh.createCircle(engine, 1, { segments: 32 }), + rotation: new Vector3() + }, + ring: { + label: "Ring", + mesh: PrimitiveMesh.createRing(engine, 1, 0.5, { ringSegments: 32, widthSegments: 2 }), + rotation: new Vector3() + }, + tetrahedron: { label: "Tetrahedron", mesh: PrimitiveMesh.createTetrahedron(engine, 1) }, + octahedron: { label: "Octahedron", mesh: PrimitiveMesh.createOctahedron(engine, 1) }, + icosahedron: { label: "Icosahedron", mesh: PrimitiveMesh.createIcosahedron(engine, 1) }, + dodecahedron: { label: "Dodecahedron", mesh: PrimitiveMesh.createDodecahedron(engine, 1) }, + revolvedSurface: { + label: "Revolved surface", + mesh: PrimitiveMesh.createRevolvedSurface(engine, profile, { segments: 24 }) + }, + tube: { + label: "Tube", + mesh: PrimitiveMesh.createTube(engine, path, 0.2, { pathSegments: 48, radialSegments: 10 }) + }, + polygon: { label: "Polygon", mesh: PrimitiveMesh.createPolygon(engine, polygon), rotation: new Vector3() }, + extrudedPolygon: { + label: "Extruded polygon", + mesh: PrimitiveMesh.createExtrudedPolygon(engine, polygon, 0.6, { + bevelWidth: 0.1, + bevelDepth: 0.1, + bevelSegments: 3, + separateMaterialSlots: true, + depthSegments: 2 + }) + }, + roundedCuboid: { + label: "Rounded Cuboid", + mesh: PrimitiveMesh.createRoundedCuboid(engine, 2, 1.6, 1.4, 0.3, { + separateMaterialSlots: true, + roundingSegments: 4 + }) + } + }; + const coveredFactories = Object.keys(cases).map((type) => `create${type[0].toUpperCase()}${type.slice(1)}`); + const missingFactories = Object.getOwnPropertyNames(PrimitiveMesh).filter( + (name) => name.startsWith("create") && !coveredFactories.includes(name) + ); + if (missingFactories.length > 0) { + throw new Error(`Primitive gallery is missing: ${missingFactories.join(", ")}`); + } + + const entries = Object.entries(cases); + const columns = 6; + const rows = Math.ceil(entries.length / columns); + entries.forEach(([type, { label, mesh, rotation }], index) => { + const row = Math.floor(index / columns); + const rowColumns = Math.min(columns, entries.length - row * columns); + const x = ((index % columns) - (rowColumns - 1) / 2) * 3.3; + const y = ((rows - 1) / 2 - row) * 3.3; + const pivot = root.createChild(type); + pivot.transform.setPosition(x, y + 0.25, 0); + pivot.transform.rotation = rotation ?? new Vector3(18, -30, 0); + const { min, max } = mesh.bounds; + const scale = 1.9 / Math.max(max.x - min.x, max.y - min.y, max.z - min.z); + pivot.transform.setScale(scale, scale, scale); + const entity = pivot.createChild("Mesh"); + entity.transform.setPosition(-(min.x + max.x) / 2, -(min.y + max.y) / 2, -(min.z + max.z) / 2); + const renderer = entity.addComponent(MeshRenderer); + renderer.mesh = mesh; + renderer.setMaterials(mesh.subMeshes.map((_, slot) => (slot === 0 ? material : capMaterial))); + PrimitiveMeshGallery._createLabel(root, font, label, x, y - 1.1); + }); + + updateForE2E(engine); + initScreenshot(engine, camera); + } + + private static _createChecker(engine: WebGLEngine): Texture2D { + const size = 64; + const pixels = new Uint8Array(size * size * 4); + for (let y = 0; y < size; y++) { + for (let x = 0; x < size; x++) { + const dark = ((x >> 3) + (y >> 3)) % 2 === 0; + const offset = (y * size + x) * 4; + pixels[offset] = dark ? 40 : 224; + pixels[offset + 1] = dark ? 119 : 234; + pixels[offset + 2] = dark ? 181 : 244; + pixels[offset + 3] = 255; + } + } + const texture = new Texture2D(engine, size, size, TextureFormat.R8G8B8A8, true); + texture.setPixelBuffer(pixels); + texture.generateMipmaps(); + texture.filterMode = TextureFilterMode.Trilinear; + return texture; + } + + private static _createLabel(root: Entity, font: Font, text: string, x: number, y: number): void { + const entity = root.createChild(`${text} Label`); + entity.transform.setPosition(x, y, 0); + const renderer = entity.addComponent(TextRenderer); + renderer.font = font; + renderer.fontSize = 24; + renderer.text = text; + renderer.color.set(0.85, 0.9, 0.97, 1); + } +} + +Logger.enable(); +PrimitiveMeshGallery.create(); diff --git a/e2e/case/primitive-capsule.ts b/e2e/case/primitive-capsule.ts index ae9da8711a..f4ba4dc554 100644 --- a/e2e/case/primitive-capsule.ts +++ b/e2e/case/primitive-capsule.ts @@ -55,7 +55,7 @@ WebGLEngine.create({ canvas: "canvas" }).then((engine) => { transform.setPosition(0, 1, 0); transform.setRotation(45, 45, 0); const meshRenderer = entity.addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCapsule(engine, 0.5, 1, 24, 1); + meshRenderer.mesh = PrimitiveMesh.createCapsule(engine, 0.5, 1, { radialSegments: 24 }); meshRenderer.setMaterial(material); updateForE2E(engine); diff --git a/e2e/case/primitive-cone.ts b/e2e/case/primitive-cone.ts index 8eb2680ae6..bf19b10982 100644 --- a/e2e/case/primitive-cone.ts +++ b/e2e/case/primitive-cone.ts @@ -55,7 +55,7 @@ WebGLEngine.create({ canvas: "canvas" }).then((engine) => { transform.setPosition(0, 1, 0); transform.setRotation(45, 45, 0); const meshRenderer = entity.addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCone(engine); + meshRenderer.mesh = PrimitiveMesh.createCone(engine, 0.5, 2); meshRenderer.setMaterial(material); updateForE2E(engine); diff --git a/e2e/case/primitive-contours.ts b/e2e/case/primitive-contours.ts new file mode 100644 index 0000000000..734c20b166 --- /dev/null +++ b/e2e/case/primitive-contours.ts @@ -0,0 +1,121 @@ +import { PrimitiveMesh, Vector2, Vector3 } from "@galacean/engine"; +import { PrimitiveMeshGallery } from "./.primitiveMeshGallery"; + +/** + * Polygon contours, bevels and open or closed path sweeps. + */ +class PrimitiveContours { + static async create(): Promise { + const gallery = await PrimitiveMeshGallery.create(); + const { engine } = gallery; + const front = new Vector3(); + const outline = [new Vector2(-1, -1), new Vector2(1, -1), new Vector2(1, 1), new Vector2(-1, 1)]; + const concave = [ + new Vector2(-1, -1), + new Vector2(1, -1), + new Vector2(1, -0.2), + new Vector2(0, -0.2), + new Vector2(0, 1), + new Vector2(-1, 1) + ]; + const hole = [ + new Vector2(-0.35, -0.35), + new Vector2(-0.35, 0.35), + new Vector2(0.35, 0.35), + new Vector2(0.35, -0.35) + ]; + const polygon = { points: outline, holes: [hole] }; + const twoHoles = { + points: outline, + holes: [-0.5, 0.5].map((offset) => hole.map(({ x, y }) => new Vector2(x * 0.55 + offset, y))) + }; + const shapes = [-0.65, 0.65].map((offset) => ({ + points: outline.map(({ x, y }) => new Vector2(x * 0.45 + offset, y * 0.65)) + })); + const path = Array.from({ length: 25 }, (_, i) => { + const t = i / 24; + return new Vector3(-1.2 + 2.4 * t, 0.45 * Math.sin(t * Math.PI * 2), 0.3 * Math.cos(t * Math.PI)); + }); + const loop = Array.from({ length: 32 }, (_, i) => { + const angle = (i / 32) * Math.PI * 2; + return new Vector3(Math.cos(angle), Math.sin(angle), 0.15 * Math.sin(angle * 3)); + }); + const smallProfile = outline.map(({ x, y }) => new Vector2(x * 0.16, y * 0.16)); + const smallHoleProfile = { points: smallProfile, holes: [hole.map(({ x, y }) => new Vector2(x * 0.2, y * 0.2))] }; + gallery.show( + "Contours, bevels and path sweeps", + [ + { + label: "Concave polygon", + detail: "automatic triangulation", + mesh: PrimitiveMesh.createPolygon(engine, concave), + rotation: front + }, + { + label: "Two holes", + detail: "outer + 2 inner contours", + mesh: PrimitiveMesh.createPolygon(engine, twoHoles), + rotation: front + }, + { + label: "Multiple polygons", + detail: "2 disjoint contours", + mesh: PrimitiveMesh.createPolygon(engine, shapes), + rotation: front + }, + { + label: "Straight extrusion", + detail: "depth: 0.6 / no bevel", + mesh: PrimitiveMesh.createExtrudedPolygon(engine, polygon, 0.6) + }, + { + label: "Independent bevel depth", + detail: "bevel width: 0.16 / depth: 0.06", + mesh: PrimitiveMesh.createExtrudedPolygon(engine, polygon, 0.6, { + bevelWidth: 0.16, + bevelDepth: 0.06, + bevelSegments: 4 + }) + }, + { + label: "Expanded contour", + detail: "offset: +0.15 / no bevel", + mesh: PrimitiveMesh.createExtrudedPolygon(engine, polygon, 0.6, { contourOffset: 0.15 }) + }, + { + label: "Contracted contour", + detail: "contourOffset: -0.15", + mesh: PrimitiveMesh.createExtrudedPolygon(engine, polygon, 0.6, { contourOffset: -0.15, bevelWidth: 0.08 }) + }, + { + label: "Open tube", + detail: "point array / open ends", + mesh: PrimitiveMesh.createTube(engine, path, 0.15, { pathSegments: 48, radialSegments: 12 }) + }, + { + label: "Closed tube", + detail: "closedPath: true / seamless join", + mesh: PrimitiveMesh.createTube(engine, loop, 0.15, { pathSegments: 64, radialSegments: 12, closedPath: true }) + }, + { + label: "Open profile sweep", + detail: "pathSegments: 48", + mesh: PrimitiveMesh.createExtrudedPolygon(engine, smallProfile, path, { pathSegments: 48 }) + }, + { + label: "Closed profile sweep", + detail: "closedPath: true / no caps", + mesh: PrimitiveMesh.createExtrudedPolygon(engine, smallProfile, loop, { pathSegments: 64, closedPath: true }) + }, + { + label: "Hollow profile sweep", + detail: "path + inner contour", + mesh: PrimitiveMesh.createExtrudedPolygon(engine, smallHoleProfile, path, { pathSegments: 48 }) + } + ], + 4 + ); + } +} + +PrimitiveContours.create(); diff --git a/e2e/case/primitive-cuboid.ts b/e2e/case/primitive-cuboid.ts index dd9e655672..5c43618e80 100644 --- a/e2e/case/primitive-cuboid.ts +++ b/e2e/case/primitive-cuboid.ts @@ -55,7 +55,7 @@ WebGLEngine.create({ canvas: "canvas" }).then((engine) => { transform.setPosition(0, 1, 0); transform.setRotation(45, 45, 0); const meshRenderer = entity.addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCuboid(engine); + meshRenderer.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); meshRenderer.setMaterial(material); updateForE2E(engine); diff --git a/e2e/case/primitive-cylinder.ts b/e2e/case/primitive-cylinder.ts index 77cf1c0043..b2957e4eb8 100644 --- a/e2e/case/primitive-cylinder.ts +++ b/e2e/case/primitive-cylinder.ts @@ -55,7 +55,7 @@ WebGLEngine.create({ canvas: "canvas" }).then((engine) => { transform.setPosition(0, 1, 0); transform.setRotation(45, 45, 0); const meshRenderer = entity.addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCylinder(engine); + meshRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); meshRenderer.setMaterial(material); updateForE2E(engine); diff --git a/e2e/case/primitive-materials.ts b/e2e/case/primitive-materials.ts new file mode 100644 index 0000000000..229616d998 --- /dev/null +++ b/e2e/case/primitive-materials.ts @@ -0,0 +1,137 @@ +import { AssetType, ModelMesh, PrimitiveMesh, PrimitiveMeshAsset, Vector2, Vector3 } from "@galacean/engine"; +import { PrimitiveMeshExample, PrimitiveMeshGallery } from "./.primitiveMeshGallery"; + +/** + * Material slots, retained mesh data and JSON asset creation. + */ +class PrimitiveMaterials { + static async create(): Promise { + const gallery = await PrimitiveMeshGallery.create(); + const { engine } = gallery; + const square = [new Vector2(-1, -1), new Vector2(1, -1), new Vector2(1, 1), new Vector2(-1, 1)]; + const polygons = [-0.6, 0.6].map((offset) => ({ + points: square.map(({ x, y }) => new Vector2(x * 0.4 + offset, y * 0.6)) + })); + const loop = Array.from({ length: 32 }, (_, i) => { + const angle = (i / 32) * Math.PI * 2; + return new Vector3(Math.cos(angle), Math.sin(angle), 0.1 * Math.sin(angle * 3)); + }); + const profiles = [-0.12, 0.12].map((offset) => ({ + points: square.map(({ x, y }) => new Vector2(x * 0.07 + offset, y * 0.07)) + })); + const asset = { + type: "sphere", + sphereRadius: 1, + sphereOptions: { subdivisionLevel: 2 } + } satisfies PrimitiveMeshAsset; + const url = URL.createObjectURL(new Blob([JSON.stringify(asset)], { type: "application/json" })); + const loaded = await engine.resourceManager.load({ type: AssetType.PrimitiveMesh, url }); + URL.revokeObjectURL(url); + const retained = PrimitiveMesh.createSphere(engine, 1, { subdivisionLevel: 2, keepMeshData: true }); + if (loaded.accessible || !retained.accessible || loaded.vertexCount !== retained.vertexCount) { + throw new Error("Primitive data retention or JSON asset creation differs from the factory."); + } + const examples: (PrimitiveMeshExample & { slots: number })[] = [ + { + label: "Cuboid / one material", + detail: "single material slot", + mesh: PrimitiveMesh.createCuboid(engine, 1, 1, 1), + slots: 1 + }, + { + label: "Cuboid / face materials", + detail: "+Y -Y -X +X +Z -Z", + mesh: PrimitiveMesh.createCuboid(engine, 1, 1, 1, { separateMaterialSlots: true }), + slots: 6 + }, + { + label: "Cylinder / part materials", + detail: "side / top / bottom", + mesh: PrimitiveMesh.createCylinder(engine, 0.5, 1.4, { separateMaterialSlots: true }), + slots: 3 + }, + { + label: "Cone / part materials", + detail: "side / bottom", + mesh: PrimitiveMesh.createCone(engine, 0.5, 1.4, { separateMaterialSlots: true }), + slots: 2, + rotation: new Vector3(-25, -28, 0) + }, + { + label: "Polygon / shape materials", + detail: "one slot per polygon", + mesh: PrimitiveMesh.createPolygon(engine, polygons, { separateMaterialSlots: true }), + slots: 2, + rotation: new Vector3() + }, + { + label: "Extruded / cap and wall", + detail: "caps / walls + bevels", + mesh: PrimitiveMesh.createExtrudedPolygon(engine, square, 0.6, { + bevelWidth: 0.12, + separateMaterialSlots: true + }), + slots: 2 + }, + { + label: "Closed / two profiles", + detail: "one wall slot per profile", + mesh: PrimitiveMesh.createExtrudedPolygon(engine, profiles, loop, { + pathSegments: 64, + closedPath: true, + separateMaterialSlots: true + }), + slots: 2 + }, + { + label: "Rounded / face materials", + detail: "six material slots", + mesh: PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.2, { + roundingSegments: 4, + separateMaterialSlots: true + }), + slots: 6 + }, + { + label: "Factory / retained data", + detail: "CPU data: readable", + mesh: retained, + slots: 1, + appearance: "checker" + }, + { + label: "JSON asset / released data", + detail: "CPU data: released", + mesh: loaded, + slots: 1, + appearance: "checker" + }, + { + label: "Mirrored torus knot", + detail: "axis: 2 / section: -3", + mesh: PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2, -3, { pathSegments: 96 }), + slots: 1, + appearance: "checker" + }, + { + label: "Clamped corner radius", + detail: "radius: 2 clamped to 0.5", + mesh: PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 2, { roundingSegments: 6 }), + slots: 1, + appearance: "checker" + } + ]; + for (const { label, mesh, slots } of examples) { + if (mesh.subMeshes.length !== slots) { + throw new Error(`${label}: expected ${slots} material slots, got ${mesh.subMeshes.length}.`); + } + } + gallery.show( + "Material groups, CPU data and JSON assets", + examples.map((example) => ({ ...example, appearance: example.appearance ?? "groups" })), + 4 + ); + } +} + +PrimitiveMaterials.create(); diff --git a/e2e/case/primitive-plane.ts b/e2e/case/primitive-plane.ts index f56cf5f085..7edcc659a3 100644 --- a/e2e/case/primitive-plane.ts +++ b/e2e/case/primitive-plane.ts @@ -55,7 +55,7 @@ WebGLEngine.create({ canvas: "canvas" }).then((engine) => { transform.setPosition(0, 1, 0); transform.setRotation(45, -45, 0); const meshRenderer = entity.addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createPlane(engine); + meshRenderer.mesh = PrimitiveMesh.createPlane(engine, 1, 1); meshRenderer.setMaterial(material); updateForE2E(engine); diff --git a/e2e/case/primitive-sections.ts b/e2e/case/primitive-sections.ts new file mode 100644 index 0000000000..c862bfa016 --- /dev/null +++ b/e2e/case/primitive-sections.ts @@ -0,0 +1,101 @@ +import { PrimitiveMesh, PrimitiveMeshCapMode, Vector2, Vector3 } from "@galacean/engine"; +import { PrimitiveMeshGallery } from "./.primitiveMeshGallery"; + +/** + * Angular ranges and independent end-cap controls. + */ +class PrimitiveSections { + static async create(): Promise { + const gallery = await PrimitiveMeshGallery.create(); + const { engine } = gallery; + const front = new Vector3(); + const profile = [new Vector2(0, -1), new Vector2(0.7, -1), new Vector2(0.9, 0), new Vector2(0.6, 1)]; + gallery.show( + "Angular ranges and end caps", + [ + { + label: "Circle sector", + detail: "angleRange: [30, 300]", + mesh: PrimitiveMesh.createCircle(engine, 0.5, { angleRange: new Vector2(30, 300) }), + rotation: front + }, + { + label: "Ring sector", + detail: "angleRange: [30, 300]", + mesh: PrimitiveMesh.createRing(engine, 0.5, 0.25, { angleRange: new Vector2(30, 300) }), + rotation: front + }, + { + label: "Torus arc", + detail: "ringAngleRange: [30, 300]", + mesh: PrimitiveMesh.createTorus(engine, 0.5, 0.1, { ringAngleRange: new Vector2(30, 300) }) + }, + { + label: "Torus cross-section", + detail: "tubeAngleRange: [0, 180]", + mesh: PrimitiveMesh.createTorus(engine, 0.5, 0.2, { tubeAngleRange: new Vector2(0, 180) }) + }, + { + label: "Both torus ranges", + detail: "arc 270 / tube 270 degrees", + mesh: PrimitiveMesh.createTorus(engine, 0.5, 0.2, { + ringAngleRange: new Vector2(30, 300), + tubeAngleRange: new Vector2(45, 315) + }) + }, + { label: "Cylinder: both", detail: "caps: both", mesh: PrimitiveMesh.createCylinder(engine, 0.5, 1.4) }, + { + label: "Cylinder: top", + detail: "caps: top", + mesh: PrimitiveMesh.createCylinder(engine, 0.5, 1.4, { caps: PrimitiveMeshCapMode.Top }) + }, + { + label: "Cylinder: bottom", + detail: "caps: bottom", + mesh: PrimitiveMesh.createCylinder(engine, 0.5, 1.4, { caps: PrimitiveMeshCapMode.Bottom }), + rotation: new Vector3(-25, -28, 0) + }, + { + label: "Cylinder: open", + detail: "caps: none", + mesh: PrimitiveMesh.createCylinder(engine, 0.5, 1.4, { caps: PrimitiveMeshCapMode.None }) + }, + { + label: "Cylinder sector", + detail: "angleRange: [30, 270]", + mesh: PrimitiveMesh.createCylinder(engine, 0.5, 1.4, { angleRange: new Vector2(30, 270) }) + }, + { + label: "Truncated cone sector", + detail: "top 0.25 / bottom 0.6", + mesh: PrimitiveMesh.createTruncatedCone(engine, 0.25, 0.6, 1.4, { angleRange: new Vector2(30, 270) }) + }, + { + label: "Cone with cap", + detail: "cap: true", + mesh: PrimitiveMesh.createCone(engine, 0.5, 1.4), + rotation: new Vector3(-25, -28, 0) + }, + { + label: "Cone without cap", + detail: "cap: false", + mesh: PrimitiveMesh.createCone(engine, 0.5, 1.4, { cap: false }), + rotation: new Vector3(-25, -28, 0) + }, + { + label: "Full revolved surface", + detail: "angleRange: [0, 360]", + mesh: PrimitiveMesh.createRevolvedSurface(engine, profile, { segments: 32 }) + }, + { + label: "Partial revolved surface", + detail: "angleRange: [30, 270]", + mesh: PrimitiveMesh.createRevolvedSurface(engine, profile, { segments: 32, angleRange: new Vector2(30, 270) }) + } + ], + 5 + ); + } +} + +PrimitiveSections.create(); diff --git a/e2e/case/primitive-sphere-sections.ts b/e2e/case/primitive-sphere-sections.ts new file mode 100644 index 0000000000..c0ee87bb6e --- /dev/null +++ b/e2e/case/primitive-sphere-sections.ts @@ -0,0 +1,101 @@ +import { + BlinnPhongMaterial, + Camera, + DirectLight, + Font, + MeshRenderer, + PrimitiveMesh, + RenderFace, + TextRenderer, + Texture2D, + TextureFilterMode, + TextureFormat, + Vector2, + Vector3, + WebGLEngine +} from "@galacean/engine"; +import { initScreenshot, updateForE2E } from "./.mockForE2E"; + +class SphereSections { + static async create(): Promise { + await document.fonts.load('24px "AlibabaSans"'); + const engine = await WebGLEngine.create({ canvas: "canvas" }); + engine.canvas.setAutoResolution(2); + const scene = engine.sceneManager.activeScene; + scene.background.solidColor.set(0.035, 0.045, 0.065, 1); + scene.ambientLight.diffuseSolidColor.set(0.6, 0.6, 0.6, 1); + const root = scene.createRootEntity("Sphere Sections"); + const cameraEntity = root.createChild("Camera"); + cameraEntity.transform.setPosition(0, 0, 16); + const camera = cameraEntity.addComponent(Camera); + camera.isOrthographic = true; + camera.orthographicSize = 3.7; + const light = root.createChild("Light"); + light.transform.setRotation(35, -35, 0); + light.addComponent(DirectLight); + + const material = new BlinnPhongMaterial(engine); + material.renderFace = RenderFace.Double; + material.specularColor.set(0.18, 0.18, 0.18, 1); + const pixels = new Uint8Array(64 * 32 * 4); + for (let y = 0; y < 32; y++) { + for (let x = 0; x < 64; x++) { + const dark = ((x >> 2) + (y >> 2)) % 2 === 0; + const offset = (y * 64 + x) * 4; + pixels[offset] = dark ? 40 : 224; + pixels[offset + 1] = dark ? 119 : 234; + pixels[offset + 2] = dark ? 181 : 244; + pixels[offset + 3] = 255; + } + } + const texture = new Texture2D(engine, 64, 32, TextureFormat.R8G8B8A8, true); + texture.setPixelBuffer(pixels); + texture.generateMipmaps(); + texture.filterMode = TextureFilterMode.Trilinear; + material.baseTexture = texture; + const cases: { + name: string; + horizontalAngleRange?: Vector2; + verticalAngleRange?: Vector2; + rotation?: Vector3; + }[] = [ + { name: "Full sphere" }, + { name: "Hemisphere", verticalAngleRange: new Vector2(0, 90) }, + { name: "Half longitude", horizontalAngleRange: new Vector2(90, 270) }, + { name: "Octant", horizontalAngleRange: new Vector2(90, 180), verticalAngleRange: new Vector2(0, 90) }, + { name: "Latitude band", verticalAngleRange: new Vector2(50, 130) }, + { + name: "Across 360 degrees", + horizontalAngleRange: new Vector2(330, 390), + verticalAngleRange: new Vector2(20, 160), + rotation: new Vector3(20, 90, 0) + } + ]; + const font = Font.createFromOS(engine, "AlibabaSans"); + cases.forEach(({ name, horizontalAngleRange, verticalAngleRange, rotation }, index) => { + const x = ((index % 3) - 1) * 3.3; + const y = (0.5 - Math.floor(index / 3)) * 3.2; + const entity = root.createChild(name); + entity.transform.setPosition(x, y + 0.2, 0); + entity.transform.rotation = rotation ?? new Vector3(20, -35, 0); + const renderer = entity.addComponent(MeshRenderer); + renderer.mesh = PrimitiveMesh.createSphere(engine, 1, { + horizontalAngleRange, + verticalAngleRange, + subdivisionLevel: 3 + }); + renderer.setMaterial(material); + const label = root.createChild(`${name} Label`); + label.transform.setPosition(x, y - 1.15, 0); + const text = label.addComponent(TextRenderer); + text.font = font; + text.fontSize = 24; + text.text = name; + text.color.set(0.85, 0.9, 0.97, 1); + }); + updateForE2E(engine); + initScreenshot(engine, camera); + } +} + +SphereSections.create(); diff --git a/e2e/case/primitive-sphere.ts b/e2e/case/primitive-sphere.ts index 709da5c504..4d73f50c5d 100644 --- a/e2e/case/primitive-sphere.ts +++ b/e2e/case/primitive-sphere.ts @@ -55,7 +55,7 @@ WebGLEngine.create({ canvas: "canvas" }).then((engine) => { transform.setPosition(0, 1, 0); transform.setRotation(45, 45, 0); const meshRenderer = entity.addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createSubdivisionSurfaceSphere(engine); + meshRenderer.mesh = PrimitiveMesh.createSphere(engine, 0.5); meshRenderer.setMaterial(material); updateForE2E(engine); diff --git a/e2e/case/primitive-topology.ts b/e2e/case/primitive-topology.ts new file mode 100644 index 0000000000..68a788ebf9 --- /dev/null +++ b/e2e/case/primitive-topology.ts @@ -0,0 +1,178 @@ +import { PrimitiveMesh, Vector2, Vector3 } from "@galacean/engine"; +import { PrimitiveMeshExample, PrimitiveMeshGallery } from "./.primitiveMeshGallery"; + +/** + * Triangle distribution, subdivision controls and rounded edge quality. + */ +class PrimitiveTopology { + static async create(): Promise { + const gallery = await PrimitiveMeshGallery.create(); + const { engine } = gallery; + const keep = { keepMeshData: true }; + const examples: PrimitiveMeshExample[] = [ + { + label: "Sphere / level 1", + detail: "subdivisionLevel: 1", + mesh: PrimitiveMesh.createSphere(engine, 0.5, { ...keep, subdivisionLevel: 1 }) + }, + { + label: "Sphere / level 3", + detail: "subdivisionLevel: 3", + mesh: PrimitiveMesh.createSphere(engine, 0.5, { ...keep, subdivisionLevel: 3 }) + }, + { + label: "Cylinder / 6 sides", + detail: "radialSegments: 6", + mesh: PrimitiveMesh.createCylinder(engine, 0.5, 2, { ...keep, radialSegments: 6 }) + }, + { + label: "Cylinder / 24 sides", + detail: "radial: 24 / height: 4", + mesh: PrimitiveMesh.createCylinder(engine, 0.5, 2, { ...keep, radialSegments: 24, heightSegments: 4 }) + }, + { + label: "Cone / 6 sides", + detail: "radial: 6 / height: 3", + mesh: PrimitiveMesh.createCone(engine, 0.5, 2, { ...keep, radialSegments: 6, heightSegments: 3 }) + }, + { + label: "Cuboid subdivisions", + detail: "width: 4 / height: 2 / depth: 3", + mesh: PrimitiveMesh.createCuboid(engine, 1, 1, 1, { + ...keep, + widthSegments: 4, + heightSegments: 2, + depthSegments: 3 + }) + }, + { + label: "Plane / 1 by 6", + detail: "width: 1 / depth: 6", + mesh: PrimitiveMesh.createPlane(engine, 1, 1, { ...keep, widthSegments: 1, depthSegments: 6 }), + rotation: new Vector3(65, -20, 0) + }, + { + label: "Plane / 6 by 1", + detail: "width: 6 / depth: 1", + mesh: PrimitiveMesh.createPlane(engine, 1, 1, { ...keep, widthSegments: 6, depthSegments: 1 }), + rotation: new Vector3(65, -20, 0) + }, + { + label: "Capsule / coarse caps", + detail: "radial: 8 / caps: 2 / height: 1", + mesh: PrimitiveMesh.createCapsule(engine, 0.5, 1, { ...keep, radialSegments: 8, capSegments: 2 }) + }, + { + label: "Capsule / fine caps", + detail: "radial: 16 / caps: 8 / height: 4", + mesh: PrimitiveMesh.createCapsule(engine, 0.5, 1, { + ...keep, + radialSegments: 16, + capSegments: 8, + heightSegments: 4 + }) + }, + { + label: "Tetrahedron subdivision", + detail: "edgeSegments: 3", + mesh: PrimitiveMesh.createTetrahedron(engine, 0.5, { ...keep, edgeSegments: 3 }) + }, + { + label: "Octahedron subdivision", + detail: "edgeSegments: 3", + mesh: PrimitiveMesh.createOctahedron(engine, 0.5, { ...keep, edgeSegments: 3 }) + }, + { + label: "Icosahedron subdivision", + detail: "edgeSegments: 3", + mesh: PrimitiveMesh.createIcosahedron(engine, 0.5, { ...keep, edgeSegments: 3 }) + }, + { + label: "Dodecahedron subdivision", + detail: "edgeSegments: 3", + mesh: PrimitiveMesh.createDodecahedron(engine, 0.5, { ...keep, edgeSegments: 3 }) + }, + { + label: "Sphere / level 2", + detail: "subdivisionLevel: 2", + mesh: PrimitiveMesh.createSphere(engine, 0.5, { ...keep, subdivisionLevel: 2 }) + }, + { + label: "Rounded cuboid / zero", + detail: "cornerRadius: 0", + mesh: PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0, { ...keep }) + }, + { + label: "Rounded cuboid / coarse", + detail: "radius: 0.2 / rounding: 1", + mesh: PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.2, { ...keep, roundingSegments: 1 }) + }, + { + label: "Rounded cuboid / fine", + detail: "radius: 0.2 / rounding: 4", + mesh: PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.2, { ...keep, roundingSegments: 4 }) + }, + { + label: "Torus knot / 2, 3", + detail: "axis: 2 / section: 3", + mesh: PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2, 3, { ...keep, pathSegments: 96 }) + }, + { + label: "Torus knot / 3, 2", + detail: "axis: 3 / section: 2", + mesh: PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 3, 2, { ...keep, pathSegments: 96 }) + }, + { + label: "Circle / 8 segments", + detail: "segments: 8", + mesh: PrimitiveMesh.createCircle(engine, 0.5, { ...keep, segments: 8 }), + rotation: new Vector3() + }, + { + label: "Ring / width subdivisions", + detail: "ring: 12 / width: 4", + mesh: PrimitiveMesh.createRing(engine, 0.5, 0.25, { ...keep, ringSegments: 12, widthSegments: 4 }), + rotation: new Vector3() + }, + { + label: "Revolved surface", + detail: "segments: 8", + mesh: PrimitiveMesh.createRevolvedSurface( + engine, + [new Vector2(0.4, -1), new Vector2(0.8, 0), new Vector2(0.4, 1)], + { + ...keep, + segments: 8 + } + ) + }, + { + label: "Tube / path subdivisions", + detail: "path: 12 / radial: 6", + mesh: PrimitiveMesh.createTube( + engine, + [new Vector3(-1, -0.4, 0), new Vector3(0, 0.4, 0.3), new Vector3(1, -0.4, 0)], + 0.2, + { ...keep, pathSegments: 12, radialSegments: 6 } + ) + }, + { + label: "Extruded / bevel layers", + detail: "segments: depth 3 / bevel 3", + mesh: PrimitiveMesh.createExtrudedPolygon( + engine, + [new Vector2(-1, -1), new Vector2(1, -1), new Vector2(1, 1), new Vector2(-1, 1)], + 0.6, + { ...keep, depthSegments: 3, bevelWidth: 0.15, bevelSegments: 3 } + ) + } + ]; + gallery.show( + "Subdivision and triangle topology", + examples.map((example) => ({ ...example, wireframe: true })), + 5 + ); + } +} + +PrimitiveTopology.create(); diff --git a/e2e/case/primitive-torus.ts b/e2e/case/primitive-torus.ts index b658731611..ddbbe3dcd8 100644 --- a/e2e/case/primitive-torus.ts +++ b/e2e/case/primitive-torus.ts @@ -55,7 +55,7 @@ WebGLEngine.create({ canvas: "canvas" }).then((engine) => { transform.setPosition(0, 1, 0); transform.setRotation(45, 45, 0); const meshRenderer = entity.addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createTorus(engine); + meshRenderer.mesh = PrimitiveMesh.createTorus(engine, 0.5, 0.1); meshRenderer.setMaterial(material); updateForE2E(engine); diff --git a/e2e/case/shader-mrt.ts b/e2e/case/shader-mrt.ts index 39513e1c12..10b0627ac1 100644 --- a/e2e/case/shader-mrt.ts +++ b/e2e/case/shader-mrt.ts @@ -97,7 +97,7 @@ WebGLEngine.create({ canvas: "canvas", shaderCompiler }).then((engine) => { const sphere = rootEntity.createChild("sphere"); sphere.transform.position.x = -1; const renderer = sphere.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createSphere(engine); + renderer.mesh = PrimitiveMesh.createSphere(engine, 0.5); const material = new Material(engine, shader); material.shaderData.setColor("material_BaseColor", new Color(1, 0, 0, 0.2)); renderer.setMaterial(material); diff --git a/e2e/case/shader-renderState.ts b/e2e/case/shader-renderState.ts index c968c12d4e..1051e50ae5 100644 --- a/e2e/case/shader-renderState.ts +++ b/e2e/case/shader-renderState.ts @@ -102,7 +102,7 @@ WebGLEngine.create({ canvas: "canvas", shaderCompiler }).then((engine) => { const sphere = rootEntity.createChild("sphere"); sphere.transform.position.x = -1; const renderer = sphere.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createSphere(engine); + renderer.mesh = PrimitiveMesh.createSphere(engine, 0.5); const material = new Material(engine, shader); material.shaderData.setColor("u_color", new Color(1, 0, 0, 0.2)); renderer.setMaterial(material); @@ -113,7 +113,7 @@ WebGLEngine.create({ canvas: "canvas", shaderCompiler }).then((engine) => { const cuboid = rootEntity.createChild("sphere"); cuboid.transform.position.x = 1; const renderer = cuboid.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createCuboid(engine); + renderer.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); const material = new Material(engine, shader); material.shaderData.setColor("u_color", new Color(1, 0, 0, 0.2)); renderer.setMaterial(material); diff --git a/e2e/case/texture-hdr-ktx2.ts b/e2e/case/texture-hdr-ktx2.ts index 9442c6ca6f..3787e6cfff 100644 --- a/e2e/case/texture-hdr-ktx2.ts +++ b/e2e/case/texture-hdr-ktx2.ts @@ -71,7 +71,7 @@ WebGLEngine.create({ canvas: "canvas", shaderCompiler, ktx2Loader: { workerCount const planeEntity = rootEntity.createChild("plane"); const meshRenderer = planeEntity.addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCuboid(engine); + meshRenderer.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); const mtl = new Material(engine, Shader.create(shaderSource)); meshRenderer.setMaterial(mtl); diff --git a/e2e/case/texture-sRGB-KTX2.ts b/e2e/case/texture-sRGB-KTX2.ts index 99803b82aa..de0a198aa5 100644 --- a/e2e/case/texture-sRGB-KTX2.ts +++ b/e2e/case/texture-sRGB-KTX2.ts @@ -37,7 +37,7 @@ WebGLEngine.create({ canvas: "canvas" }).then((engine) => { const entity = rootEntity.createChild("mesh"); entity.transform.setRotation(0, 90, 0); const meshRenderer = entity.addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createSubdivisionSurfaceSphere(engine); + meshRenderer.mesh = PrimitiveMesh.createSphere(engine, 0.5); meshRenderer.setMaterial(material); updateForE2E(engine); diff --git a/e2e/config.ts b/e2e/config.ts index 077a5fc1bd..0a6c444235 100644 --- a/e2e/config.ts +++ b/e2e/config.ts @@ -229,10 +229,46 @@ export const E2E_CONFIG = { } }, Primitive: { + sections: { + category: "Primitive", + caseFileName: "primitive-sections", + threshold: 0.005, + diffPercentage: 0.02 + }, + contours: { + category: "Primitive", + caseFileName: "primitive-contours", + threshold: 0.005, + diffPercentage: 0.02 + }, + topology: { + category: "Primitive", + caseFileName: "primitive-topology", + threshold: 0.005, + diffPercentage: 0.02 + }, + materials: { + category: "Primitive", + caseFileName: "primitive-materials", + threshold: 0.005, + diffPercentage: 0.02 + }, + "sphere-sections": { + category: "Primitive", + caseFileName: "primitive-sphere-sections", + threshold: 0.005, + diffPercentage: 0.02 + }, + all: { + category: "Primitive", + caseFileName: "primitive-all", + threshold: 0.005, + diffPercentage: 0.02 + }, capsule: { category: "Primitive", caseFileName: "primitive-capsule", - threshold: 0, + threshold: 0.005, diffPercentage: 0.0016 }, cone: { @@ -244,7 +280,7 @@ export const E2E_CONFIG = { cuboid: { category: "Primitive", caseFileName: "primitive-cuboid", - threshold: 0, + threshold: 0.005, diffPercentage: 0.0016 }, cylinder: { @@ -510,19 +546,19 @@ export const E2E_CONFIG = { HDRBloomNeutral: { category: "PostProcess", caseFileName: "postProcess-HDR-bloom-neutral", - threshold: 0, + threshold: 0.01, diffPercentage: 0.001 }, LDRBloomNeutral: { category: "PostProcess", caseFileName: "postProcess-LDR-bloom-neutral", - threshold: 0, + threshold: 0.01, diffPercentage: 0.001 }, customPass: { category: "PostProcess", caseFileName: "postProcess-customPass", - threshold: 0, + threshold: 0.01, diffPercentage: 0.001 } }, diff --git a/e2e/fixtures/originImage/Advance_multi-camera-no-clear.jpg b/e2e/fixtures/originImage/Advance_multi-camera-no-clear.jpg index 5a455c4eb1..a06581c8f3 100644 --- a/e2e/fixtures/originImage/Advance_multi-camera-no-clear.jpg +++ b/e2e/fixtures/originImage/Advance_multi-camera-no-clear.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:92cb9ba66eb97d9e96e4d1133e9cf608c9aa423a2721ccfb035ec81d8b8eb181 -size 80973 +oid sha256:91d47e860a044edca16c491d0281d797ae3ef79710e4d4ee15323b8f7e3abf5f +size 80830 diff --git a/e2e/fixtures/originImage/GPUInstancing_gpu-instancing-custom-data.jpg b/e2e/fixtures/originImage/GPUInstancing_gpu-instancing-custom-data.jpg index 79399c097c..06239fe2c6 100644 --- a/e2e/fixtures/originImage/GPUInstancing_gpu-instancing-custom-data.jpg +++ b/e2e/fixtures/originImage/GPUInstancing_gpu-instancing-custom-data.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:baece2c4437803e1474699eb4e99214b38caa05393f747fe0f7e47bd6469a693 -size 427005 +oid sha256:c175f3edbc26fa28d2b3740c0f6c7adc0f1de5bc3492289a3537781cc31f5ab3 +size 426976 diff --git a/e2e/fixtures/originImage/Material_material-white-furnace.jpg b/e2e/fixtures/originImage/Material_material-white-furnace.jpg index 0d3d0f0673..e866d550db 100644 --- a/e2e/fixtures/originImage/Material_material-white-furnace.jpg +++ b/e2e/fixtures/originImage/Material_material-white-furnace.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:bde04ade6f986bb3b4f907810f5a30360312c449f1778df115fe0cd13aee9a4b -size 18784 +oid sha256:fbf371dd786ff6b29eeeb4640bcbc22152746791c17332ecd400fa6e4e854f75 +size 18635 diff --git a/e2e/fixtures/originImage/Material_shader-mrt.jpg b/e2e/fixtures/originImage/Material_shader-mrt.jpg index 4621abc35a..01293843a3 100644 --- a/e2e/fixtures/originImage/Material_shader-mrt.jpg +++ b/e2e/fixtures/originImage/Material_shader-mrt.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:233b89b0d3bf85389142f721bc072d86f4efcc42b8df9567efb6ccd041269c70 -size 23846 +oid sha256:4ce5429b6f6f61dd8471e121d1ba3fd71eec59490b2e1292e9926dd1f5a06f3d +size 23374 diff --git a/e2e/fixtures/originImage/Material_shader-renderState.jpg b/e2e/fixtures/originImage/Material_shader-renderState.jpg index 2f37e8844b..5c9196b332 100644 --- a/e2e/fixtures/originImage/Material_shader-renderState.jpg +++ b/e2e/fixtures/originImage/Material_shader-renderState.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:23b7bba1b3b6e5da54780cf645de6638e7c195e1c725ab804840b958116fcf41 -size 27873 +oid sha256:7ea4dc71c6ae5efd8feb1a10157cf4462e6b98969ee74c9437de577b09835193 +size 27432 diff --git a/e2e/fixtures/originImage/Physics_physx-collision-group.jpg b/e2e/fixtures/originImage/Physics_physx-collision-group.jpg index d9b0ec9c9d..7aa8c1845b 100644 --- a/e2e/fixtures/originImage/Physics_physx-collision-group.jpg +++ b/e2e/fixtures/originImage/Physics_physx-collision-group.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:526fa57a4690029471c0a6d21414b401c778e0cddebf21f24e94151e9d5de914 -size 40339 +oid sha256:6d7e517fd1ccc73369c93d51e58f35f5bbef77d4e55aa87dc6f0e6449626ea01 +size 40680 diff --git a/e2e/fixtures/originImage/Physics_physx-collision.jpg b/e2e/fixtures/originImage/Physics_physx-collision.jpg index 5716d22a3f..dd0e31a797 100644 --- a/e2e/fixtures/originImage/Physics_physx-collision.jpg +++ b/e2e/fixtures/originImage/Physics_physx-collision.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:2426a2b92ad4d62b28f5c54c255c6e072d7b02e4b79eff839ea8f75f16c34061 -size 36011 +oid sha256:bb176598a0cf0f511229594b7ca52fbaddffee30f95c5f7b0cf786765ddfb69e +size 36342 diff --git a/e2e/fixtures/originImage/Physics_physx-customUrl.jpg b/e2e/fixtures/originImage/Physics_physx-customUrl.jpg index 5716d22a3f..dd0e31a797 100644 --- a/e2e/fixtures/originImage/Physics_physx-customUrl.jpg +++ b/e2e/fixtures/originImage/Physics_physx-customUrl.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:2426a2b92ad4d62b28f5c54c255c6e072d7b02e4b79eff839ea8f75f16c34061 -size 36011 +oid sha256:bb176598a0cf0f511229594b7ca52fbaddffee30f95c5f7b0cf786765ddfb69e +size 36342 diff --git a/e2e/fixtures/originImage/Primitive_primitive-all.jpg b/e2e/fixtures/originImage/Primitive_primitive-all.jpg new file mode 100644 index 0000000000..30d83cd03d --- /dev/null +++ b/e2e/fixtures/originImage/Primitive_primitive-all.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0e23cc74fc32a2a4f0351a438be0f6bb5f76599cbff8310d2dc6f4904a2442b +size 445969 diff --git a/e2e/fixtures/originImage/Primitive_primitive-capsule.jpg b/e2e/fixtures/originImage/Primitive_primitive-capsule.jpg index 37161a8597..ff3837d7c5 100644 --- a/e2e/fixtures/originImage/Primitive_primitive-capsule.jpg +++ b/e2e/fixtures/originImage/Primitive_primitive-capsule.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6562f1c4fb7d859d202ef37c307aa4952b3c97c1fbe2e729e1bab970654aba75 -size 89665 +oid sha256:ec67fcb89db8f8876e8b67ae0de73dfd8530627cb3eaccfe7b73bc8480fb7c26 +size 76105 diff --git a/e2e/fixtures/originImage/Primitive_primitive-contours.jpg b/e2e/fixtures/originImage/Primitive_primitive-contours.jpg new file mode 100644 index 0000000000..253e0b76f3 --- /dev/null +++ b/e2e/fixtures/originImage/Primitive_primitive-contours.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:862d9e09f5b65c22f09886ae053e157b8de4088aa50db5eb514184a8503b1646 +size 697295 diff --git a/e2e/fixtures/originImage/Primitive_primitive-materials.jpg b/e2e/fixtures/originImage/Primitive_primitive-materials.jpg new file mode 100644 index 0000000000..acf3a14b95 --- /dev/null +++ b/e2e/fixtures/originImage/Primitive_primitive-materials.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf803d113676191953da120cb1ddfc0780509ceadcb1609e75f701347fa002a5 +size 522020 diff --git a/e2e/fixtures/originImage/Primitive_primitive-sections.jpg b/e2e/fixtures/originImage/Primitive_primitive-sections.jpg new file mode 100644 index 0000000000..9ff54b450c --- /dev/null +++ b/e2e/fixtures/originImage/Primitive_primitive-sections.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1d03c70656d8fe30cc0e1d850de9a226a489626be6665b3cbd4de0bea62f3d5 +size 648751 diff --git a/e2e/fixtures/originImage/Primitive_primitive-sphere-sections.jpg b/e2e/fixtures/originImage/Primitive_primitive-sphere-sections.jpg new file mode 100644 index 0000000000..1db2c1b506 --- /dev/null +++ b/e2e/fixtures/originImage/Primitive_primitive-sphere-sections.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5413ae86cf1fb15d49aa202e63b3a2859a3d06fd513a6d21f7eb66a437724384 +size 310562 diff --git a/e2e/fixtures/originImage/Primitive_primitive-topology.jpg b/e2e/fixtures/originImage/Primitive_primitive-topology.jpg new file mode 100644 index 0000000000..cad8cdd51c --- /dev/null +++ b/e2e/fixtures/originImage/Primitive_primitive-topology.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c05ec99e093e5e9fa8ea659ae38a25ce26f2afc277224baa044751e862caaff8 +size 824923 diff --git a/e2e/primitive-mesh.md b/e2e/primitive-mesh.md new file mode 100644 index 0000000000..64c0e459e5 --- /dev/null +++ b/e2e/primitive-mesh.md @@ -0,0 +1,26 @@ +# Primitive mesh visual tests + +The suite contains six galleries with 90 examples. Each screenshot fixes the camera, lighting and parameters so changes can be compared with the checked-in baseline. + +| Case | Examples | Coverage | +| --- | --: | --- | +| `primitive-all` | 20 | Every primitive factory, including the four regular polyhedra | +| `primitive-sphere-sections` | 6 | Complete sphere, hemispheres, octant, latitude band and a range crossing 360 degrees | +| `primitive-sections` | 15 | Circle/ring sectors, both torus ranges, cylinder cap combinations, cone caps and partial revolved surfaces | +| `primitive-contours` | 12 | Concave contours, multiple holes/shapes, bevel size/thickness/offset, tubes and profile sweeps | +| `primitive-topology` | 25 | Sphere subdivisions, directional segment counts, polyhedron subdivisions, rounded corners and torus knots | +| `primitive-materials` | 12 | Material-slot order, multiple shapes, `keepMeshData`, JSON asset loading and corner-radius clamping | + +Run all six galleries: + +```sh +pnpm exec playwright test --project=chromium --workers=1 --reporter=line --grep 'Primitive (all|sphere-sections|sections|contours|topology|materials)$' +``` + +After changing engine package sources, run `pnpm run build` before the tests. To inspect a gallery interactively, run `pnpm run e2e:case` and open `http://localhost:5175/mpa/primitive-all.html`, replacing the filename with another case above. + +Inspect the images in `e2e/downloads` before accepting a new baseline under `e2e/fixtures/originImage`. The topology gallery offsets its line overlay slightly along the normals to avoid depth fighting; it does not modify the displayed surface. Red and gold grid lines mark texture-coordinate boundaries. Open cuts and tubes intentionally have no end caps. The new galleries render front faces, so a cut can expose the background through the mesh. + +The galleries use a per-pixel color threshold of `0.005` to tolerate small GPU and JPEG differences. Pixels exceeding that threshold may occupy at most `0.02%` of the image. Cylinders retain their side seam at -Z and the same planar UV orientation on both caps. Capsule UV changes update the older capsule baseline. + +The all-primitives gallery checks that every factory is represented. The material gallery also asserts sub-mesh counts, CPU-data accessibility and the loaded mesh's vertex count before making the screenshot available. diff --git a/examples/src/paricle-emit-mesh.ts b/examples/src/paricle-emit-mesh.ts index 1986ca4912..c9eae2ad37 100644 --- a/examples/src/paricle-emit-mesh.ts +++ b/examples/src/paricle-emit-mesh.ts @@ -32,7 +32,7 @@ main(); function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture2D, glTFModel: GLTFResource): Entity { const meshRenderer = rootEntity.createChild("Mesh").addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCylinder(engine); + meshRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const unlitMaterial = new UnlitMaterial(engine); unlitMaterial.baseTexture = glTFModel.textures[0]; meshRenderer.setMaterial(unlitMaterial); @@ -52,7 +52,7 @@ function createFireParticle(rootEntity: Entity, engine: Engine, texture: Texture particleRenderer.renderMode = ParticleRenderMode.Mesh; // particleRenderer.mesh = glTFModel.meshes[0][0]; - particleRenderer.mesh = PrimitiveMesh.createCylinder(engine); + particleRenderer.mesh = PrimitiveMesh.createCylinder(engine, 0.5, 2); const generator = particleRenderer.generator; generator.useAutoRandomSeed = false; diff --git a/examples/src/shader-03-ui-script.ts b/examples/src/shader-03-ui-script.ts index 321a3e4b75..39826e0802 100644 --- a/examples/src/shader-03-ui-script.ts +++ b/examples/src/shader-03-ui-script.ts @@ -188,7 +188,7 @@ WebGLEngine.create({ canvas: "canvas", shaderCompiler: new ShaderCompiler() }).t // 创建平面 const planeEntity = rootEntity.createChild("plane"); const renderer = planeEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createPlane(engine, 3, 3, 20, 20); // 增加细分以显示顶点动画 + renderer.mesh = PrimitiveMesh.createPlane(engine, 3, 3, { widthSegments: 20 }); // 增加细分以显示顶点动画 renderer.setMaterial(material); // 运行引擎 diff --git a/examples/src/shader-04-multi-pass.ts b/examples/src/shader-04-multi-pass.ts index 427982f394..9bcb025633 100644 --- a/examples/src/shader-04-multi-pass.ts +++ b/examples/src/shader-04-multi-pass.ts @@ -134,7 +134,7 @@ function createSphere(engine: Engine, name: string, position: Vector3): Entity { entity.transform.position = position; const renderer = entity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createSphere(engine, 0.8, 64); + renderer.mesh = PrimitiveMesh.createSphere(engine, 0.8, { subdivisionLevel: 5 }); return entity; } diff --git a/packages/core/src/mesh/MeshTangentUtils.ts b/packages/core/src/mesh/MeshTangentUtils.ts new file mode 100644 index 0000000000..5a4bab9729 --- /dev/null +++ b/packages/core/src/mesh/MeshTangentUtils.ts @@ -0,0 +1,142 @@ +import { Vector2, Vector3, Vector4 } from "@galacean/engine-math"; + +/** + * @internal + */ +export class MeshTangentUtils { + static calculateTangents( + positions: readonly Vector3[], + normals: readonly Vector3[], + uvs: readonly Vector2[], + indices: ArrayLike | null + ): Vector4[] { + return MeshTangentUtils._calculateTangents(positions, normals, uvs, indices, null) as Vector4[]; + } + + static calculateTangentsFromBuffer(vertices: Float32Array, indices: ArrayLike | null): Float32Array { + return MeshTangentUtils._calculateTangents(null, null, null, indices, vertices) as Float32Array; + } + + private static _calculateTangents( + positions: readonly Vector3[] | null, + normals: readonly Vector3[] | null, + uvs: readonly Vector2[] | null, + indices: ArrayLike | null, + vertices: Float32Array | null + ): Vector4[] | Float32Array { + const vertexCount = vertices ? vertices.length / 8 : positions!.length; + const indexCount = indices ? indices.length : vertexCount; + // Accumulate the tangent basis in double precision + const basis = new Float64Array(vertexCount * 6); + for (let i = 0; i + 2 < indexCount; i += 3) { + const a = indices ? indices[i] : i; + const b = indices ? indices[i + 1] : i + 1; + const c = indices ? indices[i + 2] : i + 2; + let e1x: number, e1y: number, e1z: number, e2x: number, e2y: number, e2z: number; + let x1: number, x2: number, y1: number, y2: number; + if (vertices) { + const offsetA = a * 8; + const offsetB = b * 8; + const offsetC = c * 8; + e1x = vertices[offsetB] - vertices[offsetA]; + e1y = vertices[offsetB + 1] - vertices[offsetA + 1]; + e1z = vertices[offsetB + 2] - vertices[offsetA + 2]; + e2x = vertices[offsetC] - vertices[offsetA]; + e2y = vertices[offsetC + 1] - vertices[offsetA + 1]; + e2z = vertices[offsetC + 2] - vertices[offsetA + 2]; + x1 = vertices[offsetB + 6] - vertices[offsetA + 6]; + x2 = vertices[offsetC + 6] - vertices[offsetA + 6]; + y1 = vertices[offsetB + 7] - vertices[offsetA + 7]; + y2 = vertices[offsetC + 7] - vertices[offsetA + 7]; + } else { + const p0 = positions![a]; + const p1 = positions![b]; + const p2 = positions![c]; + const uv0 = uvs![a]; + const uv1 = uvs![b]; + const uv2 = uvs![c]; + e1x = p1.x - p0.x; + e1y = p1.y - p0.y; + e1z = p1.z - p0.z; + e2x = p2.x - p0.x; + e2y = p2.y - p0.y; + e2z = p2.z - p0.z; + x1 = uv1.x - uv0.x; + x2 = uv2.x - uv0.x; + y1 = uv1.y - uv0.y; + y2 = uv2.y - uv0.y; + } + const determinant = x1 * y2 - x2 * y1; + if (determinant === 0) { + continue; + } + const inverse = 1 / determinant; + const ty1 = y1 * inverse; + const ty2 = y2 * inverse; + const bx1 = x1 * inverse; + const bx2 = x2 * inverse; + const tx = e1x * ty2 - e2x * ty1; + const ty = e1y * ty2 - e2y * ty1; + const tz = e1z * ty2 - e2z * ty1; + const bx = e2x * bx1 - e1x * bx2; + const by = e2y * bx1 - e1y * bx2; + const bz = e2z * bx1 - e1z * bx2; + for (let corner = 0; corner < 3; corner++) { + const offset = (corner === 0 ? a : corner === 1 ? b : c) * 6; + basis[offset] += tx; + basis[offset + 1] += ty; + basis[offset + 2] += tz; + basis[offset + 3] += bx; + basis[offset + 4] += by; + basis[offset + 5] += bz; + } + } + + const tangents = vertices ? new Float32Array(vertexCount * 4) : new Array(vertexCount); + for (let i = 0; i < vertexCount; i++) { + let nx: number, ny: number, nz: number; + if (vertices) { + const offset = i * 8; + nx = vertices[offset + 3]; + ny = vertices[offset + 4]; + nz = vertices[offset + 5]; + } else { + const normal = normals![i]; + nx = normal.x; + ny = normal.y; + nz = normal.z; + } + const offset = i * 6; + let tx = basis[offset]; + let ty = basis[offset + 1]; + let tz = basis[offset + 2]; + const bx = basis[offset + 3]; + const by = basis[offset + 4]; + const bz = basis[offset + 5]; + const handedness = (ty * bz - tz * by) * nx + (tz * bx - tx * bz) * ny + (tx * by - ty * bx) * nz > 0 ? 1 : -1; + // Custom normals need not have unit length + const normalLengthSquared = nx * nx + ny * ny + nz * nz; + const projection = normalLengthSquared > 0 ? (tx * nx + ty * ny + tz * nz) / normalLengthSquared : 0; + tx -= nx * projection; + ty -= ny * projection; + tz -= nz * projection; + const length = Math.hypot(tx, ty, tz); + if (length > 0) { + const inverse = 1 / length; + tx *= inverse; + ty *= inverse; + tz *= inverse; + } + if (vertices) { + const result = tangents as Float32Array; + result[i * 4] = tx; + result[i * 4 + 1] = ty; + result[i * 4 + 2] = tz; + result[i * 4 + 3] = handedness; + } else { + (tangents as Vector4[])[i] = new Vector4(tx, ty, tz, handedness); + } + } + return tangents; + } +} diff --git a/packages/core/src/mesh/ModelMesh.ts b/packages/core/src/mesh/ModelMesh.ts index 7461173ee7..467fd7c15c 100644 --- a/packages/core/src/mesh/ModelMesh.ts +++ b/packages/core/src/mesh/ModelMesh.ts @@ -12,6 +12,7 @@ import { IndexFormat } from "../graphic/enums/IndexFormat"; import { VertexElementFormat } from "../graphic/enums/VertexElementFormat"; import { BlendShape } from "./BlendShape"; import { BlendShapeManager } from "./BlendShapeManager"; +import { MeshTangentUtils } from "./MeshTangentUtils"; import { VertexAttribute } from "./enums/VertexAttribute"; /** @@ -19,12 +20,6 @@ import { VertexAttribute } from "./enums/VertexAttribute"; * Define draw ranges with `addSubMesh()` and assign a material to each corresponding MeshRenderer slot. */ export class ModelMesh extends Mesh { - private static _tempVec0 = new Vector3(); - private static _tempVec1 = new Vector3(); - private static _tempVec2 = new Vector3(); - private static _tempVec3 = new Vector3(); - private static _tempVec4 = new Vector3(); - /** @internal */ _blendShapeManager: BlendShapeManager; /** @internal */ @@ -673,9 +668,11 @@ export class ModelMesh extends Mesh { } /** - * Calculate mesh tangent. - * @remark need to set positions(with or not with indices), normals, uv before calculation. - * @remark based on http://foundationsofgameenginedev.com/FGED2-sample.pdf + * Calculate tangents from readable positions, normals and UVs. + * @remarks + * Without indices, every three consecutive vertices form a triangle. + * Incomplete trailing triangles and triangles with zero UV area are ignored. + * @see http://foundationsofgameenginedev.com/FGED2-sample.pdf */ calculateTangents(): void { const positions = this.getPositions()!; @@ -686,78 +683,7 @@ export class ModelMesh extends Mesh { throw "Set normal and uv before calculation."; } - const { _indices: indices, vertexCount } = this; - const { _tempVec0: e1, _tempVec1: e2, _tempVec2: t, _tempVec3: b, _tempVec4: temp } = ModelMesh; - const triangleCount = indices ? indices.length / 3 : positions.length / 3; - const tangents = new Array(vertexCount); - const biTangents = new Array(vertexCount); - for (let i = 0; i < vertexCount; i++) { - tangents[i] = new Vector4(); - biTangents[i] = new Vector3(); - } - - // Calculate tangent and bi-tangent for each triangle and add to all three vertices. - for (let k = 0; k < triangleCount; k++) { - let i0 = 3 * k; - let i1 = 3 * k + 1; - let i2 = 3 * k + 2; - if (indices) { - i0 = indices[i0]; - i1 = indices[i1]; - i2 = indices[i2]; - } - - const p0 = positions[i0]; - const p1 = positions[i1]; - const p2 = positions[i2]; - const w0 = uvs[i0]; - const w1 = uvs[i1]; - const w2 = uvs[i2]; - - Vector3.subtract(p1, p0, e1); - Vector3.subtract(p2, p0, e2); - const x1 = w1.x - w0.x; - const x2 = w2.x - w0.x; - const y1 = w1.y - w0.y; - const y2 = w2.y - w0.y; - const r = 1.0 / (x1 * y2 - x2 * y1); - - Vector3.scale(e1, y2 * r, t); - Vector3.scale(e2, y1 * r, temp); - Vector3.subtract(t, temp, t); - Vector3.scale(e2, x1 * r, b); - Vector3.scale(e1, x2 * r, temp); - Vector3.subtract(b, temp, b); - - let tangent = tangents[i0]; - tangent.set(tangent.x + t.x, tangent.y + t.y, tangent.z + t.z, 1.0); - - tangent = tangents[i1]; - tangent.set(tangent.x + t.x, tangent.y + t.y, tangent.z + t.z, 1.0); - - tangent = tangents[i2]; - tangent.set(tangent.x + t.x, tangent.y + t.y, tangent.z + t.z, 1.0); - - biTangents[i0].add(b); - biTangents[i1].add(b); - biTangents[i2].add(b); - } - - // Orthonormalize each tangent and calculate the handedness. - for (let i = 0; i < vertexCount; i++) { - const n = normals[i]; - const b = biTangents[i]; - const tangent = tangents[i]; - t.set(tangent.x, tangent.y, tangent.z); - - Vector3.cross(t, b, temp); - const w = Vector3.dot(temp, n) > 0.0 ? 1 : -1; - Vector3.scale(n, Vector3.dot(t, n), temp); - Vector3.subtract(t, temp, t); - t.normalize(); - tangent.set(t.x, t.y, t.z, w); - } - this.setTangents(tangents); + this.setTangents(MeshTangentUtils.calculateTangents(positions, normals, uvs, this._indices)); } /** @@ -766,27 +692,28 @@ export class ModelMesh extends Mesh { override _setVertexBufferBinding(index: number, binding: VertexBufferBinding | null): void { const vertexBufferBindings = this._primitive.vertexBufferBindings; const updateInfos = this._vertexBufferInfos; - const onVertexBufferChanged = () => { - if (!this._advancedDataSyncToBuffer) { - updateInfos[index].dataVersion = this._dataVersionCounter++; - } - }; + let updateInfo = updateInfos[index]; - // Remove listener from previous binding const previousBinding = vertexBufferBindings[index]; - previousBinding && previousBinding.buffer._dataUpdateManager.removeListener(onVertexBufferChanged); + if (previousBinding) { + previousBinding.buffer._dataUpdateManager.removeListener(updateInfo.onBufferChanged); + } super._setVertexBufferBinding(index, binding); - // Add listener to new binding and trigger update if (binding) { - binding.buffer._dataUpdateManager.addListener(onVertexBufferChanged); - (updateInfos[index] ||= new BufferUpdateInfo()).reset(); - onVertexBufferChanged(); - } else { - if (index + 1 == vertexBufferBindings.length) { - vertexBufferBindings.length--; + if (!updateInfo) { + updateInfo = updateInfos[index] = new BufferUpdateInfo(() => { + if (!this._advancedDataSyncToBuffer) { + updateInfos[index].dataVersion = this._dataVersionCounter++; + } + }); } + binding.buffer._dataUpdateManager.addListener(updateInfo.onBufferChanged); + updateInfo.reset(); + updateInfo.onBufferChanged(); + } else if (index + 1 == vertexBufferBindings.length) { + vertexBufferBindings.length--; } } @@ -812,6 +739,10 @@ export class ModelMesh extends Mesh { * @internal */ protected override _onDestroy(): void { + const bindings = this._primitive.vertexBufferBindings; + for (let i = 0; i < bindings.length; i++) { + bindings[i]?.buffer._dataUpdateManager.removeListener(this._vertexBufferInfos[i].onBufferChanged); + } super._onDestroy(); this._releaseCache(true); } @@ -1337,6 +1268,8 @@ class BufferUpdateInfo { dataVersion: number = -1; uploadAdvancedData: boolean = false; + constructor(readonly onBufferChanged: () => void) {} + reset(): void { this.uploadAdvancedData = false; } diff --git a/packages/core/src/mesh/PrimitiveMesh.ts b/packages/core/src/mesh/PrimitiveMesh.ts index 25ae7e8d3c..d073ae5396 100644 --- a/packages/core/src/mesh/PrimitiveMesh.ts +++ b/packages/core/src/mesh/PrimitiveMesh.ts @@ -1,28 +1,46 @@ -import { MathUtil, Vector3 } from "@galacean/engine-math"; +import { MathUtil, Vector2, Vector3 } from "@galacean/engine-math"; import { Engine } from "../Engine"; import { GLCapabilityType } from "../base/Constant"; import { BufferBindFlag, BufferUsage, VertexElement, VertexElementFormat } from "../graphic"; import { Buffer } from "../graphic/Buffer"; import { ModelMesh } from "./ModelMesh"; -import { - CapsuleRestoreInfo, - ConeRestoreInfo, - CuboidRestoreInfo, - CylinderRestoreInfo, - PlaneRestoreInfo, - PrimitiveMeshRestorer, - SphereRestoreInfo, - SubdivisionSurfaceSphereRestoreInfo, - TorusRestoreInfo -} from "./PrimitiveMeshRestorer"; +import type { + SphereMeshOptions, + CuboidMeshOptions, + PlaneMeshOptions, + CylinderMeshOptions, + TruncatedConeMeshOptions, + ConeMeshOptions, + CapsuleMeshOptions, + TorusMeshOptions, + CircleMeshOptions, + RingMeshOptions, + RegularPolyhedronMeshOptions, + RevolvedSurfaceMeshOptions, + TubeMeshOptions, + PolygonMeshOptions, + LinearExtrudedPolygonMeshOptions, + PathExtrudedPolygonMeshOptions, + TorusKnotMeshOptions, + RoundedCuboidMeshOptions, + PolygonShape +} from "./PrimitiveMeshOptions"; +import { PrimitiveMeshCapMode } from "./enums/PrimitiveMeshCapMode"; import { VertexAttribute } from "./enums/VertexAttribute"; +import { PrimitiveMeshBuilder } from "./primitive/PrimitiveMeshBuilder"; +import { PrimitiveMeshRestorer } from "./primitive/PrimitiveMeshRestorer"; +import { MeshPathUtils } from "./primitive/MeshPathUtils"; +import { PolygonUtils } from "./primitive/PolygonUtils"; +import { SubdivisionUtils } from "./primitive/SubdivisionUtils"; /** - * Used to generate common primitive meshes. + * Creates primitive meshes in local space. Angle ranges use degrees. + * Meshes have one sub-mesh unless material grouping is enabled. + * @remarks + * Input arrays and vectors are copied. Changing them later does not update the mesh. + * Device restoration uses the original creation inputs; later mesh edits are not backed up. */ export class PrimitiveMesh { - private static _tempVec30: Vector3 = new Vector3(); - private static readonly _sphereSeedPositions = new Float32Array([ -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, 1, -1, -1, 1, 1, -1, -1, -1, -1, -1, 1, -1 ]); @@ -30,305 +48,1881 @@ export class PrimitiveMesh { private static readonly _sphereSeedCells = new Float32Array([ 0, 1, 2, 3, 3, 2, 4, 5, 5, 4, 6, 7, 7, 0, 3, 5, 7, 6, 1, 0, 6, 4, 2, 1 ]); + private static readonly _goldenRatio = (1 + Math.sqrt(5)) / 2; + private static readonly _inverseGoldenRatio = 1 / PrimitiveMesh._goldenRatio; + private static readonly _regularPolyhedra: Record = { + tetrahedron: [ + [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1], + [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1] + ], + octahedron: [ + [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1], + [0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2] + ], + icosahedron: [ + [ + -1, + PrimitiveMesh._goldenRatio, + 0, + 1, + PrimitiveMesh._goldenRatio, + 0, + -1, + -PrimitiveMesh._goldenRatio, + 0, + 1, + -PrimitiveMesh._goldenRatio, + 0, + 0, + -1, + PrimitiveMesh._goldenRatio, + 0, + 1, + PrimitiveMesh._goldenRatio, + 0, + -1, + -PrimitiveMesh._goldenRatio, + 0, + 1, + -PrimitiveMesh._goldenRatio, + PrimitiveMesh._goldenRatio, + 0, + -1, + PrimitiveMesh._goldenRatio, + 0, + 1, + -PrimitiveMesh._goldenRatio, + 0, + -1, + -PrimitiveMesh._goldenRatio, + 0, + 1 + ], + [ + 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, + 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 + ] + ], + dodecahedron: [ + [ + -1, + -1, + -1, + -1, + -1, + 1, + -1, + 1, + -1, + -1, + 1, + 1, + 1, + -1, + -1, + 1, + -1, + 1, + 1, + 1, + -1, + 1, + 1, + 1, + 0, + -PrimitiveMesh._inverseGoldenRatio, + -PrimitiveMesh._goldenRatio, + 0, + -PrimitiveMesh._inverseGoldenRatio, + PrimitiveMesh._goldenRatio, + 0, + PrimitiveMesh._inverseGoldenRatio, + -PrimitiveMesh._goldenRatio, + 0, + PrimitiveMesh._inverseGoldenRatio, + PrimitiveMesh._goldenRatio, + -PrimitiveMesh._inverseGoldenRatio, + -PrimitiveMesh._goldenRatio, + 0, + -PrimitiveMesh._inverseGoldenRatio, + PrimitiveMesh._goldenRatio, + 0, + PrimitiveMesh._inverseGoldenRatio, + -PrimitiveMesh._goldenRatio, + 0, + PrimitiveMesh._inverseGoldenRatio, + PrimitiveMesh._goldenRatio, + 0, + -PrimitiveMesh._goldenRatio, + 0, + -PrimitiveMesh._inverseGoldenRatio, + PrimitiveMesh._goldenRatio, + 0, + -PrimitiveMesh._inverseGoldenRatio, + -PrimitiveMesh._goldenRatio, + 0, + PrimitiveMesh._inverseGoldenRatio, + PrimitiveMesh._goldenRatio, + 0, + PrimitiveMesh._inverseGoldenRatio + ], + [ + 3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, + 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, + 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, + 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9 + ] + ] + }; - private static _sphereEdgeIdx: number = 0; - private static _spherePoleIdx: number = 0; + /** + * Create a sphere or an open spherical section from a subdivided cube. + * U follows the horizontal angle interval and V follows the vertical angle interval, each scaled to 0–1. + * The horizontal start marks the U seam; V increases from the upper to the lower boundary. + * @param engine - The engine that owns the mesh + * @param radius - The radius in local units + * @param options - Optional mesh generation settings + * @returns The generated mesh + */ + static createSphere(engine: Engine, radius: number, options?: SphereMeshOptions): ModelMesh { + const subdivisionLevel = options?.subdivisionLevel ?? 3; + const horizontalAngleRange = options?.horizontalAngleRange; + const verticalAngleRange = options?.verticalAngleRange; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createSphereData, + [ + radius, + subdivisionLevel, + horizontalAngleRange?.x ?? 0, + horizontalAngleRange?.y ?? 360, + verticalAngleRange?.x ?? 0, + verticalAngleRange?.y ?? 180 + ], + options + ); + } /** - * Create a sphere mesh. - * @param engine - Engine - * @param radius - Sphere radius - * @param segments - Number of segments - * @param noLongerAccessible - No longer access the vertices of the mesh after creation - * @returns Sphere model mesh + * Create an axis-aligned cuboid centered at the origin. + * @remarks + * Each face spans 0–1 in U/V. Face directions (+U, +V) are: + * +Y: (+X, +Z); -Y: (+X, -Z); -X: (+Z, -Y); + * +X: (-Z, -Y); +Z: (+X, -Y); -Z: (-X, -Y). + * @param engine - The engine that owns the mesh + * @param width - The full size along X in local units + * @param height - The full size along Y in local units + * @param depth - The full size along Z in local units + * @param options - Optional mesh generation settings + * @returns The generated mesh */ - static createSphere( + static createCuboid( engine: Engine, - radius: number = 0.5, - segments: number = 18, - noLongerAccessible: boolean = true + width: number, + height: number, + depth: number, + options?: CuboidMeshOptions ): ModelMesh { - const sphereMesh = new ModelMesh(engine); - PrimitiveMesh._setSphereData(sphereMesh, radius, segments, noLongerAccessible, false); + const widthSegments = options?.widthSegments ?? 1; + const heightSegments = options?.heightSegments ?? widthSegments; + const depthSegments = options?.depthSegments ?? widthSegments; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createCuboidData, + [width, height, depth, widthSegments, heightSegments, depthSegments], + options + ); + } - const vertexBuffer = sphereMesh.vertexBufferBindings[0]!.buffer; - engine.resourceManager.addContentRestorer( - new PrimitiveMeshRestorer(sphereMesh, new SphereRestoreInfo(radius, segments, vertexBuffer, noLongerAccessible)) + /** + * Create a plane in XZ facing +Y, centered at the origin. + * UVs span 0–1, with U along +X and V along +Z. + * @param engine - The engine that owns the mesh + * @param width - The full size along X in local units + * @param depth - The full size along Z in local units + * @param options - Optional mesh generation settings + * @returns The generated mesh + */ + static createPlane(engine: Engine, width: number, depth: number, options?: PlaneMeshOptions): ModelMesh { + const widthSegments = options?.widthSegments ?? 1; + const depthSegments = options?.depthSegments ?? widthSegments; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createPlaneData, + [width, depth, widthSegments, depthSegments], + options ); - return sphereMesh; } /** - * Create a sphere mesh by implementing Catmull-Clark Surface Subdivision Algorithm. - * Max step is limited to 6. - * @param engine - Engine - * @param radius - Sphere radius - * @param step - Number of subdiv steps - * @param noLongerAccessible - No longer access the vertices of the mesh after creation - * @returns Sphere model mesh + * Create a cylinder centered on Y with equal end radii. + * U spans the angular range from 0 to 1; V runs from 0 at the top to 1 at the bottom. + * The default side seam is at -Z. Both caps use planar UVs with U along +X and V along -Z. + * @param engine - The engine that owns the mesh + * @param radius - The radius in local units + * @param height - The full size along Y in local units + * @param options - Optional mesh generation settings + * @returns The generated mesh */ - static createSubdivisionSurfaceSphere( - engine: Engine, - radius: number = 0.5, - step: number = 3, - noLongerAccessible: boolean = true - ): ModelMesh { - const sphereMesh = new ModelMesh(engine); - PrimitiveMesh._setSubdivisionSurfaceSphereData(sphereMesh, radius, step, noLongerAccessible, false); - - const vertexBuffer = sphereMesh.vertexBufferBindings[0]!.buffer; - engine.resourceManager.addContentRestorer( - new PrimitiveMeshRestorer( - sphereMesh, - new SubdivisionSurfaceSphereRestoreInfo(radius, step, vertexBuffer, noLongerAccessible) - ) + static createCylinder(engine: Engine, radius: number, height: number, options?: CylinderMeshOptions): ModelMesh { + const radialSegments = options?.radialSegments ?? 20; + const heightSegments = options?.heightSegments ?? 1; + const caps = options?.caps ?? PrimitiveMeshCapMode.Both; + const angleRange = options?.angleRange; + const startAngle = angleRange?.x ?? 0; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createCylinderData, + [ + radius, + radius, + height, + radialSegments, + heightSegments, + caps === PrimitiveMeshCapMode.Both || caps === PrimitiveMeshCapMode.Top, + caps === PrimitiveMeshCapMode.Both || caps === PrimitiveMeshCapMode.Bottom, + startAngle, + (angleRange?.y ?? 360) - startAngle, + options?.separateMaterialSlots ?? false + ], + options ); - return sphereMesh; } /** - * Create a cuboid mesh. - * @param engine - Engine - * @param width - Cuboid width - * @param height - Cuboid height - * @param depth - Cuboid depth - * @param noLongerAccessible - No longer access the vertices of the mesh after creation - * @returns Cuboid model mesh + * Create a truncated cone centered on Y with independently sized ends. + * U spans the angular range from 0 to 1; V runs from 0 at the top to 1 at the bottom. + * The default side seam is at -Z. Both caps use planar UVs with U along +X and V along -Z. + * @param engine - The engine that owns the mesh + * @param topRadius - The top radius in local units + * @param bottomRadius - The bottom radius in local units + * @param height - The full size along Y in local units + * @param options - Optional mesh generation settings + * @returns The generated mesh */ - static createCuboid( + static createTruncatedCone( engine: Engine, - width: number = 1, - height: number = 1, - depth: number = 1, - noLongerAccessible: boolean = true + topRadius: number, + bottomRadius: number, + height: number, + options?: TruncatedConeMeshOptions ): ModelMesh { - const mesh = new ModelMesh(engine); - PrimitiveMesh._setCuboidData(mesh, width, height, depth, noLongerAccessible, false); + const radialSegments = options?.radialSegments ?? 20; + const heightSegments = options?.heightSegments ?? 1; + const caps = options?.caps ?? PrimitiveMeshCapMode.Both; + const angleRange = options?.angleRange; + const startAngle = angleRange?.x ?? 0; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createCylinderData, + [ + topRadius, + bottomRadius, + height, + radialSegments, + heightSegments, + caps === PrimitiveMeshCapMode.Both || caps === PrimitiveMeshCapMode.Top, + caps === PrimitiveMeshCapMode.Both || caps === PrimitiveMeshCapMode.Bottom, + startAngle, + (angleRange?.y ?? 360) - startAngle, + options?.separateMaterialSlots ?? false + ], + options + ); + } - const vertexBuffer = mesh.vertexBufferBindings[0]!.buffer; - engine.resourceManager.addContentRestorer( - new PrimitiveMeshRestorer(mesh, new CuboidRestoreInfo(width, height, depth, vertexBuffer, noLongerAccessible)) + /** + * Create a cone centered on Y with its tip at the top. + * U spans the angular range from 0 to 1; V runs from 0 at the tip to 1 at the base. + * The default side seam is at -Z. The base uses planar UVs with U along +X and V along -Z. + * @param engine - The engine that owns the mesh + * @param radius - The bottom radius in local units + * @param height - The full size along Y in local units + * @param options - Optional mesh generation settings + * @returns The generated mesh + */ + static createCone(engine: Engine, radius: number, height: number, options?: ConeMeshOptions): ModelMesh { + const radialSegments = options?.radialSegments ?? 20; + const heightSegments = options?.heightSegments ?? 1; + const cap = options?.cap ?? true; + const angleRange = options?.angleRange; + const startAngle = angleRange?.x ?? 0; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createCylinderData, + [0, radius, height, radialSegments, heightSegments, false, cap, startAngle, (angleRange?.y ?? 360) - startAngle], + options ); - return mesh; } /** - * Create a plane mesh with U mapped along local +X and V along local +Z. - * @param engine - Engine - * @param width - Plane width along the local X axis - * @param height - Plane height along the local Z axis - * @param horizontalSegments - Plane horizontal segments - * @param verticalSegments - Plane vertical segments - * @param noLongerAccessible - No longer access the vertices of the mesh after creation - * @returns Plane model mesh + * Create a capsule centered on Y. + * U runs around Y from -Z towards -X. V runs from 0 at the top to 1 at the bottom, + * proportional to surface length along the hemispheres and cylinder. + * @param engine - The engine that owns the mesh + * @param radius - The radius of the cylinder and hemispherical ends in local units + * @param cylinderHeight - The straight cylindrical section height in local units; total height is `cylinderHeight + 2 * radius` + * @param options - Optional mesh generation settings + * @returns The generated mesh */ - static createPlane( + static createCapsule( engine: Engine, - width: number = 1, - height: number = 1, - horizontalSegments: number = 1, - verticalSegments: number = 1, - noLongerAccessible: boolean = true + radius: number, + cylinderHeight: number, + options?: CapsuleMeshOptions ): ModelMesh { - const mesh = new ModelMesh(engine); - PrimitiveMesh._setPlaneData(mesh, width, height, horizontalSegments, verticalSegments, noLongerAccessible, false); - - const vertexBuffer = mesh.vertexBufferBindings[0]!.buffer; - engine.resourceManager.addContentRestorer( - new PrimitiveMeshRestorer( - mesh, - new PlaneRestoreInfo(width, height, horizontalSegments, verticalSegments, vertexBuffer, noLongerAccessible) - ) + const radialSegments = options?.radialSegments ?? 6; + const capSegments = options?.capSegments ?? radialSegments; + const heightSegments = options?.heightSegments ?? 1; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createCapsuleData, + [radius, cylinderHeight, radialSegments, capSegments, heightSegments], + options ); - return mesh; } /** - * Create a cylinder mesh. - * @param engine - Engine - * @param radiusTop - The radius of top cap - * @param radiusBottom - The radius of bottom cap - * @param height - The height of torso - * @param radialSegments - Cylinder radial segments - * @param heightSegments - Cylinder height segments - * @param noLongerAccessible - No longer access the vertices of the mesh after creation - * @returns Cylinder model mesh + * Create a torus centered in XY around Z. + * U spans the ring angle interval and V spans the tube angle interval, each scaled to 0–1. + * @param engine - The engine that owns the mesh + * @param radius - The distance from the origin to the tube centerline in local units + * @param tubeRadius - The radius of the tube cross-section in local units + * @param options - Optional mesh generation settings + * @returns The generated mesh */ - static createCylinder( - engine: Engine, - radiusTop: number = 0.5, - radiusBottom: number = 0.5, - height: number = 2, - radialSegments: number = 20, - heightSegments: number = 1, - noLongerAccessible: boolean = true - ): ModelMesh { - const mesh = new ModelMesh(engine); - PrimitiveMesh._setCylinderData( - mesh, - radiusTop, - radiusBottom, - height, - radialSegments, - heightSegments, - noLongerAccessible, - false + static createTorus(engine: Engine, radius: number, tubeRadius: number, options?: TorusMeshOptions): ModelMesh { + const ringSegments = options?.ringSegments ?? 30; + const radialSegments = options?.radialSegments ?? 30; + const ringAngleRange = options?.ringAngleRange; + const tubeAngleRange = options?.tubeAngleRange; + const startAngle = ringAngleRange?.x ?? 0; + const tubeStartAngle = tubeAngleRange?.x ?? 0; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createTorusData, + [ + radius, + tubeRadius, + radialSegments, + ringSegments, + (ringAngleRange?.y ?? 360) - startAngle, + tubeStartAngle, + (tubeAngleRange?.y ?? 360) - tubeStartAngle, + startAngle + ], + options ); + } - const vertexBuffer = mesh.vertexBufferBindings[0]!.buffer; - engine.resourceManager.addContentRestorer( - new PrimitiveMeshRestorer( - mesh, - new CylinderRestoreInfo( - radiusTop, - radiusBottom, - height, - radialSegments, - heightSegments, - vertexBuffer, - noLongerAccessible - ) - ) + /** + * Create a filled disk or sector in XY facing +Z. + * UVs project X/Y onto the full disk's bounding square; angular cuts do not rescale them. + * @param engine - The engine that owns the mesh + * @param radius - The radius in local units + * @param options - Optional mesh generation settings + * @returns The generated mesh + */ + static createCircle(engine: Engine, radius: number, options?: CircleMeshOptions): ModelMesh { + const segments = options?.segments ?? 32; + const angleRange = options?.angleRange; + const startAngle = angleRange?.x ?? 0; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createCircleData, + [radius, segments, startAngle, (angleRange?.y ?? 360) - startAngle], + options ); - return mesh; } /** - * Create a torus mesh. - * @param engine - Engine - * @param radius - Torus radius - * @param tubeRadius - Torus tube - * @param radialSegments - Torus radial segments - * @param tubularSegments - Torus tubular segments - * @param arc - Central angle - * @param noLongerAccessible - No longer access the vertices of the mesh after creation - * @returns Torus model mesh + * Create a ring or ring sector in XY facing +Z. + * UVs project X/Y onto the outer disk's bounding square; angular cuts do not rescale them. + * @param engine - The engine that owns the mesh + * @param outerRadius - The outer radius in local units + * @param innerRadius - The inner radius in local units + * @param options - Optional mesh generation settings + * @returns The generated mesh */ - static createTorus( + static createRing(engine: Engine, outerRadius: number, innerRadius: number, options?: RingMeshOptions): ModelMesh { + const ringSegments = options?.ringSegments ?? 32; + const widthSegments = options?.widthSegments ?? 1; + const angleRange = options?.angleRange; + const startAngle = angleRange?.x ?? 0; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createRingData, + [innerRadius, outerRadius, ringSegments, widthSegments, startAngle, (angleRange?.y ?? 360) - startAngle], + options + ); + } + + /** + * Create a regular tetrahedron or its spherical subdivision. + * UVs use spherical projection around Y, with the U seam at +X and V from 0 at +Y to 1 at -Y. + * Triangles crossing the U seam may use values above 1. + * @param engine - The engine that owns the mesh + * @param radius - The distance from the origin to each vertex in local units + * @param options - Optional mesh generation settings + * @returns The generated mesh + */ + static createTetrahedron(engine: Engine, radius: number, options?: RegularPolyhedronMeshOptions): ModelMesh { + const edgeSegments = options?.edgeSegments ?? 1; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createRegularPolyhedronData, + ["tetrahedron", radius, edgeSegments], + options + ); + } + + /** + * Create a regular octahedron or its spherical subdivision. + * UVs use spherical projection around Y, with the U seam at +X and V from 0 at +Y to 1 at -Y. + * Triangles crossing the U seam may use values above 1. + * @param engine - The engine that owns the mesh + * @param radius - The distance from the origin to each vertex in local units + * @param options - Optional mesh generation settings + * @returns The generated mesh + */ + static createOctahedron(engine: Engine, radius: number, options?: RegularPolyhedronMeshOptions): ModelMesh { + const edgeSegments = options?.edgeSegments ?? 1; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createRegularPolyhedronData, + ["octahedron", radius, edgeSegments], + options + ); + } + + /** + * Create a regular icosahedron or its spherical subdivision. + * UVs use spherical projection around Y, with the U seam at +X and V from 0 at +Y to 1 at -Y. + * Triangles crossing the U seam may use values above 1. + * @param engine - The engine that owns the mesh + * @param radius - The distance from the origin to each vertex in local units + * @param options - Optional mesh generation settings + * @returns The generated mesh + */ + static createIcosahedron(engine: Engine, radius: number, options?: RegularPolyhedronMeshOptions): ModelMesh { + const edgeSegments = options?.edgeSegments ?? 1; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createRegularPolyhedronData, + ["icosahedron", radius, edgeSegments], + options + ); + } + + /** + * Create a regular dodecahedron or its spherical subdivision. + * UVs use spherical projection around Y, with the U seam at +X and V from 0 at +Y to 1 at -Y. + * Triangles crossing the U seam may use values above 1. + * @param engine - The engine that owns the mesh + * @param radius - The distance from the origin to each vertex in local units + * @param options - Optional mesh generation settings + * @returns The generated mesh + */ + static createDodecahedron(engine: Engine, radius: number, options?: RegularPolyhedronMeshOptions): ModelMesh { + const edgeSegments = options?.edgeSegments ?? 1; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createRegularPolyhedronData, + ["dodecahedron", radius, edgeSegments], + options + ); + } + + /** + * Create a surface of revolution by rotating a radius-height profile around Y. + * No end caps are added automatically. + * Define inner walls and closed ends in the profile when needed. + * U spans the revolution from 0 to 1; V advances uniformly by profile point index from 0 to 1. + * @param engine - The engine that owns the mesh + * @param profile - The profile points in input order, with at least two points; X is radius and Y is height. Repeat the first point to close the profile + * @param options - Optional mesh generation settings + * @returns The generated mesh + */ + static createRevolvedSurface( engine: Engine, - radius: number = 0.5, - tubeRadius: number = 0.1, - radialSegments: number = 30, - tubularSegments: number = 30, - arc: number = 360, - noLongerAccessible: boolean = true + profile: readonly Vector2[], + options?: RevolvedSurfaceMeshOptions ): ModelMesh { - const mesh = new ModelMesh(engine); - PrimitiveMesh._setTorusData( - mesh, - radius, - tubeRadius, - radialSegments, - tubularSegments, - arc, - noLongerAccessible, - false + const segments = options?.segments ?? 12; + const angleRange = options?.angleRange; + const startAngle = angleRange?.x ?? 0; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createRevolvedSurfaceData, + [profile, segments, startAngle, (angleRange?.y ?? 360) - startAngle], + options ); + } - const vertexBuffer = mesh.vertexBufferBindings[0]!.buffer; - engine.resourceManager.addContentRestorer( - new PrimitiveMeshRestorer( - mesh, - new TorusRestoreInfo(radius, tubeRadius, radialSegments, tubularSegments, arc, vertexBuffer, noLongerAccessible) - ) + /** + * Sweep a circular cross-section along a path without end caps. + * U measures normalized path distance; V runs around the generated path frame from 0 to 1. + * @param engine - The engine that owns the mesh + * @param path - The centerline points, resampled at equal distances along the polyline; at least two distinct points are required + * @param radius - The radius of the cross-section in local units + * @param options - Optional mesh generation settings + * @returns The generated mesh + */ + static createTube(engine: Engine, path: readonly Vector3[], radius: number, options?: TubeMeshOptions): ModelMesh { + const pathSegments = options?.pathSegments ?? 64; + const radialSegments = options?.radialSegments ?? 8; + const closedPath = options?.closedPath ?? false; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createTubeData, + [path, radius, pathSegments, radialSegments, closedPath], + options ); - return mesh; } /** - * Create a cone mesh. - * @param engine - Engine - * @param radius - The radius of cap - * @param height - The height of torso - * @param radialSegments - Cone radial segments - * @param heightSegments - Cone height segments - * @param noLongerAccessible - No longer access the vertices of the mesh after creation - * @returns Cone model mesh + * Create a zero-thickness polygon mesh in the XY plane, facing +Z. + * UVs use the local X/Y coordinates directly, without normalization. + * @param engine - The engine that owns the mesh + * @param shapes - A contour, a polygon with holes, or an array of polygons; closing points need not be repeated + * @param options - Optional mesh generation settings + * @returns The triangulated polygon mesh without side walls */ - static createCone( + static createPolygon( engine: Engine, - radius: number = 0.5, - height: number = 2, - radialSegments: number = 20, - heightSegments: number = 1, - noLongerAccessible: boolean = true + shapes: readonly Vector2[] | PolygonShape | readonly PolygonShape[], + options?: PolygonMeshOptions ): ModelMesh { - const mesh = new ModelMesh(engine); - PrimitiveMesh._setConeData(mesh, radius, height, radialSegments, heightSegments, noLongerAccessible, false); - - const vertexBuffer = mesh.vertexBufferBindings[0]!.buffer; - engine.resourceManager.addContentRestorer( - new PrimitiveMeshRestorer( - mesh, - new ConeRestoreInfo(radius, height, radialSegments, heightSegments, vertexBuffer, noLongerAccessible) - ) + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createPolygonData, + [PrimitiveMesh._polygons(shapes)], + options ); - return mesh; } /** - * Create a capsule mesh. - * @param engine - Engine - * @param radius - The radius of the two hemispherical ends - * @param height - The height of the cylindrical part, measured between the centers of the hemispherical ends - * @param radialSegments - Hemispherical end radial segments - * @param heightSegments - Cylindrical part height segments - * @param noLongerAccessible - No longer access the vertices of the mesh after creation - * @returns Capsule model mesh + * Extrude polygon contours along +Z. + * Caps use their local X/Y coordinates as UVs. Wall U measures the original contour length; + * V follows the generated extrusion layers from 0 to 1, including bevel layers. + * @param engine - The engine that owns the mesh + * @param shapes - A contour, a polygon with holes, or an array of polygons; closing points need not be repeated + * @param depth - The total extrusion depth in local units, including both end bevels + * @param options - Optional linear extrusion settings + * @returns The mesh with side walls and both end caps */ - static createCapsule( + static createExtrudedPolygon( engine: Engine, - radius: number = 0.5, - height: number = 2, - radialSegments: number = 6, - heightSegments: number = 1, - noLongerAccessible: boolean = true + shapes: readonly Vector2[] | PolygonShape | readonly PolygonShape[], + depth: number, + options?: LinearExtrudedPolygonMeshOptions + ): ModelMesh; + /** + * Extrude polygon contours along a spatial path. + * @remarks + * Open paths generate both end caps; closed paths join the end cross-sections without caps. + * Caps use cross-section X/Y coordinates as UVs. Wall U measures the contour length; + * V follows the path from 0 to 1. + * @param engine - The engine that owns the mesh + * @param shapes - A contour, a polygon with holes, or an array of polygons; closing points need not be repeated + * @param path - The extrusion path in local coordinates, with at least two distinct points + * @param options - Optional path extrusion settings + * @returns The mesh swept along the path + */ + static createExtrudedPolygon( + engine: Engine, + shapes: readonly Vector2[] | PolygonShape | readonly PolygonShape[], + path: readonly Vector3[], + options?: PathExtrudedPolygonMeshOptions + ): ModelMesh; + static createExtrudedPolygon( + engine: Engine, + shapes: readonly Vector2[] | PolygonShape | readonly PolygonShape[], + depthOrPath: number | readonly Vector3[], + options?: LinearExtrudedPolygonMeshOptions | PathExtrudedPolygonMeshOptions ): ModelMesh { - const mesh = new ModelMesh(engine); - PrimitiveMesh._setCapsuleData(mesh, radius, height, radialSegments, heightSegments, noLongerAccessible, false); - - const vertexBuffer = mesh.vertexBufferBindings[0]!.buffer; - engine.resourceManager.addContentRestorer( - new PrimitiveMeshRestorer( - mesh, - new CapsuleRestoreInfo(radius, height, radialSegments, heightSegments, vertexBuffer, noLongerAccessible) - ) + const extrudedPolygonOptions: (LinearExtrudedPolygonMeshOptions & PathExtrudedPolygonMeshOptions) | undefined = + options; + const depthSegments = extrudedPolygonOptions?.depthSegments ?? 1; + const pathSegments = extrudedPolygonOptions?.pathSegments ?? 1; + const closedPath = extrudedPolygonOptions?.closedPath ?? false; + const bevelWidth = extrudedPolygonOptions?.bevelWidth ?? 0; + const bevelDepth = extrudedPolygonOptions?.bevelDepth ?? bevelWidth; + const contourOffset = extrudedPolygonOptions?.contourOffset ?? 0; + const bevelSegments = extrudedPolygonOptions?.bevelSegments ?? 3; + const path = typeof depthOrPath === "number" ? undefined : depthOrPath; + const depth = typeof depthOrPath === "number" ? depthOrPath : 0; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createExtrudedPolygonData, + [ + PrimitiveMesh._polygons(shapes), + depth, + path ? pathSegments : depthSegments, + path, + path ? closedPath : false, + bevelDepth, + bevelWidth, + contourOffset, + bevelSegments + ], + options + ); + } + + /** + * Create a closed torus knot. At least one of `axisTurns` and `crossSectionTurns` must be nonzero. + * U follows the knot parameter from 0 to 1; V runs around the generated tube cross-section from 0 to 1. + * @param engine - The engine that owns the mesh + * @param radius - The base radius of the torus in local units + * @param tubeRadius - The radius of the tube cross-section in local units + * @param axisTurns - The signed integer revolution count around the torus axis; negative values reverse the winding + * @param crossSectionTurns - The signed integer revolution count around the torus cross-section; negative values reverse the winding + * @param options - Optional mesh generation settings + * @returns The generated mesh + */ + static createTorusKnot( + engine: Engine, + radius: number, + tubeRadius: number, + axisTurns: number, + crossSectionTurns: number, + options?: TorusKnotMeshOptions + ): ModelMesh { + const pathSegments = options?.pathSegments ?? 64; + const radialSegments = options?.radialSegments ?? 8; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createTorusKnotData, + [radius, tubeRadius, pathSegments, radialSegments, axisTurns, crossSectionTurns], + options ); - return mesh; } /** - * @internal + * Create an axis-aligned cuboid with rounded edges and corners. + * @remarks + * UVs preserve the face orientations of {@link PrimitiveMesh.createCuboid} and account for rounded edge length. + * @param engine - The engine that owns the mesh + * @param width - The full size along X in local units + * @param height - The full size along Y in local units + * @param depth - The full size along Z in local units + * @param cornerRadius - The edge and corner radius in local units, clamped to half the smallest dimension + * @param options - Optional mesh generation settings + * @returns The generated mesh */ - static _setSubdivisionSurfaceSphereData( - sphereMesh: ModelMesh, + static createRoundedCuboid( + engine: Engine, + width: number, + height: number, + depth: number, + cornerRadius: number, + options?: RoundedCuboidMeshOptions + ): ModelMesh { + const roundingSegments = options?.roundingSegments ?? 2; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createRoundedCuboidData, + [width, height, depth, cornerRadius, roundingSegments], + options + ); + } + + private static _createPlaneData( + width: number, + depth: number, + widthSegments: number, + depthSegments: number + ): PrimitiveMeshBuilder { + const columns = PrimitiveMesh._getSegmentCount(widthSegments); + const rows = PrimitiveMesh._getSegmentCount(depthSegments); + const data = new PrimitiveMeshBuilder((columns + 1) * (rows + 1), columns * rows * 6); + for (let y = 0; y <= rows; y++) { + for (let x = 0; x <= columns; x++) { + data.addVertex((x / columns - 0.5) * width, 0, (y / rows - 0.5) * depth, 0, 1, 0, x / columns, y / rows); + } + } + for (let y = 0; y < rows; y++) { + for (let x = 0; x < columns; x++) { + const a = y * (columns + 1) + x; + const c = a + columns + 1; + data.addTriangle(a, c, a + 1); + data.addTriangle(a + 1, c, c + 1); + } + } + data.boundsExtent = new Vector3(width / 2, 0, depth / 2); + return data; + } + + private static _createCuboidData( + width: number, + height: number, + depth: number, + widthSegments: number, + heightSegments: number, + depthSegments: number + ): PrimitiveMeshBuilder { + const x = width / 2; + const y = height / 2; + const z = depth / 2; + const sx = PrimitiveMesh._getSegmentCount(widthSegments); + const sy = PrimitiveMesh._getSegmentCount(heightSegments); + const sz = PrimitiveMesh._getSegmentCount(depthSegments); + const data = new PrimitiveMeshBuilder( + 2 * ((sx + 1) * (sy + 1) + (sx + 1) * (sz + 1) + (sy + 1) * (sz + 1)), + 12 * (sx * sy + sx * sz + sy * sz) + ); + // Origins and UV directions preserve the existing cuboid texture orientation + grid( + new Vector3(-x, y, -z), + new Vector3(2 * x, 0, 0), + new Vector3(0, 0, 2 * z), + new Vector3(0, 1, 0), + sx, + sz, + false, + false + ); + grid( + new Vector3(-x, -y, -z), + new Vector3(2 * x, 0, 0), + new Vector3(0, 0, 2 * z), + new Vector3(0, -1, 0), + sx, + sz, + false, + true + ); + grid( + new Vector3(-x, y, -z), + new Vector3(0, 0, 2 * z), + new Vector3(0, -2 * y, 0), + new Vector3(-1, 0, 0), + sz, + sy, + false, + false + ); + grid( + new Vector3(x, y, -z), + new Vector3(0, 0, 2 * z), + new Vector3(0, -2 * y, 0), + new Vector3(1, 0, 0), + sz, + sy, + true, + false + ); + grid( + new Vector3(-x, y, z), + new Vector3(2 * x, 0, 0), + new Vector3(0, -2 * y, 0), + new Vector3(0, 0, 1), + sx, + sy, + false, + false + ); + grid( + new Vector3(-x, y, -z), + new Vector3(2 * x, 0, 0), + new Vector3(0, -2 * y, 0), + new Vector3(0, 0, -1), + sx, + sy, + true, + false + ); + data.boundsExtent = new Vector3(width / 2, height / 2, depth / 2); + return data; + + function grid( + origin: Vector3, + u: Vector3, + v: Vector3, + normal: Vector3, + columns: number, + rows: number, + flipU: boolean, + flipV: boolean + ): void { + const base = data.vertexCount; + const start = data.indexCount; + const crossDot = + (u.y * v.z - u.z * v.y) * normal.x + (u.z * v.x - u.x * v.z) * normal.y + (u.x * v.y - u.y * v.x) * normal.z; + for (let row = 0; row <= rows; row++) { + for (let column = 0; column <= columns; column++) { + const a = column / columns; + const b = row / rows; + data.addVertex( + origin.x + u.x * a + v.x * b, + origin.y + u.y * a + v.y * b, + origin.z + u.z * a + v.z * b, + normal.x, + normal.y, + normal.z, + flipU ? 1 - a : a, + flipV ? 1 - b : b + ); + } + } + for (let row = 0; row < rows; row++) { + for (let column = 0; column < columns; column++) { + const a = base + row * (columns + 1) + column; + const c = a + columns + 1; + if (crossDot > 0) { + data.addTriangle(a, a + 1, c); + data.addTriangle(a + 1, c + 1, c); + } else { + data.addTriangle(a, c, a + 1); + data.addTriangle(a + 1, c, c + 1); + } + } + } + data.addGroup(start); + } + } + + private static _createCylinderData( + radiusTop: number, + radiusBottom: number, + height: number, + radialSegments: number, + heightSegments: number, + includeTopCap: boolean, + includeBottomCap: boolean, + startAngleDegrees: number, + arcDegrees: number, + separateMaterialSlots: boolean = false + ): PrimitiveMeshBuilder { + const radial = PrimitiveMesh._getSegmentCount(radialSegments, 3); + const vertical = PrimitiveMesh._getSegmentCount(heightSegments); + const startAngle = Math.PI + MathUtil.degreeToRadian(startAngleDegrees); + const arc = MathUtil.degreeToRadian(arcDegrees); + const circle = PrimitiveMesh._createArcSamples(radial, startAngle, arc); + const slope = height === 0 ? 0 : (radiusBottom - radiusTop) / height; + const full = Math.abs(arc) === Math.PI * 2; + const capCount = (includeTopCap && radiusTop !== 0 ? 1 : 0) + (includeBottomCap && radiusBottom !== 0 ? 1 : 0); + const sideTriangles = 2 * vertical - (radiusTop === 0 ? 1 : 0) - (radiusBottom === 0 ? 1 : 0); + const data = new PrimitiveMeshBuilder( + (radial + 1) * (vertical + 1) + capCount * (radial + (full ? 1 : 2)), + radial * (sideTriangles + capCount) * 3 + ); + for (let y = 0; y <= vertical; y++) { + const v = y / vertical; + const radius = radiusBottom + (radiusTop - radiusBottom) * v; + for (let x = 0; x <= radial; x++) { + const u = x / radial; + const cos = circle[x * 2]; + const sin = circle[x * 2 + 1]; + data.addVertex(radius * sin, (v - 0.5) * height, radius * cos, sin, slope, cos, u, 1 - v); + } + } + for (let y = 0; y < vertical; y++) { + for (let x = 0; x < radial; x++) { + const a = y * (radial + 1) + x; + const c = a + radial + 1; + if (radiusBottom !== 0 || y !== 0) { + data.addTriangle(a + 1, c, a); + } + if (radiusTop !== 0 || y !== vertical - 1) { + data.addTriangle(a + 1, c + 1, c); + } + } + } + data.addGroup(0); + const capStart = data.indexCount; + // Interleave ungrouped caps to preserve transparent blending order + const interleaveCaps = capCount === 2 && !separateMaterialSlots; + if (includeTopCap) { + cap(radiusTop, 1); + } + if (includeBottomCap) { + cap(radiusBottom, -1); + } + if (interleaveCaps) { + data.addGroup(capStart); + } + data.boundsExtent = new Vector3(Math.max(radiusTop, radiusBottom), height / 2, Math.max(radiusTop, radiusBottom)); + return data; + + function cap(radius: number, sign: number): void { + if (radius === 0) { + return; + } + const start = data.indexCount; + const center = data.addVertex(0, (sign * height) / 2, 0, 0, sign, 0, 0.5, 0.5); + const rowStart = sign > 0 ? vertical * (radial + 1) : 0; + const inverseDiameter = 1 / (2 * radius); + // A partial cap includes both endpoints; a full cap reuses its first rim vertex + const rimCount = full ? radial : radial + 1; + for (let x = 0; x < rimCount; x++) { + const offset = (rowStart + x) * 8; + const positionX = data.vertices[offset]; + const positionZ = data.vertices[offset + 2]; + data.addVertex( + positionX, + (sign * height) / 2, + positionZ, + 0, + sign, + 0, + positionX * inverseDiameter + 0.5, + 0.5 - positionZ * inverseDiameter + ); + } + let indexOffset = interleaveCaps ? capStart + (sign > 0 ? 3 : 0) : start; + const indexStride = interleaveCaps ? 6 : 3; + for (let x = 0; x < radial; x++) { + const current = center + x + 1; + const next = full && x === radial - 1 ? center + 1 : current + 1; + data.indices[indexOffset] = center; + data.indices[indexOffset + 1] = sign > 0 ? current : next; + data.indices[indexOffset + 2] = sign > 0 ? next : current; + indexOffset += indexStride; + } + data.indexCount += radial * 3; + if (!interleaveCaps) { + data.addGroup(start); + } + } + } + + private static _createCapsuleData( + radius: number, + cylinderHeight: number, + radialSegments: number, + capSegments: number, + heightSegments: number + ): PrimitiveMeshBuilder { + const radial = PrimitiveMesh._getSegmentCount(radialSegments, 3); + const caps = PrimitiveMesh._getSegmentCount(capSegments); + const vertical = PrimitiveMesh._getSegmentCount(heightSegments); + const rows = caps * 2 + vertical; + const circle = PrimitiveMesh._createArcSamples(radial, Math.PI); + const capLength = (Math.PI * radius) / 2; + const totalLength = capLength * 2 + cylinderHeight; + const data = new PrimitiveMeshBuilder((radial + 1) * (rows + 1), radial * (rows - 1) * 6); + for (let y = 0; y <= rows; y++) { + let py: number; + let ringRadius: number; + let ny: number; + let distance: number; + if (y <= caps) { + const angle = ((y / caps) * Math.PI) / 2; + ringRadius = radius * Math.sin(angle); + ny = -Math.cos(angle); + py = -cylinderHeight / 2 + radius * ny; + distance = (y / caps) * capLength; + } else if (y <= caps + vertical) { + ringRadius = radius; + ny = 0; + py = -cylinderHeight / 2 + ((y - caps) / vertical) * cylinderHeight; + distance = capLength + ((y - caps) / vertical) * cylinderHeight; + } else { + const angle = (((y - caps - vertical) / caps) * Math.PI) / 2; + ringRadius = radius * Math.cos(angle); + ny = Math.sin(angle); + py = cylinderHeight / 2 + radius * ny; + distance = capLength + cylinderHeight + ((y - caps - vertical) / caps) * capLength; + } + const normalRadius = Math.sqrt(Math.max(0, 1 - ny * ny)); + // Center pole UVs between the other two vertices of each triangle + const offset = y === 0 ? -0.5 / radial : y === rows ? 0.5 / radial : 0; + for (let x = 0; x <= radial; x++) { + const cos = circle[x * 2]; + const sin = circle[x * 2 + 1]; + data.addVertex( + ringRadius * sin, + py, + ringRadius * cos, + sin * normalRadius, + ny, + cos * normalRadius, + x / radial + offset, + totalLength > 0 ? 1 - distance / totalLength : 0 + ); + } + } + for (let y = 0; y < rows; y++) { + for (let x = 0; x < radial; x++) { + const a = y * (radial + 1) + x; + const c = a + radial + 1; + if (y !== 0) { + data.addTriangle(a + 1, c, a); + } + if (y !== rows - 1) { + data.addTriangle(a + 1, c + 1, c); + } + } + } + data.boundsExtent = new Vector3(radius, cylinderHeight / 2 + radius, radius); + return data; + } + + private static _createTorusData( radius: number, - step: number, - noLongerAccessible: boolean, - isRestoreMode: boolean, - restoreVertexBuffer?: Buffer + tubeRadius: number, + radialSegments: number, + ringSegments: number, + arcDegrees: number, + tubeStartAngleDegrees: number, + tubeArcDegrees: number, + startAngleDegrees: number + ): PrimitiveMeshBuilder { + const radial = PrimitiveMesh._getSegmentCount(radialSegments, 3); + const tubular = PrimitiveMesh._getSegmentCount(ringSegments, 1); + const arc = MathUtil.degreeToRadian(arcDegrees); + const tubeStart = MathUtil.degreeToRadian(tubeStartAngleDegrees); + const tubeArc = MathUtil.degreeToRadian(tubeArcDegrees); + const circle = PrimitiveMesh._createArcSamples(tubular, MathUtil.degreeToRadian(startAngleDegrees), arc); + const data = new PrimitiveMeshBuilder((radial + 1) * (tubular + 1), radial * tubular * 6); + for (let y = 0; y <= radial; y++) { + const v = tubeStart + (y / radial) * tubeArc; + const cosV = Math.cos(v); + const nz = Math.sin(v); + for (let x = 0; x <= tubular; x++) { + const cosU = circle[x * 2]; + const sinU = circle[x * 2 + 1]; + const nx = cosV * cosU; + const ny = cosV * sinU; + data.addVertex( + radius * cosU + tubeRadius * nx, + radius * sinU + tubeRadius * ny, + tubeRadius * nz, + nx, + ny, + nz, + x / tubular, + y / radial + ); + } + } + for (let y = 0; y < radial; y++) { + for (let x = 0; x < tubular; x++) { + const a = y * (tubular + 1) + x; + const c = a + tubular + 1; + data.addTriangle(c, a, c + 1); + data.addTriangle(a, a + 1, c + 1); + } + } + data.boundsExtent = new Vector3(radius + tubeRadius, radius + tubeRadius, tubeRadius); + return data; + } + + private static _createCircleData( + radius: number, + segments: number, + startAngle: number, + arcDegrees: number + ): PrimitiveMeshBuilder { + const count = PrimitiveMesh._getSegmentCount(segments, 3); + const start = MathUtil.degreeToRadian(startAngle); + const arc = MathUtil.degreeToRadian(arcDegrees); + const data = new PrimitiveMeshBuilder(count + 2, count * 3); + data.addVertex(0, 0, 0, 0, 0, 1, 0.5, 0.5); + for (let i = 0; i <= count; i++) { + const angle = start + (i / count) * arc; + const x = Math.cos(angle); + const y = Math.sin(angle); + data.addVertex(radius * x, radius * y, 0, 0, 0, 1, (x + 1) / 2, (y + 1) / 2); + if (i > 0) { + data.addTriangle(0, i, i + 1); + } + } + return data; + } + + private static _createRingData( + innerRadius: number, + outerRadius: number, + ringSegments: number, + widthSegments: number, + startAngle: number, + arcDegrees: number + ): PrimitiveMeshBuilder { + const radial = PrimitiveMesh._getSegmentCount(ringSegments, 3); + const width = PrimitiveMesh._getSegmentCount(widthSegments); + const start = MathUtil.degreeToRadian(startAngle); + const arc = MathUtil.degreeToRadian(arcDegrees); + const circle = PrimitiveMesh._createArcSamples(radial, start, arc); + const data = new PrimitiveMeshBuilder((radial + 1) * (width + 1), radial * width * 6); + for (let y = 0; y <= width; y++) { + const radius = innerRadius + ((outerRadius - innerRadius) * y) / width; + for (let x = 0; x <= radial; x++) { + const px = radius * circle[x * 2]; + const py = radius * circle[x * 2 + 1]; + data.addVertex( + px, + py, + 0, + 0, + 0, + 1, + outerRadius !== 0 ? (px / outerRadius + 1) / 2 : 0.5, + outerRadius !== 0 ? (py / outerRadius + 1) / 2 : 0.5 + ); + } + } + for (let y = 0; y < width; y++) { + for (let x = 0; x < radial; x++) { + const a = y * (radial + 1) + x; + const c = a + radial + 1; + data.addTriangle(a, c, a + 1); + data.addTriangle(a + 1, c, c + 1); + } + } + return data; + } + + private static _createRoundedCuboidData( + width: number, + height: number, + depth: number, + cornerRadius: number, + roundingSegments: number + ): PrimitiveMeshBuilder { + const radius = Math.max(0, Math.min(cornerRadius, width / 2, height / 2, depth / 2)); + if (radius === 0) { + return PrimitiveMesh._createCuboidData(width, height, depth, 1, 1, 1); + } + const cornerSegments = PrimitiveMesh._getSegmentCount(roundingSegments); + const count = cornerSegments * 2 + 1; + const data = PrimitiveMesh._createCuboidData(width, height, depth, count, count, count); + const inner = new Vector3(width / 2 - radius, height / 2 - radius, depth / 2 - radius); + const center = new Vector3(); + const delta = new Vector3(); + const components = ["x", "y", "z"] as const; + const uvAxes = { x: ["z", "y"], y: ["x", "z"], z: ["x", "y"] } as const; + for (let i = 0; i < data.vertexCount * 8; i += 8) { + const faceAxis = data.vertices[i + 3] !== 0 ? "x" : data.vertices[i + 4] !== 0 ? "y" : "z"; + for (let axis = 0; axis < 3; axis++) { + const component = components[axis]; + const halfSize = inner[component] + radius; + const gridIndex = Math.round(((data.vertices[i + axis] / halfSize + 1) / 2) * count); + const p = + gridIndex <= cornerSegments + ? -inner[component] - radius * (1 - gridIndex / cornerSegments) + : inner[component] + (radius * (gridIndex - cornerSegments - 1)) / cornerSegments; + center[component] = Math.max(-inner[component], Math.min(inner[component], p)); + delta[component] = p - center[component]; + } + const length = Math.hypot(delta.x, delta.y, delta.z); + for (let axis = 0; axis < 3; axis++) { + const component = components[axis]; + const n = delta[component] / length; + data.vertices[i + axis] = center[component] + n * radius; + data.vertices[i + 3 + axis] = n; + } + for (let uv = 0; uv < 2; uv++) { + const component = uvAxes[faceAxis][uv]; + const angle = Math.atan2(Math.abs(delta[component]), Math.abs(delta[faceAxis])); + const distance = Math.abs(center[component]) + radius * angle; + const surfaceLength = inner[component] * 2 + (Math.PI * radius) / 2; + const direction = Math.sign(data.vertices[i + 6 + uv] - 0.5); + data.vertices[i + 6 + uv] = 0.5 + (direction * distance) / surfaceLength; + } + } + return data; + } + + private static _createRevolvedSurfaceData( + points: readonly Vector2[], + segmentCount: number, + startAngle: number, + arcDegrees: number + ): PrimitiveMeshBuilder { + if (points.length < 2) { + throw new Error("A revolved surface profile needs at least two points."); + } + const count = PrimitiveMesh._getSegmentCount(segmentCount); + const start = MathUtil.degreeToRadian(startAngle); + const arc = MathUtil.degreeToRadian(arcDegrees); + const data = new PrimitiveMeshBuilder((count + 1) * points.length, count * (points.length - 1) * 6); + const normals: Vector3[] = []; + for (let i = 0; i < points.length; i++) { + const previous = points[Math.max(0, i - 1)]; + const current = points[i]; + const next = points[Math.min(points.length - 1, i + 1)]; + const a = PrimitiveMesh._normalizeVector(new Vector3(current.y - previous.y, previous.x - current.x, 0)); + const b = PrimitiveMesh._normalizeVector(new Vector3(next.y - current.y, current.x - next.x, 0)); + normals.push(PrimitiveMesh._normalizeVector(a.add(b))); + } + for (let x = 0; x <= count; x++) { + const angle = start + (x / count) * arc; + const sin = Math.sin(angle); + const cos = Math.cos(angle); + for (let y = 0; y < points.length; y++) { + const point = points[y]; + const normal = normals[y]; + data.addVertex( + point.x * sin, + point.y, + point.x * cos, + normal.x * sin, + normal.y, + normal.x * cos, + x / count, + y / (points.length - 1) + ); + } + } + for (let x = 0; x < count; x++) { + for (let y = 0; y < points.length - 1; y++) { + const a = x * points.length + y; + const b = a + points.length; + if (points[y].x !== 0) { + data.addTriangle(a, b, a + 1); + } + if (points[y + 1].x !== 0) { + data.addTriangle(b, b + 1, a + 1); + } + } + } + return data; + } + + private static _createTubeData( + path: readonly Vector3[], + radius: number, + pathSegments: number, + radialSegments: number, + closedPath: boolean + ): PrimitiveMeshBuilder { + const tangents: Vector3[] = []; + const points = MeshPathUtils.sample(path, PrimitiveMesh._getSegmentCount(pathSegments), closedPath, tangents); + return PrimitiveMesh._createTubeSurfaceData(points, radius, radialSegments, closedPath, tangents); + } + + private static _createTubeSurfaceData( + points: readonly Vector3[], + radius: number, + radialSegments: number, + closedPath: boolean, + fallbackTangents?: readonly Vector3[] + ): PrimitiveMeshBuilder { + const count = points.length - 1; + const radial = PrimitiveMesh._getSegmentCount(radialSegments, 3); + const frames = MeshPathUtils.computeFrames(points, closedPath, fallbackTangents); + const data = new PrimitiveMeshBuilder((count + 1) * (radial + 1), count * radial * 6); + const circle = PrimitiveMesh._createArcSamples(radial); + for (let y = 0; y <= count; y++) { + const point = points[y]; + const normal = frames.normals[y]; + const binormal = frames.binormals[y]; + for (let x = 0; x <= radial; x++) { + const c = circle[x * 2]; + const s = circle[x * 2 + 1]; + const nx = normal.x * c + binormal.x * s; + const ny = normal.y * c + binormal.y * s; + const nz = normal.z * c + binormal.z * s; + data.addVertex( + point.x + radius * nx, + point.y + radius * ny, + point.z + radius * nz, + nx, + ny, + nz, + y / count, + x / radial + ); + } + } + for (let y = 0; y < count; y++) { + for (let x = 0; x < radial; x++) { + const a = y * (radial + 1) + x; + const c = a + radial + 1; + data.addTriangle(a, a + 1, c); + data.addTriangle(a + 1, c + 1, c); + } + } + return data; + } + + private static _createTorusKnotData( + radius: number, + tubeRadius: number, + pathSegments: number, + radialSegments: number, + axisTurns: number, + crossSectionTurns: number + ): PrimitiveMeshBuilder { + if (axisTurns === 0 && crossSectionTurns === 0) { + throw new Error("A torus knot needs at least one nonzero winding."); + } + const count = PrimitiveMesh._getSegmentCount(pathSegments); + const points: Vector3[] = []; + const tangents: Vector3[] = []; + for (let i = 0; i < count; i++) { + const angle = (i / count) * Math.PI * 2; + const u = axisTurns * angle; + const v = crossSectionTurns * angle; + points.push( + new Vector3( + (radius * (2 + Math.cos(v)) * Math.cos(u)) / 2, + (radius * (2 + Math.cos(v)) * Math.sin(u)) / 2, + (radius * Math.sin(v)) / 2 + ) + ); + const radialDerivative = -crossSectionTurns * Math.sin(v); + const angularDerivative = axisTurns * (2 + Math.cos(v)); + tangents.push( + new Vector3( + radialDerivative * Math.cos(u) - angularDerivative * Math.sin(u), + radialDerivative * Math.sin(u) + angularDerivative * Math.cos(u), + crossSectionTurns * Math.cos(v) + ) + ); + } + points.push(points[0]); + tangents.push(tangents[0]); + return PrimitiveMesh._createTubeSurfaceData(points, tubeRadius, radialSegments, true, tangents); + } + + private static _createRegularPolyhedronData( + type: "tetrahedron" | "octahedron" | "icosahedron" | "dodecahedron", + radius: number, + segments: number + ): PrimitiveMeshBuilder { + const [positions, indices] = PrimitiveMesh._regularPolyhedra[type]; + const divisions = PrimitiveMesh._getSegmentCount(segments); + const vertexCount = indices.length * divisions * divisions; + const data = new PrimitiveMeshBuilder(vertexCount, vertexCount); + const vertices = new Float64Array(((divisions + 1) * (divisions + 2) * 8) / 2); + const left = new Vector3(); + const right = new Vector3(); + const point = new Vector3(); + for (let face = 0; face < indices.length; face += 3) { + let offset = 0; + for (let i = 0; i <= divisions; i++) { + left.copyFromArray(positions, indices[face] * 3); + right.copyFromArray(positions, indices[face + 1] * 3); + point.copyFromArray(positions, indices[face + 2] * 3); + Vector3.lerp(left, point, i / divisions, left); + Vector3.lerp(right, point, i / divisions, right); + for (let j = 0; j <= divisions - i; j++) { + Vector3.lerp(left, right, divisions === i ? 0 : j / (divisions - i), point); + PrimitiveMesh._normalizeVector(point); + vertices[offset] = point.x * radius; + vertices[offset + 1] = point.y * radius; + vertices[offset + 2] = point.z * radius; + point.copyToArray(vertices, offset + 3); + vertices[offset + 6] = Math.atan2(point.z, -point.x) / (2 * Math.PI) + 0.5; + vertices[offset + 7] = Math.acos(Math.max(-1, Math.min(1, point.y))) / Math.PI; + offset += 8; + } + } + let row = 0; + for (let i = 0; i < divisions; i++) { + const next = row + divisions - i + 1; + for (let j = 0; j < divisions - i; j++) { + PrimitiveMesh._addPolyhedronFace( + data, + vertices, + (row + j + 1) * 8, + (next + j) * 8, + (row + j) * 8, + divisions === 1 + ); + if (j < divisions - i - 1) { + PrimitiveMesh._addPolyhedronFace( + data, + vertices, + (row + j + 1) * 8, + (next + j + 1) * 8, + (next + j) * 8, + divisions === 1 + ); + } + } + row = next; + } + } + return data; + } + + private static _addPolyhedronFace( + data: PrimitiveMeshBuilder, + vertices: Float64Array, + a: number, + b: number, + c: number, + flat: boolean ): void { - // Max step is limited to 6. Because 7 step will generate a single mesh with over 98306 vertices - step = MathUtil.clamp(Math.floor(step), 1, 6); + let uA = vertices[a + 6]; + let uB = vertices[b + 6]; + let uC = vertices[c + 6]; + const poleA = Math.abs(vertices[a + 4]) > 1 - 1e-10; + const poleB = Math.abs(vertices[b + 4]) > 1 - 1e-10; + const poleC = Math.abs(vertices[c + 4]) > 1 - 1e-10; + if (poleA) { + uA = uB; + } + if (poleB) { + uB = uC; + } + if (poleC) { + uC = uA; + } + const minU = Math.min(uA, uB, uC); + const maxU = Math.max(uA, uB, uC); + const middleU = uA === minU ? Math.min(uB, uC) : uB === minU ? Math.min(uA, uC) : Math.min(uA, uB); + // Choose the shortest U interval before averaging pole coordinates + let gap = 1 + minU - maxU; + let startU = minU; + if (middleU - minU > gap) { + gap = middleU - minU; + startU = middleU; + } + if (maxU - middleU > gap) { + startU = maxU; + } + if (uA < startU) { + uA += 1; + } + if (uB < startU) { + uB += 1; + } + if (uC < startU) { + uC += 1; + } + if (poleA) { + uA = (uB + uC) / 2; + } + if (poleB) { + uB = (uC + uA) / 2; + } + if (poleC) { + uC = (uA + uB) / 2; + } + let nx = 0; + let ny = 0; + let nz = 0; + if (flat) { + const abX = vertices[b] - vertices[a]; + const abY = vertices[b + 1] - vertices[a + 1]; + const abZ = vertices[b + 2] - vertices[a + 2]; + const acX = vertices[c] - vertices[a]; + const acY = vertices[c + 1] - vertices[a + 1]; + const acZ = vertices[c + 2] - vertices[a + 2]; + nx = abY * acZ - abZ * acY; + ny = abZ * acX - abX * acZ; + nz = abX * acY - abY * acX; + const length = Math.hypot(nx, ny, nz); + const inverse = length > 0 ? 1 / length : 0; + nx *= inverse; + ny *= inverse; + nz *= inverse; + } + const start = data.vertexCount; + for (let i = 0; i < 3; i++) { + const offset = i === 0 ? a : i === 1 ? b : c; + data.addVertex( + vertices[offset], + vertices[offset + 1], + vertices[offset + 2], + flat ? nx : vertices[offset + 3], + flat ? ny : vertices[offset + 4], + flat ? nz : vertices[offset + 5], + i === 0 ? uA : i === 1 ? uB : uC, + vertices[offset + 7] + ); + } + data.addTriangle(start, start + 1, start + 2); + } + + private static _createPolygonData(shapes: readonly PolygonShape[]): PrimitiveMeshBuilder { + const data = new PrimitiveMeshBuilder(); + for (const polygon of shapes) { + const contours = PolygonUtils.prepareContours(polygon); + const { points, indices } = PolygonUtils.triangulateContours(contours); + const base = data.vertexCount; + const start = data.indexCount; + for (const point of points) { + data.addVertex(point.x, point.y, 0, 0, 0, 1, point.x, point.y); + } + for (const index of indices) { + data.addIndex(base + index); + } + data.addGroup(start); + } + return data; + } + + private static _createExtrudedPolygonData( + shapes: readonly PolygonShape[], + depth: number, + stepCount: number, + pathInput: readonly Vector3[] | undefined, + closedPath: boolean, + bevelDepth: number, + bevelWidth: number, + contourOffset: number, + bevelSegmentCount: number + ): PrimitiveMeshBuilder { + const data = new PrimitiveMeshBuilder(); + const steps = PrimitiveMesh._getSegmentCount(stepCount, closedPath ? 3 : 1); + const tangents: Vector3[] = []; + const path = pathInput ? MeshPathUtils.sample(pathInput, steps, closedPath, tangents) : undefined; + const frames = path ? MeshPathUtils.computeFrames(path, closedPath, tangents) : undefined; + const bevelEnabled = !path && bevelWidth > 0; + const bevelSegments = bevelEnabled ? PrimitiveMesh._getSegmentCount(bevelSegmentCount) : 0; + const thickness = bevelEnabled ? Math.min(bevelDepth, depth / 2) : 0; + const size = bevelEnabled ? bevelWidth : 0; + const offset = path ? 0 : contourOffset; + const layers: { z: number; inset: number }[] = []; + const uvA = new Vector2(); + const uvB = new Vector2(); + const uvC = new Vector2(); + const uvD = new Vector2(); + for (let i = 0; i < bevelSegments; i++) { + const angle = ((i / bevelSegments) * Math.PI) / 2; + layers.push({ z: thickness * (1 - Math.cos(angle)), inset: size * (1 - Math.sin(angle)) }); + } + for (let i = 0; i <= steps; i++) { + layers.push({ z: thickness + ((depth - thickness * 2) * i) / steps, inset: 0 }); + } + for (let i = 1; i <= bevelSegments; i++) { + const angle = ((i / bevelSegments) * Math.PI) / 2; + layers.push({ + z: depth - thickness + thickness * Math.sin(angle), + inset: size * (1 - Math.cos(angle)) + }); + } + + for (const polygon of shapes) { + const contours = PolygonUtils.prepareContours(polygon); + const offsetContours = new Array(layers.length); + for (let i = 0; i < layers.length; i++) { + offsetContours[i] = + i > 0 && layers[i].inset === layers[i - 1].inset + ? offsetContours[i - 1] + : contours.map((contour) => PrimitiveMesh._insetContour(contour, layers[i].inset - offset)); + } + const rings = offsetContours.map((contour, layer) => { + const { z } = layers[layer]; + const center = path?.[layer]; + const normal = frames?.normals[layer]; + const binormal = frames?.binormals[layer]; + return contour.map((points) => + points.map((point) => + center + ? new Vector3( + center.x + normal!.x * point.x + binormal!.x * point.y, + center.y + normal!.y * point.x + binormal!.y * point.y, + center.z + normal!.z * point.x + binormal!.z * point.y + ) + : new Vector3(point.x, point.y, z) + ) + ); + }); + if (!closedPath) { + const capStart = data.indexCount; + cap(0, false); + cap(layers.length - 1, true); + data.addGroup(capStart); + } + const sideStart = data.indexCount; + for (let contour = 0; contour < contours.length; contour++) { + const original = contours[contour]; + const distances = [0]; + for (let point = 0; point < original.length; point++) { + const next = original[(point + 1) % original.length]; + distances.push(distances[point] + Math.hypot(next.x - original[point].x, next.y - original[point].y)); + } + for (let layer = 0; layer < layers.length - 1; layer++) { + for (let point = 0; point < original.length; point++) { + const next = (point + 1) % original.length; + const a = rings[layer][contour][point]; + const b = rings[layer][contour][next]; + const c = rings[layer + 1][contour][point]; + const d = rings[layer + 1][contour][next]; + uvA.set(distances[point], layer / (layers.length - 1)); + uvB.set(distances[point + 1], uvA.y); + uvC.set(uvA.x, (layer + 1) / (layers.length - 1)); + uvD.set(uvB.x, uvC.y); + data.addFace(a, b, c, uvA, uvB, uvC); + data.addFace(b, d, c, uvB, uvD, uvC); + } + } + } + data.addGroup(sideStart); + + function cap(layer: number, top: boolean): void { + const { points, indices } = PolygonUtils.triangulateContours(offsetContours[layer]); + const positions = rings[layer].flat(); + for (let i = 0; i < indices.length; i += 3) { + const a = indices[i]; + const b = indices[i + (top ? 1 : 2)]; + const c = indices[i + (top ? 2 : 1)]; + data.addFace(positions[a], positions[b], positions[c], points[a], points[b], points[c]); + } + } + } + return data; + } - const positions = new Float32Array(3 * (6 * Math.pow(4, step) + 2)); - const cells = new Float32Array(24 * Math.pow(4, step)); - PrimitiveMesh._subdiveCatmullClark(step, positions, cells); + private static _insetContour(contour: Vector2[], distance: number): Vector2[] { + if (distance === 0) { + return contour; + } + return contour.map((point, index) => { + const previous = contour[(index + contour.length - 1) % contour.length]; + const next = contour[(index + 1) % contour.length]; + const ax = point.x - previous.x; + const ay = point.y - previous.y; + const bx = next.x - point.x; + const by = next.y - point.y; + const al = Math.hypot(ax, ay); + const bl = Math.hypot(bx, by); + const nx = -ay / al - by / bl; + const ny = ax / al + bx / bl; + const denominator = nx * (-by / bl) + ny * (bx / bl); + const scale = Math.abs(denominator) > 1e-10 ? distance / denominator : 0; + return new Vector2(point.x + nx * scale, point.y + ny * scale); + }); + } + + private static _createSphereData( + radius: number, + subdivisionLevel: number, + horizontalStart: number, + horizontalEnd: number, + verticalStart: number, + verticalEnd: number + ): PrimitiveMeshBuilder { + const horizontalArc = Math.min(360, horizontalEnd - horizontalStart); + verticalStart = Math.max(0, verticalStart); + verticalEnd = Math.min(180, verticalEnd); + if (horizontalArc < 360 || verticalStart > 0 || verticalEnd < 180) { + const surface = PrimitiveMesh._createSphereSurfaceData(1, subdivisionLevel); + return PrimitiveMesh._createSphereSectionData( + surface, + radius, + horizontalStart, + horizontalArc, + verticalStart, + verticalEnd + ); + } + + const data = PrimitiveMesh._createSphereSurfaceData(radius, subdivisionLevel); + if (horizontalStart !== 0) { + const angle = MathUtil.degreeToRadian(horizontalStart); + const cos = Math.cos(angle); + const sin = Math.sin(angle); + const vertices = data.vertices; + for (let i = 0; i < vertices.length; i += 8) { + const x = vertices[i]; + const z = vertices[i + 2]; + const nx = vertices[i + 3]; + const nz = vertices[i + 5]; + vertices[i] = x * cos + z * sin; + vertices[i + 2] = -x * sin + z * cos; + vertices[i + 3] = nx * cos + nz * sin; + vertices[i + 5] = -nx * sin + nz * cos; + } + } + return data; + } + + private static _createSphereSectionData( + surface: PrimitiveMeshBuilder, + radius: number, + horizontalStart: number, + horizontalArc: number, + verticalStart: number, + verticalEnd: number + ): PrimitiveMeshBuilder { + const data = new PrimitiveMeshBuilder(surface.vertexCount, surface.indexCount); + if (horizontalArc <= 0 || verticalEnd <= verticalStart) { + return data; + } + const vertices = surface.vertices; + const indices = surface.indices; + const horizontalArcRadians = MathUtil.degreeToRadian(horizontalArc); + const verticalStartRadians = MathUtil.degreeToRadian(verticalStart); + const verticalArcRadians = MathUtil.degreeToRadian(verticalEnd - verticalStart); + const startAngle = MathUtil.degreeToRadian(horizontalStart); + const cos = Math.cos(startAngle); + const sin = Math.sin(startAngle); + const fullTurn = horizontalArc === 360; + const segmentCount = fullTurn ? 1 : Math.ceil(horizontalArc / 180); + const boundaries: { start: Vector3; end: Vector3 }[] = []; + for (let i = 0; i < segmentCount; i++) { + const start = (horizontalArcRadians * i) / segmentCount; + const end = (horizontalArcRadians * (i + 1)) / segmentCount; + boundaries.push({ + start: new Vector3(Math.sin(start), 0, Math.cos(start)), + end: new Vector3(-Math.sin(end), 0, -Math.cos(end)) + }); + } + const topNormal = new Vector3(0, -1, 0); + const bottomNormal = new Vector3(0, 1, 0); + const topOffset = -Math.cos(verticalStartRadians); + const bottomOffset = Math.cos(MathUtil.degreeToRadian(verticalEnd)); + const vertexMap = new Map(); + const trianglePoints = [new Vector3(), new Vector3(), new Vector3()]; + const verticalPoints: Vector3[] = []; + const clippedPoints: Vector3[] = []; + const polygonPoints: Vector3[] = []; + const points = new Array(3); + const uvs = new Float64Array(6); + const poles = new Array(3); + const ab = new Vector3(); + const ac = new Vector3(); + for (let i = 0; i < indices.length; i += 3) { + let triangle = trianglePoints; + let triangleCount = 3; + for (let corner = 0; corner < 3; corner++) { + const offset = indices[i + corner] * 8; + PrimitiveMesh._normalizeVector( + triangle[corner].set(vertices[offset], vertices[offset + 1], vertices[offset + 2]) + ); + } + if (verticalStart > 0) { + triangleCount = PrimitiveMesh._clipSpherePolygon(triangle, triangleCount, topNormal, topOffset, verticalPoints); + triangle = verticalPoints; + } + if (verticalEnd < 180) { + const output = triangle === trianglePoints ? verticalPoints : trianglePoints; + triangleCount = PrimitiveMesh._clipSpherePolygon(triangle, triangleCount, bottomNormal, bottomOffset, output); + triangle = output; + } + for (const boundary of boundaries) { + let polygon = triangle; + let polygonCount = triangleCount; + if (!fullTurn) { + polygonCount = PrimitiveMesh._clipSpherePolygon(polygon, polygonCount, boundary.start, 0, clippedPoints); + polygonCount = PrimitiveMesh._clipSpherePolygon(clippedPoints, polygonCount, boundary.end, 0, polygonPoints); + polygon = polygonPoints; + } + for (let corner = 1; corner + 1 < polygonCount; corner++) { + points[0] = polygon[0]; + points[1] = polygon[corner]; + points[2] = polygon[corner + 1]; + Vector3.subtract(points[1], points[0], ab); + Vector3.subtract(points[2], points[0], ac); + Vector3.cross(ab, ac, ab); + if (ab.length() < 1e-12) { + continue; + } + let minU = Infinity; + let maxU = -Infinity; + let nonPoleCount = 0; + for (let j = 0; j < 3; j++) { + const point = points[j]; + let angle = Math.atan2(point.z, -point.x); + angle = angle < -1e-10 ? angle + Math.PI * 2 : Math.max(0, angle); + const u = MathUtil.clamp(angle / horizontalArcRadians, 0, 1); + uvs[j * 2] = u; + uvs[j * 2 + 1] = MathUtil.clamp( + (Math.acos(MathUtil.clamp(point.y, -1, 1)) - verticalStartRadians) / verticalArcRadians, + 0, + 1 + ); + poles[j] = Math.hypot(point.x, point.z) <= 1e-10; + if (!poles[j]) { + minU = Math.min(minU, u); + maxU = Math.max(maxU, u); + nonPoleCount++; + } + } + let sumU = 0; + for (let j = 0; j < 3; j++) { + if (!poles[j]) { + if (fullTurn && maxU - minU > 0.5 && uvs[j * 2] < 0.5) { + uvs[j * 2] += 1; + } + sumU += uvs[j * 2]; + } + } + for (let j = 0; j < 3; j++) { + const point = points[j]; + const u = poles[j] ? sumU / nonPoleCount : uvs[j * 2]; + const v = uvs[j * 2 + 1]; + const key = `${Math.round(point.x * 1e10)},${Math.round(point.y * 1e10)},${Math.round(point.z * 1e10)},${Math.round(u * 1e10)},${Math.round(v * 1e10)}`; + let index = vertexMap.get(key); + if (index === undefined) { + const nx = point.x * cos + point.z * sin; + const nz = -point.x * sin + point.z * cos; + index = data.addVertex(radius * nx, radius * point.y, radius * nz, nx, point.y, nz, u, v); + vertexMap.set(key, index); + } + data.addIndex(index); + } + } + } + } + data.boundsExtent = new Vector3(radius, radius, radius); + return data; + } + + private static _clipSpherePolygon( + polygon: readonly Vector3[], + count: number, + normal: Vector3, + offset: number, + out: Vector3[] + ): number { + if (count === 0) { + return 0; + } + let resultCount = 0; + let previous = polygon[count - 1]; + let previousDistance = Vector3.dot(previous, normal) - offset; + for (let i = 0; i < count; i++) { + const current = polygon[i]; + const distance = Vector3.dot(current, normal) - offset; + const inside = distance >= -1e-9; + const previousInside = previousDistance >= -1e-9; + if (inside !== previousInside) { + const point = (out[resultCount++] ??= new Vector3()); + const t = previousDistance / (previousDistance - distance); + if (t < 1e-10) { + point.copyFrom(previous); + } else if (t > 1 - 1e-10) { + point.copyFrom(current); + } else { + Vector3.lerp(previous, current, t, point); + // Preserve latitude boundaries when projecting the intersection back onto the sphere + const length = Math.hypot(point.x, point.z); + const scale = length > 0 ? Math.sqrt(Math.max(0, 1 - point.y * point.y)) / length : 0; + point.x *= scale; + point.z *= scale; + } + } + if (inside) { + (out[resultCount++] ??= new Vector3()).copyFrom(current); + } + previous = current; + previousDistance = distance; + } + return resultCount; + } + + private static _createSphereSurfaceData(radius: number, subdivisionLevel: number): PrimitiveMeshBuilder { + // Level 7 exceeds the 16-bit vertex index range + const level = MathUtil.clamp(Math.floor(subdivisionLevel), 1, 6); + + const { positions, quads: cells } = SubdivisionUtils.subdivideQuads( + PrimitiveMesh._sphereSeedPositions, + PrimitiveMesh._sphereSeedCells, + level + ); const positionCount = positions.length / 3; const cellsCount = cells.length / 4; - const poleOffset = positionCount + Math.pow(2, step + 1) - 1; - // 16 extra vertices for pole uv - // 2 vertices at each pole are idle + const poleOffset = positionCount + Math.pow(2, level + 1) - 1; + // Reserve pole duplicates so each triangle can use a local U coordinate const vertexCount = poleOffset + 16; const vertices = new Float32Array(vertexCount * 8); - const indices = PrimitiveMesh._generateIndices(sphereMesh.engine, positionCount, cellsCount * 6); + const indices = new Uint16Array(cellsCount * 6); let seamCount = 0; const seamVertices = >{}; - // Get normals, uvs, and scale to radius for (let i = 0; i < positionCount; i++) { let offset = 3 * i; @@ -353,21 +1947,19 @@ export class PrimitiveMesh { vertices[offset + 6] = (Math.PI - Math.atan2(z, x)) / (2 * Math.PI); vertices[offset + 7] = Math.acos(y) / Math.PI; + // Duplicate the seam so adjacent triangles can use U = 0 and U = 1 if (vertices[offset + 6] === 0) { - // Generate seam vertex const seamOffset = 8 * (positionCount + seamCount++); vertices.set(vertices.subarray(offset, offset + 8), seamOffset); vertices[seamOffset + 6] = 1.0; - // Cache seam vertex seamVertices[offset / 8] = seamOffset / 8; } } - // Get indices let offset = 0; - this._spherePoleIdx = 0; + let poleIndex = 0; for (let i = 0; i < cellsCount; i++) { const idx = 4 * i; @@ -376,1147 +1968,184 @@ export class PrimitiveMesh { let indexC = cells[idx + 2]; let indexD = cells[idx + 3]; - // Handle seam by replacing vertex index to seam vertex index if necessary const floatIndexA = 8 * indexA; const floatIndexB = 8 * indexB; const floatIndexC = 8 * indexC; const floatIndexD = 8 * indexD; - // If center Z is negative + // Use the U = 1 copies on the negative-Z side of the seam if (vertices[floatIndexA + 2] + vertices[floatIndexB + 2] + vertices[floatIndexC + 2] < 0) { - vertices[floatIndexA + 6] === 0 && (indexA = seamVertices[indexA]); - vertices[floatIndexB + 6] === 0 && (indexB = seamVertices[indexB]); - vertices[floatIndexC + 6] === 0 && (indexC = seamVertices[indexC]); - vertices[floatIndexD + 6] === 0 && (indexD = seamVertices[indexD]); + if (vertices[floatIndexA + 6] === 0) { + indexA = seamVertices[indexA]; + } + if (vertices[floatIndexB + 6] === 0) { + indexB = seamVertices[indexB]; + } + if (vertices[floatIndexC + 6] === 0) { + indexC = seamVertices[indexC]; + } + if (vertices[floatIndexD + 6] === 0) { + indexD = seamVertices[indexD]; + } } indices[offset] = indexA; indices[offset + 1] = indexB; indices[offset + 2] = indexC; - this._generateAndReplacePoleUV(indices, vertices, offset, poleOffset); + poleIndex = PrimitiveMesh._replacePoleUV(indices, vertices, offset, poleOffset, poleIndex); indices[offset + 3] = indexA; indices[offset + 4] = indexC; indices[offset + 5] = indexD; - this._generateAndReplacePoleUV(indices, vertices, offset + 3, poleOffset); + poleIndex = PrimitiveMesh._replacePoleUV(indices, vertices, offset + 3, poleOffset, poleIndex); offset += 6; } - if (!isRestoreMode) { - const { bounds } = sphereMesh; - bounds.min.set(-radius, -radius, -radius); - bounds.max.set(radius, radius, radius); - } - PrimitiveMesh._initialize(sphereMesh, vertices, indices, noLongerAccessible, isRestoreMode, restoreVertexBuffer); + const data = new PrimitiveMeshBuilder(); + data.setData(vertices, indices); + data.boundsExtent = new Vector3(radius, radius, radius); + return data; } - /** - * @internal - */ - static _setSphereData( - sphereMesh: ModelMesh, - radius: number, - segments: number, - noLongerAccessible: boolean, - isRestoreMode: boolean, - restoreVertexBuffer?: Buffer - ): void { - segments = Math.max(2, Math.floor(segments)); - - const count = segments + 1; - const vertexCount = count * count; - const rectangleCount = segments * segments; - const indices = PrimitiveMesh._generateIndices(sphereMesh.engine, vertexCount, rectangleCount * 6); - const thetaRange = Math.PI; - const alphaRange = thetaRange * 2; - const countReciprocal = 1.0 / count; - const segmentsReciprocal = 1.0 / segments; - - const vertexFloatCount = 8; - const vertices = new Float32Array(vertexCount * vertexFloatCount); - - for (let i = 0; i < vertexCount; ++i) { - const x = i % count; - const y = (i * countReciprocal) | 0; - const u = x * segmentsReciprocal; - const v = y * segmentsReciprocal; - const alphaDelta = u * alphaRange; - const thetaDelta = v * thetaRange; - const sinTheta = Math.sin(thetaDelta); - - const posX = -radius * Math.cos(alphaDelta) * sinTheta; - const posY = radius * Math.cos(thetaDelta); - const posZ = radius * Math.sin(alphaDelta) * sinTheta; - - let offset = i * vertexFloatCount; - // Position - vertices[offset++] = posX; - vertices[offset++] = posY; - vertices[offset++] = posZ; - // Normal - vertices[offset++] = posX; - vertices[offset++] = posY; - vertices[offset++] = posZ; - // TexCoord - vertices[offset++] = u; - vertices[offset++] = v; - } - - let offset = 0; - for (let i = 0; i < rectangleCount; ++i) { - const x = i % segments; - const y = (i * segmentsReciprocal) | 0; - - const a = y * count + x; - const b = a + 1; - const c = a + count; - const d = c + 1; - - indices[offset++] = b; - indices[offset++] = a; - indices[offset++] = d; - indices[offset++] = a; - indices[offset++] = c; - indices[offset++] = d; - } - - if (!isRestoreMode) { - const { bounds } = sphereMesh; - bounds.min.set(-radius, -radius, -radius); - bounds.max.set(radius, radius, radius); - } - - PrimitiveMesh._initialize(sphereMesh, vertices, indices, noLongerAccessible, isRestoreMode, restoreVertexBuffer); - } - - /** - * @internal - */ - static _subdiveCatmullClark(step: number, positions: Float32Array, cells: Float32Array) { - const edges = new Map(); - const faces = new Array(); - - positions.set(PrimitiveMesh._sphereSeedPositions); - cells.set(PrimitiveMesh._sphereSeedCells); - - for (let i = 0; i < step; i++) { - const cellCount = 6 * Math.pow(4, i); - const positionCount = 4 * cellCount + 2; - - edges.clear(); - faces.length = 0; - - // Get cell face's facePoint - for (let j = 0; j < cellCount; j++) { - const face = (faces[j] = { - facePoint: new Vector3(), - adjacentEdges: new Array(4) - }); - - // Get cell's edgePoint - for (let k = 0; k < 4; k++) { - const offset = 3 * cells[4 * j + k]; - face.facePoint.x += 0.25 * positions[offset]; - face.facePoint.y += 0.25 * positions[offset + 1]; - face.facePoint.z += 0.25 * positions[offset + 2]; - } - - // Get cell edges - for (let k = 0; k < 4; k++) { - const vertexIdxA = cells[4 * j + k]; - const vertexIdxB = cells[4 * j + ((k + 1) % 4)]; - - const edgeIdxKey = Math.min(vertexIdxA, vertexIdxB) * positionCount + Math.max(vertexIdxA, vertexIdxB); - - if (!edges.has(edgeIdxKey)) { - const edge: IEdge = { - edgePoint: new Vector3(), - edgePointIndex: undefined - }; - - const offsetA = 3 * vertexIdxA; - const offsetB = 3 * vertexIdxB; - - edge.edgePoint.set( - 0.25 * (positions[offsetA] + positions[offsetB]), - 0.25 * (positions[offsetA + 1] + positions[offsetB + 1]), - 0.25 * (positions[offsetA + 2] + positions[offsetB + 2]) - ); - - edges.set(edgeIdxKey, edge); - } - const edge = edges.get(edgeIdxKey)!; - - face.adjacentEdges[k] = edge; - - const edgePoint = edge.edgePoint; - const facePoint = face.facePoint; - - edgePoint.x += 0.25 * facePoint.x; - edgePoint.y += 0.25 * facePoint.y; - edgePoint.z += 0.25 * facePoint.z; - } - } - - const prePointCount = cellCount + 2; - const edgePointOffset = prePointCount + cellCount; - - let pointIdx = 0; - this._sphereEdgeIdx = 0; - const preCells = cells.slice(0, 4 * cellCount); - - // Get New positions, which consists of updated positions of existing points, face points and edge points - for (let j = 0; j < cellCount; j++) { - // Add face point to new positions - const face = faces[j]; - face.facePoint.copyToArray(positions, 3 * (prePointCount + j)); - - // Get the face point index - const ic = prePointCount + j; - - let id!: number, ib!: number, temp!: number; - - // ia -- id -- ia - // | | | - // ib -- ic -- ib - // | | | - // ia -- id -- ia - for (let k = 0; k < 4; k++) { - // Get the updated existing point index - const ia = preCells[pointIdx++]; - - // ib and id share four edge points in one cell - switch (k) { - case 0: { - const edgeB = face.adjacentEdges[k % 4]; - const edgeD = face.adjacentEdges[(k + 3) % 4]; - ib = this._calculateEdgeIndex(positions, edgeB, edgePointOffset); - id = this._calculateEdgeIndex(positions, edgeD, edgePointOffset); - temp = id; - break; - } - case 1: - case 2: { - const edgeB = face.adjacentEdges[k % 4]; - id = ib; - ib = this._calculateEdgeIndex(positions, edgeB, edgePointOffset); - break; - } - case 3: { - id = ib; - ib = temp; - break; - } - } - - const idx = 4 * (4 * j + k); - cells[idx] = ia; - cells[idx + 1] = ib; - cells[idx + 2] = ic; - cells[idx + 3] = id; - } - } - } - } - - /** - * Duplicate vertices at the poles and adjust their UV coordinates. - */ - private static _generateAndReplacePoleUV( + private static _replacePoleUV( indices: Uint16Array | Uint32Array, vertices: Float32Array, idx: number, - poleOffset: number - ) { + poleOffset: number, + poleIndex: number + ): number { const v = vertices[8 * indices[idx] + 7]; if (v === 0 || v === 1) { const offset = 8 * indices[idx]; - const addedOffset = 8 * (poleOffset + this._spherePoleIdx); + const addedOffset = 8 * (poleOffset + poleIndex); vertices.set(vertices.subarray(offset, offset + 8), addedOffset); vertices[addedOffset + 6] = 0.5 * (vertices[offset + 6] + vertices[8 * indices[idx + 1] + 6] + vertices[8 * indices[idx + 2] + 6] - 0.5); - indices[idx] = poleOffset + this._spherePoleIdx++; + indices[idx] = poleOffset + poleIndex++; } + return poleIndex; } - /** - * Get edge point index for subdivision surface sphere. - */ - private static _calculateEdgeIndex(positions: Float32Array, edge: IEdge, offset: number): number { - if (edge.edgePointIndex !== undefined) { - return edge.edgePointIndex; - } else { - edge.edgePoint.copyToArray(positions, 3 * (offset + PrimitiveMesh._sphereEdgeIdx)); - const index = offset + PrimitiveMesh._sphereEdgeIdx++; - edge.edgePointIndex = index; - return index; + private static _createMesh( + engine: Engine, + generate: (...args: T) => PrimitiveMeshBuilder, + args: [...T], + options?: { keepMeshData?: boolean; separateMaterialSlots?: boolean } + ): ModelMesh { + const keepMeshData = options?.keepMeshData ?? false; + for (let i = 0; i < args.length; i++) { + args[i] = PrimitiveMesh._copy(args[i]); } - } - - /** - * @internal - */ - static _setCuboidData( - cuboidMesh: ModelMesh, - width: number, - height: number, - depth: number, - noLongerAccessible: boolean, - isRestoreMode: boolean, - restoreVertexBuffer?: Buffer - ): void { - const halfWidth = width / 2; - const halfHeight = height / 2; - const halfDepth = depth / 2; - - const vertexFloatCount = 8; - const vertices = new Float32Array(24 * vertexFloatCount); - - // Up - (vertices[0] = -halfWidth), (vertices[1] = halfHeight), (vertices[2] = -halfDepth); - (vertices[6] = 0), (vertices[7] = 0); - (vertices[8] = halfWidth), (vertices[9] = halfHeight), (vertices[10] = -halfDepth); - (vertices[14] = 1), (vertices[15] = 0); - (vertices[16] = halfWidth), (vertices[17] = halfHeight), (vertices[18] = halfDepth); - (vertices[22] = 1), (vertices[23] = 1); - (vertices[24] = -halfWidth), (vertices[25] = halfHeight), (vertices[26] = halfDepth); - (vertices[30] = 0), (vertices[31] = 1); - for (let i = 0; i < 4; i++) { - let normalOffset = vertexFloatCount * i + 3; - (vertices[normalOffset++] = 0), (vertices[normalOffset++] = 1), (vertices[normalOffset++] = 0); - } - - // Down - (vertices[32] = -halfWidth), (vertices[33] = -halfHeight), (vertices[34] = -halfDepth); - (vertices[38] = 0), (vertices[39] = 1); - (vertices[40] = halfWidth), (vertices[41] = -halfHeight), (vertices[42] = -halfDepth); - (vertices[46] = 1), (vertices[47] = 1); - (vertices[48] = halfWidth), (vertices[49] = -halfHeight), (vertices[50] = halfDepth); - (vertices[54] = 1), (vertices[55] = 0); - (vertices[56] = -halfWidth), (vertices[57] = -halfHeight), (vertices[58] = halfDepth); - (vertices[62] = 0), (vertices[63] = 0); - for (let i = 0; i < 4; i++) { - let normalOffset = vertexFloatCount * i + 35; - (vertices[normalOffset++] = 0), (vertices[normalOffset++] = -1), (vertices[normalOffset++] = 0); - } - - // Left - (vertices[64] = -halfWidth), (vertices[65] = halfHeight), (vertices[66] = -halfDepth); - (vertices[70] = 0), (vertices[71] = 0); - (vertices[72] = -halfWidth), (vertices[73] = halfHeight), (vertices[74] = halfDepth); - (vertices[78] = 1), (vertices[79] = 0); - (vertices[80] = -halfWidth), (vertices[81] = -halfHeight), (vertices[82] = halfDepth); - (vertices[86] = 1), (vertices[87] = 1); - (vertices[88] = -halfWidth), (vertices[89] = -halfHeight), (vertices[90] = -halfDepth); - (vertices[94] = 0), (vertices[95] = 1); - for (let i = 0; i < 4; i++) { - let normalOffset = vertexFloatCount * i + 67; - (vertices[normalOffset++] = -1), (vertices[normalOffset++] = 0), (vertices[normalOffset++] = 0); - } - - // Right - (vertices[96] = halfWidth), (vertices[97] = halfHeight), (vertices[98] = -halfDepth); - (vertices[102] = 1), (vertices[103] = 0); - (vertices[104] = halfWidth), (vertices[105] = halfHeight), (vertices[106] = halfDepth); - (vertices[110] = 0), (vertices[111] = 0); - (vertices[112] = halfWidth), (vertices[113] = -halfHeight), (vertices[114] = halfDepth); - (vertices[118] = 0), (vertices[119] = 1); - (vertices[120] = halfWidth), (vertices[121] = -halfHeight), (vertices[122] = -halfDepth); - (vertices[126] = 1), (vertices[127] = 1); - for (let i = 0; i < 4; i++) { - let normalOffset = vertexFloatCount * i + 99; - (vertices[normalOffset++] = 1), (vertices[normalOffset++] = 0), (vertices[normalOffset++] = 0); - } - - // Front - (vertices[128] = -halfWidth), (vertices[129] = halfHeight), (vertices[130] = halfDepth); - (vertices[134] = 0), (vertices[135] = 0); - (vertices[136] = halfWidth), (vertices[137] = halfHeight), (vertices[138] = halfDepth); - (vertices[142] = 1), (vertices[143] = 0); - (vertices[144] = halfWidth), (vertices[145] = -halfHeight), (vertices[146] = halfDepth); - (vertices[150] = 1), (vertices[151] = 1); - (vertices[152] = -halfWidth), (vertices[153] = -halfHeight), (vertices[154] = halfDepth); - (vertices[158] = 0), (vertices[159] = 1); - for (let i = 0; i < 4; i++) { - let normalOffset = vertexFloatCount * i + 131; - (vertices[normalOffset++] = 0), (vertices[normalOffset++] = 0), (vertices[normalOffset++] = 1); - } - - // Back - (vertices[160] = -halfWidth), (vertices[161] = halfHeight), (vertices[162] = -halfDepth); - (vertices[166] = 1), (vertices[167] = 0); - (vertices[168] = halfWidth), (vertices[169] = halfHeight), (vertices[170] = -halfDepth); - (vertices[174] = 0), (vertices[175] = 0); - (vertices[176] = halfWidth), (vertices[177] = -halfHeight), (vertices[178] = -halfDepth); - (vertices[182] = 0), (vertices[183] = 1); - (vertices[184] = -halfWidth), (vertices[185] = -halfHeight), (vertices[186] = -halfDepth); - (vertices[190] = 1), (vertices[191] = 1); - for (let i = 0; i < 4; i++) { - let normalOffset = vertexFloatCount * i + 163; - (vertices[normalOffset++] = 0), (vertices[normalOffset++] = 0), (vertices[normalOffset++] = -1); - } - - const indices = new Uint16Array(36); - - // prettier-ignore - // Up - indices[0] = 0, indices[1] = 2, indices[2] = 1, indices[3] = 2, indices[4] = 0, indices[5] = 3, - // Down - indices[6] = 4, indices[7] = 6, indices[8] = 7, indices[9] = 6, indices[10] = 4, indices[11] = 5, - // Left - indices[12] = 8, indices[13] = 10, indices[14] = 9, indices[15] = 10, indices[16] = 8, indices[17] = 11, - // Right - indices[18] = 12, indices[19] = 14, indices[20] = 15, indices[21] = 14, indices[22] = 12, indices[23] = 13, - // Front - indices[24] = 16, indices[25] = 18, indices[26] = 17, indices[27] = 18, indices[28] = 16, indices[29] = 19, - // Back - indices[30] = 20, indices[31] = 22, indices[32] = 23, indices[33] = 22, indices[34] = 20, indices[35] = 21; - - if (!isRestoreMode) { - const { bounds } = cuboidMesh; - bounds.min.set(-halfWidth, -halfHeight, -halfDepth); - bounds.max.set(halfWidth, halfHeight, halfDepth); - } - PrimitiveMesh._initialize(cuboidMesh, vertices, indices, noLongerAccessible, isRestoreMode, restoreVertexBuffer); - } - - /** - * @internal - */ - static _setPlaneData( - planeMesh: ModelMesh, - width: number, - height: number, - horizontalSegments: number, - verticalSegments: number, - noLongerAccessible: boolean, - isRestoreMode: boolean, - restoreVertexBuffer?: Buffer - ): void { - horizontalSegments = Math.max(1, Math.floor(horizontalSegments)); - verticalSegments = Math.max(1, Math.floor(verticalSegments)); - - const horizontalCount = horizontalSegments + 1; - const verticalCount = verticalSegments + 1; - const halfWidth = width / 2; - const halfHeight = height / 2; - const gridWidth = width / horizontalSegments; - const gridHeight = height / verticalSegments; - const vertexCount = horizontalCount * verticalCount; - const rectangleCount = verticalSegments * horizontalSegments; - const indices = PrimitiveMesh._generateIndices(planeMesh.engine, vertexCount, rectangleCount * 6); - const horizontalCountReciprocal = 1.0 / horizontalCount; - const horizontalSegmentsReciprocal = 1.0 / horizontalSegments; - const verticalSegmentsReciprocal = 1.0 / verticalSegments; - - const vertexFloatCount = 8; - const vertices = new Float32Array(vertexCount * vertexFloatCount); - - for (let i = 0; i < vertexCount; ++i) { - const x = i % horizontalCount; - const z = (i * horizontalCountReciprocal) | 0; - - let offset = i * vertexFloatCount; - // Position - vertices[offset++] = x * gridWidth - halfWidth; - vertices[offset++] = 0; - vertices[offset++] = z * gridHeight - halfHeight; - // Normal - vertices[offset++] = 0; - vertices[offset++] = 1; - vertices[offset++] = 0; - // TexCoord - vertices[offset++] = x * horizontalSegmentsReciprocal; - vertices[offset++] = z * verticalSegmentsReciprocal; + const data = generate(...args); + data.trim(); + if (data.vertexCount > 65535 && !engine._hardwareRenderer.canIUse(GLCapabilityType.elementIndexUint)) { + throw new Error("The vertex count is over limit."); } - - let offset = 0; - for (let i = 0; i < rectangleCount; ++i) { - const x = i % horizontalSegments; - const y = (i * horizontalSegmentsReciprocal) | 0; - - const a = y * horizontalCount + x; - const b = a + 1; - const c = a + horizontalCount; - const d = c + 1; - - indices[offset++] = a; - indices[offset++] = c; - indices[offset++] = b; - indices[offset++] = c; - indices[offset++] = d; - indices[offset++] = b; + const mesh = new ModelMesh(engine); + const vertices = data.vertices; + const indices = data.indices; + mesh.setVertexElements([ + new VertexElement(VertexAttribute.Position, 0, VertexElementFormat.Vector3, 0), + new VertexElement(VertexAttribute.Normal, 12, VertexElementFormat.Vector3, 0), + new VertexElement(VertexAttribute.UV, 24, VertexElementFormat.Vector2, 0) + ]); + const vertexBuffer = new Buffer(mesh.engine, BufferBindFlag.VertexBuffer, vertices, BufferUsage.Static, true); + mesh.setVertexBufferBinding(vertexBuffer, 32, 0); + mesh.setIndices(indices); + mesh.calculateTangents(); + PrimitiveMesh._setBounds(mesh, data); + mesh.uploadData(!keepMeshData); + if (!keepMeshData) { + vertexBuffer.markAsUnreadable(); } - - if (!isRestoreMode) { - const { bounds } = planeMesh; - bounds.min.set(-halfWidth, 0, -halfHeight); - bounds.max.set(halfWidth, 0, halfHeight); + if (options?.separateMaterialSlots && data.groups.length) { + for (const group of data.groups) { + mesh.addSubMesh(group.start, group.count); + } + } else { + mesh.addSubMesh(0, indices.length); } - - PrimitiveMesh._initialize(planeMesh, vertices, indices, noLongerAccessible, isRestoreMode, restoreVertexBuffer); + engine.resourceManager.addContentRestorer(new PrimitiveMeshRestorer(mesh, generate, args)); + return mesh; } - /** - * @internal - */ - static _setCylinderData( - cylinderMesh: ModelMesh, - radiusTop: number = 0.5, - radiusBottom: number = 0.5, - height: number = 2, - radialSegments: number = 20, - heightSegments: number = 1, - noLongerAccessible: boolean, - isRestoreMode: boolean, - restoreVertexBuffer?: Buffer - ): void { - radialSegments = Math.floor(radialSegments); - heightSegments = Math.floor(heightSegments); - - const radialCount = radialSegments + 1; - const verticalCount = heightSegments + 1; - const halfHeight = height * 0.5; - const unitHeight = height / heightSegments; - const torsoVertexCount = radialCount * verticalCount; - const torsoRectangleCount = radialSegments * heightSegments; - const capTriangleCount = radialSegments * 2; - const totalVertexCount = torsoVertexCount + 2 + capTriangleCount; - const indices = PrimitiveMesh._generateIndices( - cylinderMesh.engine, - totalVertexCount, - torsoRectangleCount * 6 + capTriangleCount * 3 - ); - const radialCountReciprocal = 1.0 / radialCount; - const radialSegmentsReciprocal = 1.0 / radialSegments; - const heightSegmentsReciprocal = 1.0 / heightSegments; - - const vertexFloatCount = 8; - const vertices = new Float32Array(totalVertexCount * vertexFloatCount); - - let indicesOffset = 0; - - // Create torso - const thetaStart = Math.PI; - const thetaRange = Math.PI * 2; - const radiusDiff = radiusBottom - radiusTop; - const slope = radiusDiff / height; - const radiusSlope = radiusDiff / heightSegments; - - for (let i = 0; i < torsoVertexCount; ++i) { - const x = i % radialCount; - const y = (i * radialCountReciprocal) | 0; - const u = x * radialSegmentsReciprocal; - const v = y * heightSegmentsReciprocal; - const theta = thetaStart + u * thetaRange; - const sinTheta = Math.sin(theta); - const cosTheta = Math.cos(theta); - const radius = radiusBottom - y * radiusSlope; - - const posX = radius * sinTheta; - const posY = y * unitHeight - halfHeight; - const posZ = radius * cosTheta; - - let offset = i * vertexFloatCount; - // Position - vertices[offset++] = posX; - vertices[offset++] = posY; - vertices[offset++] = posZ; - // Normal - vertices[offset++] = sinTheta; - vertices[offset++] = slope; - vertices[offset++] = cosTheta; - // TexCoord - vertices[offset++] = u; - vertices[offset++] = 1 - v; - } - - for (let i = 0; i < torsoRectangleCount; ++i) { - const x = i % radialSegments; - const y = (i * radialSegmentsReciprocal) | 0; - - const a = y * radialCount + x; - const b = a + 1; - const c = a + radialCount; - const d = c + 1; - - indices[indicesOffset++] = b; - indices[indicesOffset++] = c; - indices[indicesOffset++] = a; - indices[indicesOffset++] = b; - indices[indicesOffset++] = d; - indices[indicesOffset++] = c; - } - - let offset = torsoVertexCount * vertexFloatCount; - // Bottom position - vertices[offset++] = 0; - vertices[offset++] = -halfHeight; - vertices[offset++] = 0; - // Bottom normal - vertices[offset++] = 0; - vertices[offset++] = -1; - vertices[offset++] = 0; - // Bottom texCoord - vertices[offset++] = 0.5; - vertices[offset++] = 0.5; - - // Top position - vertices[offset++] = 0; - vertices[offset++] = halfHeight; - vertices[offset++] = 0; - // Top normal - vertices[offset++] = 0; - vertices[offset++] = 1; - vertices[offset++] = 0; - // Top texCoord - vertices[offset++] = 0.5; - vertices[offset++] = 0.5; - - // Add cap vertices - offset = (torsoVertexCount + 2) * vertexFloatCount; - - const diameterTopReciprocal = 1.0 / (radiusTop * 2); - const diameterBottomReciprocal = 1.0 / (radiusBottom * 2); - const positionStride = radialCount * heightSegments; - for (let i = 0; i < radialSegments; ++i) { - const curPosBottomOffset = i * vertexFloatCount; - let curPosX = vertices[curPosBottomOffset]; - let curPosZ = vertices[curPosBottomOffset + 2]; - - // Bottom position - vertices[offset++] = curPosX; - vertices[offset++] = -halfHeight; - vertices[offset++] = curPosZ; - // Bottom normal - vertices[offset++] = 0; - vertices[offset++] = -1; - vertices[offset++] = 0; - // Bottom texcoord - vertices[offset++] = curPosX * diameterBottomReciprocal + 0.5; - vertices[offset++] = 0.5 - curPosZ * diameterBottomReciprocal; - - const curPosTopOffset = (i + positionStride) * vertexFloatCount; - curPosX = vertices[curPosTopOffset]; - curPosZ = vertices[curPosTopOffset + 2]; - - // Top position - vertices[offset++] = curPosX; - vertices[offset++] = halfHeight; - vertices[offset++] = curPosZ; - // Top normal - vertices[offset++] = 0; - vertices[offset++] = 1; - vertices[offset++] = 0; - // Top texcoord - vertices[offset++] = curPosX * diameterTopReciprocal + 0.5; - vertices[offset++] = 0.5 - curPosZ * diameterTopReciprocal; - } - - // Add cap indices - const topCapIndex = torsoVertexCount + 1; - const bottomIndiceIndex = torsoVertexCount + 2; - const topIndiceIndex = bottomIndiceIndex + 1; - for (let i = 0; i < radialSegments; ++i) { - const firstStride = i * 2; - const secondStride = i === radialSegments - 1 ? 0 : firstStride + 2; - - // Bottom - indices[indicesOffset++] = torsoVertexCount; - indices[indicesOffset++] = bottomIndiceIndex + secondStride; - indices[indicesOffset++] = bottomIndiceIndex + firstStride; - - // Top - indices[indicesOffset++] = topCapIndex; - indices[indicesOffset++] = topIndiceIndex + firstStride; - indices[indicesOffset++] = topIndiceIndex + secondStride; - } - - if (!isRestoreMode) { - const { bounds } = cylinderMesh; - const radiusMax = Math.max(radiusTop, radiusBottom); - bounds.min.set(-radiusMax, -halfHeight, -radiusMax); - bounds.max.set(radiusMax, halfHeight, radiusMax); - } - PrimitiveMesh._initialize(cylinderMesh, vertices, indices, noLongerAccessible, isRestoreMode, restoreVertexBuffer); + private static _polygons( + input: readonly Vector2[] | PolygonShape | readonly PolygonShape[] + ): readonly PolygonShape[] { + if (!Array.isArray(input)) { + return [input as PolygonShape]; + } + if (input.length === 0 || "points" in input[0]) { + return input as readonly PolygonShape[]; + } + return [{ points: input as readonly Vector2[] }]; } - /** - * @internal - */ - static _setTorusData( - torusMesh: ModelMesh, - radius: number, - tubeRadius: number, - radialSegments: number, - tubularSegments: number, - arc: number, - noLongerAccessible: boolean, - isRestoreMode: boolean, - restoreVertexBuffer?: Buffer - ): void { - radialSegments = Math.floor(radialSegments); - tubularSegments = Math.floor(tubularSegments); - - const vertexCount = (radialSegments + 1) * (tubularSegments + 1); - const rectangleCount = radialSegments * tubularSegments; - const indices = PrimitiveMesh._generateIndices(torusMesh.engine, vertexCount, rectangleCount * 6); - - const vertexFloatCount = 8; - const vertices = new Float32Array(vertexCount * vertexFloatCount); - - arc = (arc / 180) * Math.PI; - - let offset = 0; - - const normal = PrimitiveMesh._tempVec30; - for (let i = 0; i <= radialSegments; i++) { - for (let j = 0; j <= tubularSegments; j++) { - const u = (j / tubularSegments) * arc; - const v = (i / radialSegments) * Math.PI * 2; - const cosV = Math.cos(v); - const sinV = Math.sin(v); - const cosU = Math.cos(u); - const sinU = Math.sin(u); - - // Position - const positionX = (radius + tubeRadius * cosV) * cosU; - const positionY = (radius + tubeRadius * cosV) * sinU; - const positionZ = tubeRadius * sinV; - vertices[offset++] = positionX; - vertices[offset++] = positionY; - vertices[offset++] = positionZ; - - // Normal - const centerX = radius * cosU; - const centerY = radius * sinU; - normal.set(positionX - centerX, positionY - centerY, positionZ).normalize(); - vertices[offset++] = normal.x; - vertices[offset++] = normal.y; - vertices[offset++] = normal.z; - - // UV - vertices[offset++] = j / tubularSegments; - vertices[offset++] = i / radialSegments; - } + private static _setBounds(mesh: ModelMesh, data: PrimitiveMeshBuilder): void { + const extent = data.boundsExtent; + if (extent) { + mesh.bounds.min.set(-extent.x || 0, -extent.y || 0, -extent.z || 0); + mesh.bounds.max.copyFrom(extent); + return; } - - offset = 0; - for (let i = 1; i <= radialSegments; i++) { - for (let j = 1; j <= tubularSegments; j++) { - const a = (tubularSegments + 1) * i + j - 1; - const b = (tubularSegments + 1) * (i - 1) + j - 1; - const c = (tubularSegments + 1) * (i - 1) + j; - const d = (tubularSegments + 1) * i + j; - - indices[offset++] = a; - indices[offset++] = b; - indices[offset++] = d; - - indices[offset++] = b; - indices[offset++] = c; - indices[offset++] = d; - } + let minX = Infinity, + minY = Infinity, + minZ = Infinity; + let maxX = -Infinity, + maxY = -Infinity, + maxZ = -Infinity; + for (let i = 0; i < data.vertices.length; i += 8) { + minX = Math.min(minX, data.vertices[i]); + minY = Math.min(minY, data.vertices[i + 1]); + minZ = Math.min(minZ, data.vertices[i + 2]); + maxX = Math.max(maxX, data.vertices[i]); + maxY = Math.max(maxY, data.vertices[i + 1]); + maxZ = Math.max(maxZ, data.vertices[i + 2]); } - - if (!isRestoreMode) { - const { bounds } = torusMesh; - const outerRadius = radius + tubeRadius; - bounds.min.set(-outerRadius, -outerRadius, -tubeRadius); - bounds.max.set(outerRadius, outerRadius, tubeRadius); + if (!data.vertices.length) { + minX = minY = minZ = maxX = maxY = maxZ = 0; } - - PrimitiveMesh._initialize(torusMesh, vertices, indices, noLongerAccessible, isRestoreMode, restoreVertexBuffer); + mesh.bounds.min.set(minX, minY, minZ); + mesh.bounds.max.set(maxX, maxY, maxZ); } - /** - * @internal - */ - static _setConeData( - coneMesh: ModelMesh, - radius: number, - height: number, - radialSegments: number, - heightSegments: number, - noLongerAccessible: boolean, - isRestoreMode: boolean, - restoreVertexBuffer?: Buffer - ): void { - radialSegments = Math.floor(radialSegments); - heightSegments = Math.floor(heightSegments); - - const radialCount = radialSegments + 1; - const verticalCount = heightSegments + 1; - const halfHeight = height * 0.5; - const unitHeight = height / heightSegments; - const torsoVertexCount = radialCount * verticalCount; - const torsoRectangleCount = radialSegments * heightSegments; - const totalVertexCount = torsoVertexCount + 1 + radialSegments; - const indices = PrimitiveMesh._generateIndices( - coneMesh.engine, - totalVertexCount, - torsoRectangleCount * 6 + radialSegments * 3 - ); - const radialCountReciprocal = 1.0 / radialCount; - const radialSegmentsReciprocal = 1.0 / radialSegments; - const heightSegmentsReciprocal = 1.0 / heightSegments; - - const vertexFloatCount = 8; - const vertices = new Float32Array(totalVertexCount * 8); - - let indicesOffset = 0; - - // Create torso - const thetaStart = Math.PI; - const thetaRange = Math.PI * 2; - const slope = radius / height; - - for (let i = 0; i < torsoVertexCount; ++i) { - const x = i % radialCount; - const y = (i * radialCountReciprocal) | 0; - const u = x * radialSegmentsReciprocal; - const v = y * heightSegmentsReciprocal; - const theta = thetaStart + u * thetaRange; - const sinTheta = Math.sin(theta); - const cosTheta = Math.cos(theta); - const curRadius = radius - v * radius; - - const posX = curRadius * sinTheta; - const posY = y * unitHeight - halfHeight; - const posZ = curRadius * cosTheta; - - let offset = i * vertexFloatCount; - // Position - vertices[offset++] = posX; - vertices[offset++] = posY; - vertices[offset++] = posZ; - // Normal - vertices[offset++] = sinTheta; - vertices[offset++] = slope; - vertices[offset++] = cosTheta; - // Texcoord - vertices[offset++] = u; - vertices[offset++] = 1 - v; - } - - for (let i = 0; i < torsoRectangleCount; ++i) { - const x = i % radialSegments; - const y = (i * radialSegmentsReciprocal) | 0; - - const a = y * radialCount + x; - const b = a + 1; - const c = a + radialCount; - const d = c + 1; - - indices[indicesOffset++] = b; - indices[indicesOffset++] = c; - indices[indicesOffset++] = a; - indices[indicesOffset++] = b; - indices[indicesOffset++] = d; - indices[indicesOffset++] = c; - } - - let offset = torsoVertexCount * vertexFloatCount; - // Bottom position - vertices[offset++] = 0; - vertices[offset++] = -halfHeight; - vertices[offset++] = 0; - // Bottom normal - vertices[offset++] = 0; - vertices[offset++] = -1; - vertices[offset++] = 0; - // Bottom texcoord - vertices[offset++] = 0.5; - vertices[offset++] = 0.5; - - // Add bottom cap vertices - offset = (torsoVertexCount + 1) * vertexFloatCount; - const diameterBottomReciprocal = 1.0 / (radius * 2); - for (let i = 0; i < radialSegments; ++i) { - const curPosX = vertices[i * vertexFloatCount]; - const curPosZ = vertices[i * vertexFloatCount + 2]; - - // Bottom position - vertices[offset++] = curPosX; - vertices[offset++] = -halfHeight; - vertices[offset++] = curPosZ; - // Bottom normal - vertices[offset++] = 0; - vertices[offset++] = -1; - vertices[offset++] = 0; - // Bottom texcoord - vertices[offset++] = curPosX * diameterBottomReciprocal + 0.5; - vertices[offset++] = 0.5 - curPosZ * diameterBottomReciprocal; - } - - const bottomIndiceIndex = torsoVertexCount + 1; - for (let i = 0; i < radialSegments; ++i) { - const firstStride = i; - const secondStride = i === radialSegments - 1 ? 0 : firstStride + 1; - - // Bottom - indices[indicesOffset++] = torsoVertexCount; - indices[indicesOffset++] = bottomIndiceIndex + secondStride; - indices[indicesOffset++] = bottomIndiceIndex + firstStride; - } - - if (!isRestoreMode) { - const { bounds } = coneMesh; - bounds.min.set(-radius, -halfHeight, -radius); - bounds.max.set(radius, halfHeight, radius); - } - - PrimitiveMesh._initialize(coneMesh, vertices, indices, noLongerAccessible, isRestoreMode, restoreVertexBuffer); - } - - /** - * @internal - */ - static _setCapsuleData( - capsuleMesh: ModelMesh, - radius: number, - height: number, - radialSegments: number, - heightSegments: number, - noLongerAccessible: boolean, - isRestoreMode: boolean, - restoreVertexBuffer?: Buffer - ): void { - radialSegments = Math.max(2, Math.floor(radialSegments)); - heightSegments = Math.floor(heightSegments); - - const radialCount = radialSegments + 1; - const verticalCount = heightSegments + 1; - const halfHeight = height * 0.5; - const unitHeight = height / heightSegments; - const torsoVertexCount = radialCount * verticalCount; - const torsoRectangleCount = radialSegments * heightSegments; - - const capVertexCount = radialCount * radialCount; - const capRectangleCount = radialSegments * radialSegments; - - const totalVertexCount = torsoVertexCount + 2 * capVertexCount; - const indices = PrimitiveMesh._generateIndices( - capsuleMesh.engine, - totalVertexCount, - (torsoRectangleCount + 2 * capRectangleCount) * 6 - ); - - const radialCountReciprocal = 1.0 / radialCount; - const radialSegmentsReciprocal = 1.0 / radialSegments; - const heightSegmentsReciprocal = 1.0 / heightSegments; - - const thetaStart = Math.PI; - const thetaRange = Math.PI * 2; - - const vertexFloatCount = 8; - const vertices = new Float32Array(totalVertexCount * vertexFloatCount); - - let indicesOffset = 0; - - // create torso - for (let i = 0; i < torsoVertexCount; ++i) { - const x = i % radialCount; - const y = (i * radialCountReciprocal) | 0; - const u = x * radialSegmentsReciprocal; - const v = y * heightSegmentsReciprocal; - const theta = thetaStart + u * thetaRange; - const sinTheta = Math.sin(theta); - const cosTheta = Math.cos(theta); - - let offset = i * vertexFloatCount; - - // position - vertices[offset++] = radius * sinTheta; - vertices[offset++] = y * unitHeight - halfHeight; - vertices[offset++] = radius * cosTheta; - - // Normal - vertices[offset++] = sinTheta; - vertices[offset++] = 0; - vertices[offset++] = cosTheta; - - // Texcoord - vertices[offset++] = u; - vertices[offset++] = 1 - v; - } - - for (let i = 0; i < torsoRectangleCount; ++i) { - const x = i % radialSegments; - const y = (i * radialSegmentsReciprocal) | 0; - - const a = y * radialCount + x; - const b = a + 1; - const c = a + radialCount; - const d = c + 1; - - indices[indicesOffset++] = b; - indices[indicesOffset++] = c; - indices[indicesOffset++] = a; - indices[indicesOffset++] = b; - indices[indicesOffset++] = d; - indices[indicesOffset++] = c; - } - - PrimitiveMesh._createCapsuleCap( - radius, - height, - radialSegments, - thetaStart, - thetaRange, - torsoVertexCount, - 1, - vertices, - indices, - indicesOffset - ); - - PrimitiveMesh._createCapsuleCap( - radius, - height, - radialSegments, - thetaStart, - -thetaRange, - torsoVertexCount + capVertexCount, - -1, - vertices, - indices, - indicesOffset + 6 * capRectangleCount - ); - - if (!isRestoreMode) { - const { bounds } = capsuleMesh; - bounds.min.set(-radius, -radius - halfHeight, -radius); - bounds.max.set(radius, radius + halfHeight, radius); + private static _copy(value: unknown): unknown { + if (value instanceof Vector2 || value instanceof Vector3) { + return value.clone(); } - - PrimitiveMesh._initialize(capsuleMesh, vertices, indices, noLongerAccessible, isRestoreMode, restoreVertexBuffer); - } - - private static _initialize( - mesh: ModelMesh, - vertices: Float32Array, - indices: Uint16Array | Uint32Array, - noLongerAccessible: boolean, - isRestoreMode: boolean, - restoreVertexBuffer?: Buffer - ) { - if (isRestoreMode) { - restoreVertexBuffer!.setData(vertices); - mesh.setIndices(indices); - mesh.uploadData(noLongerAccessible); - } else { - const vertexElements = [ - new VertexElement(VertexAttribute.Position, 0, VertexElementFormat.Vector3, 0), - new VertexElement(VertexAttribute.Normal, 12, VertexElementFormat.Vector3, 0), - new VertexElement(VertexAttribute.UV, 24, VertexElementFormat.Vector2, 0) - ]; - mesh.setVertexElements(vertexElements); - - const vertexBuffer = new Buffer(mesh.engine, BufferBindFlag.VertexBuffer, vertices, BufferUsage.Static, true); - mesh.setVertexBufferBinding(vertexBuffer, 32, 0); - - mesh.setIndices(indices); - mesh.calculateTangents(); - - mesh.uploadData(noLongerAccessible); - - mesh.addSubMesh(0, indices.length); + if (Array.isArray(value)) { + return value.map(PrimitiveMesh._copy); } - } - - private static _generateIndices(engine: Engine, vertexCount: number, indexCount: number): Uint16Array | Uint32Array { - let indices: Uint16Array | Uint32Array | null = null; - if (vertexCount > 65535) { - if (engine._hardwareRenderer.canIUse(GLCapabilityType.elementIndexUint)) { - indices = new Uint32Array(indexCount); - } else { - throw Error("The vertex count is over limit."); + if (value && typeof value === "object") { + const result = {}; + for (const key of Object.keys(value)) { + result[key] = PrimitiveMesh._copy(value[key]); } - } else { - indices = new Uint16Array(indexCount); + return result; } - return indices; + return value; } - private static _createCapsuleCap( - radius: number, - height: number, - radialSegments: number, - thetaStart: number, - thetaRange: number, - offset: number, - posIndex: number, - vertices: Float32Array, - indices: Uint16Array | Uint32Array, - indicesOffset: number - ) { - const radialCount = radialSegments + 1; - const halfHeight = height * 0.5 * posIndex; - const capVertexCount = radialCount * radialCount; - const capRectangleCount = radialSegments * radialSegments; - const radialCountReciprocal = 1.0 / radialCount; - const radialSegmentsReciprocal = 1.0 / radialSegments; - const vertexFloatCount = 8; - - for (let i = 0; i < capVertexCount; ++i) { - const x = i % radialCount; - const y = (i * radialCountReciprocal) | 0; - const u = x * radialSegmentsReciprocal; - const v = y * radialSegmentsReciprocal; - const theta = thetaStart + u * thetaRange; - const alpha = v * Math.PI * 0.5; - const sinAlpha = Math.sin(alpha); - - const posX = radius * Math.sin(theta) * sinAlpha; - const posY = radius * Math.cos(alpha) * posIndex + halfHeight; - const posZ = radius * Math.cos(theta) * sinAlpha; - - let index = (i + offset) * vertexFloatCount; - // Position - vertices[index++] = posX; - vertices[index++] = posY; - vertices[index++] = posZ; - - // Normal - vertices[index++] = posX; - vertices[index++] = posY - halfHeight; - vertices[index++] = posZ; - - // Texcoord - vertices[index++] = u; - vertices[index++] = v; - } - - for (let i = 0; i < capRectangleCount; ++i) { - const x = i % radialSegments; - const y = (i * radialSegmentsReciprocal) | 0; - - const a = y * radialCount + x + offset; - const b = a + 1; - const c = a + radialCount; - const d = c + 1; - - indices[indicesOffset++] = b; - indices[indicesOffset++] = a; - indices[indicesOffset++] = d; - indices[indicesOffset++] = a; - indices[indicesOffset++] = c; - indices[indicesOffset++] = d; + private static _createArcSamples(segments: number, start: number = 0, arc: number = Math.PI * 2): Float64Array { + const samples = new Float64Array((segments + 1) * 2); + for (let i = 0; i <= segments; i++) { + const angle = start + (i / segments) * arc; + samples[i * 2] = Math.cos(angle); + samples[i * 2 + 1] = Math.sin(angle); } + return samples; } -} -interface IEdge { - edgePoint: Vector3; - edgePointIndex: number | undefined; -} + private static _getSegmentCount(value: number, minimum: number = 1): number { + return Math.max(minimum, Math.floor(value)); + } -interface IFace { - facePoint: Vector3; - adjacentEdges: Array; + private static _normalizeVector(vector: Vector3): Vector3 { + const length = Math.hypot(vector.x, vector.y, vector.z); + return vector.scale(length > 0 ? 1 / length : 0); + } } diff --git a/packages/core/src/mesh/PrimitiveMeshOptions.ts b/packages/core/src/mesh/PrimitiveMeshOptions.ts new file mode 100644 index 0000000000..1afcda019b --- /dev/null +++ b/packages/core/src/mesh/PrimitiveMeshOptions.ts @@ -0,0 +1,435 @@ +import type { Vector2 } from "@galacean/engine-math"; +import type { PrimitiveMeshCapMode } from "./enums/PrimitiveMeshCapMode"; + +/** + * Settings shared by all primitive meshes. + */ +export interface PrimitiveMeshOptions { + /** + * Whether to retain readable vertex attributes and indices after mesh creation. + * @defaultValue `false` + */ + keepMeshData?: boolean; +} + +/** + * A polygon in the XY plane, optionally containing holes. + * Either winding order is accepted for the outer contour and holes. + */ +export interface PolygonShape { + /** + * The outer contour, with at least three distinct points. The closing point need not be repeated. + */ + points: readonly Vector2[]; + /** + * Contours cut out of the polygon, each with at least three distinct points. + * Closing points need not be repeated. + * @defaultValue No holes. + */ + holes?: readonly (readonly Vector2[])[]; +} + +/** + * Settings for a sphere or an open spherical section generated from a subdivided cube. + */ +export interface SphereMeshOptions extends PrimitiveMeshOptions { + /** + * The subdivision level, rounded down and clamped to 1 through 6. + * @defaultValue `3` + */ + subdivisionLevel?: number; + /** + * The start (`x`) and end (`y`) horizontal angles in degrees, measured from -X towards +Z. + * The span is limited to 360 degrees. Section boundaries remain open. + * @defaultValue `new Vector2(0, 360)` + */ + horizontalAngleRange?: Vector2; + /** + * The start (`x`) and end (`y`) polar angles in degrees, measured from +Y towards -Y. + * The interval is clipped to [0, 180]. + * Section boundaries remain open. + * @defaultValue `new Vector2(0, 180)` + */ + verticalAngleRange?: Vector2; +} + +/** + * Settings for an axis-aligned cuboid centered at the origin. + */ +export interface CuboidMeshOptions extends PrimitiveMeshOptions { + /** + * The number of subdivisions along X, rounded down with a minimum of 1. + * @defaultValue `1` + */ + widthSegments?: number; + /** + * The number of subdivisions along Y, rounded down with a minimum of 1. + * @defaultValue The value of `widthSegments`. + */ + heightSegments?: number; + /** + * The number of subdivisions along Z, rounded down with a minimum of 1. + * @defaultValue The value of `widthSegments`. + */ + depthSegments?: number; + /** + * Whether to create one sub-mesh per face, ordered +Y, -Y, -X, +X, +Z, -Z. + * @defaultValue `false` + */ + separateMaterialSlots?: boolean; +} + +/** + * Settings for a plane in XZ facing +Y, centered at the origin. + */ +export interface PlaneMeshOptions extends PrimitiveMeshOptions { + /** + * The number of subdivisions along X, rounded down with a minimum of 1. + * @defaultValue `1` + */ + widthSegments?: number; + /** + * The number of subdivisions along Z, rounded down with a minimum of 1. + * @defaultValue The value of `widthSegments`. + */ + depthSegments?: number; +} + +/** + * Settings for a cylinder centered on Y with equal end radii. + */ +export interface CylinderMeshOptions extends PrimitiveMeshOptions { + /** + * The number of segments around the circumference, rounded down with a minimum of 3. + * @defaultValue `20` + */ + radialSegments?: number; + /** + * The number of subdivisions along Y, rounded down with a minimum of 1. + * @defaultValue `1` + */ + heightSegments?: number; + /** + * The ends to cap. Zero-radius ends and angular cut boundaries remain open. + * @defaultValue `PrimitiveMeshCapMode.Both` + */ + caps?: PrimitiveMeshCapMode; + /** + * The start (`x`) and end (`y`) angles in degrees around Y, measured from -Z towards -X. + * @defaultValue `new Vector2(0, 360)` + */ + angleRange?: Vector2; + /** + * Whether to create separate sub-meshes for the side, top and bottom, in that order. + * Omitted or zero-radius caps do not occupy slots. + * @defaultValue `false` + */ + separateMaterialSlots?: boolean; +} + +/** + * Settings for a truncated cone centered on Y with independently sized ends. + */ +export interface TruncatedConeMeshOptions extends PrimitiveMeshOptions { + /** + * The number of segments around the circumference, rounded down with a minimum of 3. + * @defaultValue `20` + */ + radialSegments?: number; + /** + * The number of subdivisions along Y, rounded down with a minimum of 1. + * @defaultValue `1` + */ + heightSegments?: number; + /** + * The ends to cap. Zero-radius ends have no caps, and angular cut boundaries remain open. + * @defaultValue `PrimitiveMeshCapMode.Both` + */ + caps?: PrimitiveMeshCapMode; + /** + * The start (`x`) and end (`y`) angles in degrees around Y, measured from -Z towards -X. + * @defaultValue `new Vector2(0, 360)` + */ + angleRange?: Vector2; + /** + * Whether to create separate sub-meshes for the side, top and bottom, in that order. + * Omitted or zero-radius caps do not occupy slots. + * @defaultValue `false` + */ + separateMaterialSlots?: boolean; +} + +/** + * Settings for a cone centered on Y with its tip at the top. + */ +export interface ConeMeshOptions extends PrimitiveMeshOptions { + /** + * The number of segments around the circumference, rounded down with a minimum of 3. + * @defaultValue `20` + */ + radialSegments?: number; + /** + * The number of subdivisions along Y, rounded down with a minimum of 1. + * @defaultValue `1` + */ + heightSegments?: number; + /** + * Whether to cap the bottom. A zero-radius bottom and angular cut boundaries remain open. + * @defaultValue `true` + */ + cap?: boolean; + /** + * The start (`x`) and end (`y`) angles in degrees around Y, measured from -Z towards -X. + * @defaultValue `new Vector2(0, 360)` + */ + angleRange?: Vector2; + /** + * Whether to create separate sub-meshes for the side and bottom, in that order. + * An omitted or zero-radius bottom cap does not occupy a slot. + * @defaultValue `false` + */ + separateMaterialSlots?: boolean; +} + +/** + * Settings for a capsule centered on Y. + */ +export interface CapsuleMeshOptions extends PrimitiveMeshOptions { + /** + * The number of segments around the circumference, rounded down with a minimum of 3. + * @defaultValue `6` + */ + radialSegments?: number; + /** + * The number of subdivisions from each pole to the cylinder, rounded down with a minimum of 1. + * @defaultValue The value of `radialSegments`. + */ + capSegments?: number; + /** + * The number of subdivisions along the cylinder, rounded down with a minimum of 1. + * @defaultValue `1` + */ + heightSegments?: number; +} + +/** + * Settings for a torus centered in XY around Z. + */ +export interface TorusMeshOptions extends PrimitiveMeshOptions { + /** + * The number of segments around the torus, rounded down with a minimum of 1. + * @defaultValue `30` + */ + ringSegments?: number; + /** + * The number of segments around the tube cross-section, rounded down with a minimum of 3. + * @defaultValue `30` + */ + radialSegments?: number; + /** + * The start (`x`) and end (`y`) angles in degrees around Z, measured from +X towards +Y. + * Cut ends remain open. + * @defaultValue `new Vector2(0, 360)` + */ + ringAngleRange?: Vector2; + /** + * The start (`x`) and end (`y`) tube cross-section angles in degrees, measured from the outward radial direction towards +Z. + * Cut boundaries remain open. + * @defaultValue `new Vector2(0, 360)` + */ + tubeAngleRange?: Vector2; +} + +/** + * Settings for a filled disk or sector in XY facing +Z. + */ +export interface CircleMeshOptions extends PrimitiveMeshOptions { + /** + * The number of segments along the arc, rounded down with a minimum of 3. + * @defaultValue `32` + */ + segments?: number; + /** + * The start (`x`) and end (`y`) angles in degrees, measured from +X towards +Y. + * @defaultValue `new Vector2(0, 360)` + */ + angleRange?: Vector2; +} + +/** + * Settings for a ring or ring sector in XY facing +Z. + */ +export interface RingMeshOptions extends PrimitiveMeshOptions { + /** + * The number of segments along the arc, rounded down with a minimum of 3. + * @defaultValue `32` + */ + ringSegments?: number; + /** + * The number of subdivisions between the inner and outer edges, rounded down with a minimum of 1. + * @defaultValue `1` + */ + widthSegments?: number; + /** + * The start (`x`) and end (`y`) angles in degrees, measured from +X towards +Y. + * @defaultValue `new Vector2(0, 360)` + */ + angleRange?: Vector2; +} + +/** + * Settings shared by tetrahedra, octahedra, icosahedra and dodecahedra. + */ +export interface RegularPolyhedronMeshOptions extends PrimitiveMeshOptions { + /** + * The number of subdivisions per triangle edge, rounded down with a minimum of 1. + * Values above 1 project the new vertices onto the sphere and use smooth normals. + * @defaultValue `1` + */ + edgeSegments?: number; +} + +/** + * Settings for a surface of revolution generated from a radius-height profile around Y. + */ +export interface RevolvedSurfaceMeshOptions extends PrimitiveMeshOptions { + /** + * The number of segments along the revolution, rounded down with a minimum of 1. + * @defaultValue `12` + */ + segments?: number; + /** + * The start (`x`) and end (`y`) angles in degrees around Y, measured from +Z towards +X. + * Cut boundaries remain open. + * @defaultValue `new Vector2(0, 360)` + */ + angleRange?: Vector2; +} + +/** + * Settings for sweeping a circular cross-section along a polyline. + */ +export interface TubeMeshOptions extends PrimitiveMeshOptions { + /** + * The number of segments along the resampled path, rounded down with a minimum of 1. + * @defaultValue `64` + */ + pathSegments?: number; + /** + * The number of segments around the cross-section, rounded down with a minimum of 3. + * @defaultValue `8` + */ + radialSegments?: number; + /** + * Whether to join the path ends with matching cross-sections. The closing point need not be repeated. + * Open tubes have no end caps. + * @defaultValue `false` + */ + closedPath?: boolean; +} + +/** + * Settings for a zero-thickness polygon mesh in XY facing +Z. + */ +export interface PolygonMeshOptions extends PrimitiveMeshOptions { + /** + * Whether to create one sub-mesh per polygon in input order. Holes share their outer contour's sub-mesh. + * @defaultValue `false` + */ + separateMaterialSlots?: boolean; +} + +/** + * Settings for extruding polygon contours along +Z. + */ +export interface LinearExtrudedPolygonMeshOptions extends PrimitiveMeshOptions { + /** + * The number of subdivisions along the extrusion, rounded down with a minimum of 1. + * @defaultValue `1` + */ + depthSegments?: number; + /** + * The inset of each end cap relative to the side wall in local units. Zero disables bevels. + * @defaultValue `0` + */ + bevelWidth?: number; + /** + * The bevel depth at each end in local units, limited to half the extrusion depth. + * @defaultValue The value of `bevelWidth`. + */ + bevelDepth?: number; + /** + * The side-wall contour offset in local units. Positive values expand the solid and contract holes. + * Applies even when bevels are disabled. + * @defaultValue `0` + */ + contourOffset?: number; + /** + * The number of subdivisions per bevel, rounded down with a minimum of 1. + * @defaultValue `3` + */ + bevelSegments?: number; + /** + * Whether each polygon contributes a cap sub-mesh followed by a wall sub-mesh, in input order. + * Both end caps share one slot; outer walls, hole walls and bevels share the next. + * @defaultValue `false` + */ + separateMaterialSlots?: boolean; +} + +/** + * Settings for sweeping polygon contours along a polyline, without bevels. + * Polygon X and Y coordinates become offsets along the moving cross-section's axes. + */ +export interface PathExtrudedPolygonMeshOptions extends PrimitiveMeshOptions { + /** + * The number of subdivisions along the resampled path, rounded down with a minimum of 1, or 3 for closed paths. + * @defaultValue `1`, increased to `3` when `closedPath` is true. + */ + pathSegments?: number; + /** + * Whether to join the path ends with matching cross-sections and omit end caps. + * The closing point need not be repeated. + * @defaultValue `false` + */ + closedPath?: boolean; + /** + * Whether each polygon contributes a cap sub-mesh followed by a wall sub-mesh, in input order. + * Both end caps share one slot; outer and hole walls share the next. Closed paths use only the wall slot. + * @defaultValue `false` + */ + separateMaterialSlots?: boolean; +} + +/** + * Settings for a closed torus knot. + */ +export interface TorusKnotMeshOptions extends PrimitiveMeshOptions { + /** + * The number of segments along the knot, rounded down with a minimum of 1. + * @defaultValue `64` + */ + pathSegments?: number; + /** + * The number of segments around the tube cross-section, rounded down with a minimum of 3. + * @defaultValue `8` + */ + radialSegments?: number; +} + +/** + * Settings for an axis-aligned cuboid with rounded edges and corners. + */ +export interface RoundedCuboidMeshOptions extends PrimitiveMeshOptions { + /** + * The rounding subdivision count, rounded down with a minimum of 1. + * When `cornerRadius` is positive, each face uses `2 * roundingSegments + 1` subdivisions per axis. + * @defaultValue `2` + */ + roundingSegments?: number; + /** + * Whether to create one sub-mesh per face, ordered +Y, -Y, -X, +X, +Z, -Z. + * @defaultValue `false` + */ + separateMaterialSlots?: boolean; +} diff --git a/packages/core/src/mesh/PrimitiveMeshRestorer.ts b/packages/core/src/mesh/PrimitiveMeshRestorer.ts deleted file mode 100644 index e8e636f8d2..0000000000 --- a/packages/core/src/mesh/PrimitiveMeshRestorer.ts +++ /dev/null @@ -1,272 +0,0 @@ -import { ContentRestorer } from "../asset/ContentRestorer"; -import { Buffer } from "../graphic/Buffer"; -import { ModelMesh } from "./ModelMesh"; -import { PrimitiveMesh } from "./PrimitiveMesh"; - -/** - * @internal - */ -export class PrimitiveMeshRestorer extends ContentRestorer { - constructor( - resource: ModelMesh, - public primitiveInfo: PrimitiveRestoreInfo - ) { - super(resource); - } - - override restoreContent(): void { - const primitiveInfo = this.primitiveInfo; - switch (primitiveInfo.type) { - case PrimitiveType.Sphere: - const sphereInfo = primitiveInfo; - PrimitiveMesh._setSphereData( - this.resource, - sphereInfo.radius, - sphereInfo.segments, - sphereInfo.noLongerAccessible, - true, - sphereInfo.vertexBuffer - ); - break; - - case PrimitiveType.CCSphere: - const CCSphereInfo = primitiveInfo; - PrimitiveMesh._setSubdivisionSurfaceSphereData( - this.resource, - CCSphereInfo.radius, - CCSphereInfo.step, - CCSphereInfo.noLongerAccessible, - true, - CCSphereInfo.vertexBuffer - ); - break; - - case PrimitiveType.Cuboid: - const cuboidInfo = primitiveInfo; - PrimitiveMesh._setCuboidData( - this.resource, - cuboidInfo.width, - cuboidInfo.height, - cuboidInfo.depth, - cuboidInfo.noLongerAccessible, - true, - cuboidInfo.vertexBuffer - ); - break; - case PrimitiveType.Plane: - const planeInfo = primitiveInfo; - PrimitiveMesh._setPlaneData( - this.resource, - planeInfo.width, - planeInfo.height, - planeInfo.horizontalSegments, - planeInfo.verticalSegments, - planeInfo.noLongerAccessible, - true, - planeInfo.vertexBuffer - ); - break; - case PrimitiveType.Cylinder: - const cylinderInfo = primitiveInfo; - PrimitiveMesh._setCylinderData( - this.resource, - cylinderInfo.radiusTop, - cylinderInfo.radiusBottom, - cylinderInfo.height, - cylinderInfo.radialSegments, - cylinderInfo.heightSegments, - cylinderInfo.noLongerAccessible, - true, - cylinderInfo.vertexBuffer - ); - break; - case PrimitiveType.Torus: - const torusInfo = primitiveInfo; - PrimitiveMesh._setTorusData( - this.resource, - torusInfo.radius, - torusInfo.tubeRadius, - torusInfo.radialSegments, - torusInfo.tubularSegments, - torusInfo.arc, - torusInfo.noLongerAccessible, - true, - torusInfo.vertexBuffer - ); - break; - case PrimitiveType.Cone: - const coneInfo = primitiveInfo; - PrimitiveMesh._setConeData( - this.resource, - coneInfo.radius, - coneInfo.height, - coneInfo.radialSegments, - coneInfo.heightSegments, - coneInfo.noLongerAccessible, - true, - coneInfo.vertexBuffer - ); - break; - case PrimitiveType.Capsule: - const capsuleInfo = primitiveInfo; - PrimitiveMesh._setCapsuleData( - this.resource, - capsuleInfo.radius, - capsuleInfo.height, - capsuleInfo.radialSegments, - capsuleInfo.heightSegments, - capsuleInfo.noLongerAccessible, - true, - capsuleInfo.vertexBuffer - ); - break; - } - } -} - -enum PrimitiveType { - Sphere, - Cuboid, - Plane, - Cylinder, - Torus, - Cone, - Capsule, - CCSphere -} - -/** - * @internal - */ -export class PrimitiveRestoreInfo { - constructor( - public type: PrimitiveType, - public vertexBuffer: Buffer, - public noLongerAccessible: boolean - ) {} -} - -/** - * @internal - */ -export class SphereRestoreInfo extends PrimitiveRestoreInfo { - constructor( - public radius: number, - public segments: number, - vertexBuffer: Buffer, - noLongerAccessible: boolean - ) { - super(PrimitiveType.Sphere, vertexBuffer, noLongerAccessible); - } -} - -/** - * @internal - */ -export class SubdivisionSurfaceSphereRestoreInfo extends PrimitiveRestoreInfo { - constructor( - public radius: number, - public step: number, - vertexBuffer: Buffer, - noLongerAccessible: boolean - ) { - super(PrimitiveType.CCSphere, vertexBuffer, noLongerAccessible); - } -} - -/** - * @internal - */ -export class CuboidRestoreInfo extends PrimitiveRestoreInfo { - constructor( - public width: number, - public height: number, - public depth: number, - vertexBuffer: Buffer, - noLongerAccessible: boolean - ) { - super(PrimitiveType.Cuboid, vertexBuffer, noLongerAccessible); - } -} - -/** - * @internal - */ -export class PlaneRestoreInfo extends PrimitiveRestoreInfo { - constructor( - public width: number, - public height: number, - public horizontalSegments: number, - public verticalSegments: number, - vertexBuffer: Buffer, - noLongerAccessible: boolean - ) { - super(PrimitiveType.Plane, vertexBuffer, noLongerAccessible); - } -} - -/** - * @internal - */ -export class CylinderRestoreInfo extends PrimitiveRestoreInfo { - constructor( - public radiusTop: number, - public radiusBottom: number, - public height: number, - public radialSegments: number, - public heightSegments: number, - vertexBuffer: Buffer, - noLongerAccessible: boolean - ) { - super(PrimitiveType.Cylinder, vertexBuffer, noLongerAccessible); - } -} - -/** - * @internal - */ -export class TorusRestoreInfo extends PrimitiveRestoreInfo { - constructor( - public radius: number, - public tubeRadius: number, - public radialSegments: number, - public tubularSegments: number, - public arc: number, - vertexBuffer: Buffer, - noLongerAccessible: boolean - ) { - super(PrimitiveType.Torus, vertexBuffer, noLongerAccessible); - } -} - -/** - * @internal - */ -export class ConeRestoreInfo extends PrimitiveRestoreInfo { - constructor( - public radius: number, - public height: number, - public radialSegments: number, - public heightSegments: number, - vertexBuffer: Buffer, - noLongerAccessible: boolean - ) { - super(PrimitiveType.Cone, vertexBuffer, noLongerAccessible); - } -} - -/** - * @internal - */ -export class CapsuleRestoreInfo extends PrimitiveRestoreInfo { - constructor( - public radius: number, - public height: number, - public radialSegments: number, - public heightSegments: number, - vertexBuffer: Buffer, - noLongerAccessible: boolean - ) { - super(PrimitiveType.Capsule, vertexBuffer, noLongerAccessible); - } -} diff --git a/packages/core/src/mesh/enums/PrimitiveMeshCapMode.ts b/packages/core/src/mesh/enums/PrimitiveMeshCapMode.ts new file mode 100644 index 0000000000..460149f215 --- /dev/null +++ b/packages/core/src/mesh/enums/PrimitiveMeshCapMode.ts @@ -0,0 +1,21 @@ +/** + * End caps generated for cylinders and truncated cones. + */ +export enum PrimitiveMeshCapMode { + /** + * Generate both the top and bottom caps. + */ + Both = "both", + /** + * Generate only the top cap, facing +Y. + */ + Top = "top", + /** + * Generate only the bottom cap, facing -Y. + */ + Bottom = "bottom", + /** + * Leave both ends open. + */ + None = "none" +} diff --git a/packages/core/src/mesh/index.ts b/packages/core/src/mesh/index.ts index 8826054177..a9163a330f 100644 --- a/packages/core/src/mesh/index.ts +++ b/packages/core/src/mesh/index.ts @@ -4,6 +4,29 @@ export { BufferMesh } from "./BufferMesh"; export { MeshRenderer } from "./MeshRenderer"; export { ModelMesh } from "./ModelMesh"; export { PrimitiveMesh } from "./PrimitiveMesh"; +export type { + PrimitiveMeshOptions, + SphereMeshOptions, + CuboidMeshOptions, + PlaneMeshOptions, + CylinderMeshOptions, + TruncatedConeMeshOptions, + ConeMeshOptions, + CapsuleMeshOptions, + TorusMeshOptions, + CircleMeshOptions, + RingMeshOptions, + RegularPolyhedronMeshOptions, + RevolvedSurfaceMeshOptions, + TubeMeshOptions, + PolygonMeshOptions, + TorusKnotMeshOptions, + RoundedCuboidMeshOptions, + PolygonShape, + LinearExtrudedPolygonMeshOptions, + PathExtrudedPolygonMeshOptions +} from "./PrimitiveMeshOptions"; export { Skin } from "./Skin"; export { SkinnedMeshRenderer } from "./SkinnedMeshRenderer"; +export { PrimitiveMeshCapMode } from "./enums/PrimitiveMeshCapMode"; export { VertexAttribute } from "./enums/VertexAttribute"; diff --git a/packages/core/src/mesh/primitive/MeshPathUtils.ts b/packages/core/src/mesh/primitive/MeshPathUtils.ts new file mode 100644 index 0000000000..ca28a2e9c1 --- /dev/null +++ b/packages/core/src/mesh/primitive/MeshPathUtils.ts @@ -0,0 +1,151 @@ +import { Vector3 } from "@galacean/engine-math"; + +/** + * @internal + */ +export class MeshPathUtils { + static sample(path: readonly Vector3[], divisions: number, closed: boolean, tangents?: Vector3[]): Vector3[] { + const result = new Array(divisions + 1); + if (path.length < 2) { + throw new Error("A mesh path needs at least two points."); + } + const points: Vector3[] = []; + for (const point of path) { + if (points.length === 0 || Vector3.distance(points[points.length - 1], point) > 0) { + points.push(point); + } + } + if (closed && Vector3.distance(points[0], points[points.length - 1]) > 0) { + points.push(points[0]); + } + const lengths = new Float64Array(points.length); + for (let i = 1; i < points.length; i++) { + lengths[i] = lengths[i - 1] + Vector3.distance(points[i], points[i - 1]); + } + const length = lengths[lengths.length - 1]; + if (length === 0) { + throw new Error("A mesh path must have nonzero length."); + } + if (tangents) { + tangents.length = divisions + 1; + } + const adjacent = new Vector3(); + const direction = new Vector3(); + let tangent: Vector3; + let tangentEdge = 0; + let edge = 1; + for (let i = 0; i <= divisions; i++) { + const distance = (i / divisions) * length; + while (edge < lengths.length - 1 && lengths[edge] < distance) { + edge++; + } + const edgeLength = lengths[edge] - lengths[edge - 1]; + const t = edgeLength > 0 ? (distance - lengths[edge - 1]) / edgeLength : 0; + const point = new Vector3(); + Vector3.lerp(points[edge - 1], points[edge], t, point); + result[i] = point; + if (tangents) { + if (tangentEdge !== edge) { + Vector3.subtract(points[edge], points[edge - 1], direction); + MeshPathUtils._normalize(direction); + tangent = MeshPathUtils._normalize(direction.clone()); + tangentEdge = edge; + } + if (t === 0 && (edge > 1 || closed)) { + const previous = points[edge > 1 ? edge - 2 : points.length - 2]; + Vector3.subtract(points[edge - 1], previous, adjacent); + } else if (t === 1 && (edge + 1 < points.length || closed)) { + const next = points[edge + 1 < points.length ? edge + 1 : 1]; + Vector3.subtract(next, points[edge], adjacent); + } else { + tangents[i] = tangent!; + continue; + } + MeshPathUtils._normalize(adjacent).add(direction); + tangents[i] = Vector3.dot(adjacent, adjacent) > 0 ? MeshPathUtils._normalize(adjacent.clone()) : tangent!; + } + } + return result; + } + + static computeFrames( + points: readonly Vector3[], + closed: boolean, + fallbackTangents?: readonly Vector3[] + ): { normals: Vector3[]; binormals: Vector3[] } { + const last = points.length - 1; + const tangents = new Array(points.length); + for (let i = 0; i <= last; i++) { + const before = points[i === 0 ? (closed ? last - 1 : 0) : i - 1]; + const after = points[i === last ? (closed ? 1 : last) : i + 1]; + const tangent = new Vector3(); + Vector3.subtract(after, before, tangent); + if (Vector3.dot(tangent, tangent) === 0 && fallbackTangents) { + tangent.copyFrom(fallbackTangents[i]); + } + tangents[i] = MeshPathUtils._normalize(tangent); + } + const tangent = tangents[0]; + const axis = + Math.abs(tangent.x) <= Math.abs(tangent.y) && Math.abs(tangent.x) <= Math.abs(tangent.z) + ? new Vector3(1, 0, 0) + : Math.abs(tangent.y) <= Math.abs(tangent.z) + ? new Vector3(0, 1, 0) + : new Vector3(0, 0, 1); + const normal = new Vector3(); + const binormal = new Vector3(); + Vector3.cross(tangent, axis, normal); + MeshPathUtils._normalize(normal); + Vector3.cross(tangent, normal, binormal); + MeshPathUtils._normalize(binormal); + const normals = [normal]; + const binormals = [binormal]; + const rotationAxis = new Vector3(); + for (let i = 1; i <= last; i++) { + Vector3.cross(tangents[i - 1], tangents[i], rotationAxis); + const sine = Math.hypot(rotationAxis.x, rotationAxis.y, rotationAxis.z); + let normal = normals[i - 1]; + if (sine > 1e-10) { + normal = MeshPathUtils._rotate( + normal, + MeshPathUtils._normalize(rotationAxis), + Math.atan2(sine, Vector3.dot(tangents[i - 1], tangents[i])), + new Vector3() + ); + } + normals.push(normal); + const binormal = new Vector3(); + Vector3.cross(tangents[i], normal, binormal); + binormals.push(MeshPathUtils._normalize(binormal)); + } + if (closed) { + Vector3.cross(normals[last], normals[0], rotationAxis); + const angle = Math.atan2(Vector3.dot(tangents[0], rotationAxis), Vector3.dot(normals[last], normals[0])); + for (let i = 1; i <= last; i++) { + normals[i] = MeshPathUtils._rotate(normals[i], tangents[i], (angle * i) / last, new Vector3()); + Vector3.cross(tangents[i], normals[i], binormals[i]); + MeshPathUtils._normalize(binormals[i]); + } + } + return { normals, binormals }; + } + + private static _normalize(vector: Vector3): Vector3 { + const length = Math.hypot(vector.x, vector.y, vector.z); + return vector.scale(length > 0 ? 1 / length : 0); + } + + private static _rotate(point: Vector3, axis: Vector3, angle: number, out: Vector3): Vector3 { + const c = Math.cos(angle); + const s = Math.sin(angle); + const px = axis.y * point.z - axis.z * point.y; + const py = axis.z * point.x - axis.x * point.z; + const pz = axis.x * point.y - axis.y * point.x; + const parallel = Vector3.dot(axis, point) * (1 - c); + return out.set( + point.x * c + px * s + axis.x * parallel, + point.y * c + py * s + axis.y * parallel, + point.z * c + pz * s + axis.z * parallel + ); + } +} diff --git a/packages/core/src/mesh/primitive/PolygonUtils.ts b/packages/core/src/mesh/primitive/PolygonUtils.ts new file mode 100644 index 0000000000..30c9187b0f --- /dev/null +++ b/packages/core/src/mesh/primitive/PolygonUtils.ts @@ -0,0 +1,739 @@ +import { Vector2 } from "@galacean/engine-math"; +import type { PolygonShape } from "../PrimitiveMeshOptions"; + +/** + * @internal + */ +export class PolygonUtils { + static prepareContours(shape: PolygonShape): Vector2[][] { + return [shape.points, ...(shape.holes ?? [])].map((points, index) => { + const contour: Vector2[] = []; + for (const point of points) { + const previous = contour[contour.length - 1]; + if (!previous || previous.x !== point.x || previous.y !== point.y) { + contour.push(point); + } + } + const first = contour[0]; + const last = contour[contour.length - 1]; + if (contour.length > 1 && first.x === last.x && first.y === last.y) { + contour.pop(); + } + if (contour.length < 3) { + throw new Error("A mesh contour needs at least three distinct points."); + } + let area = 0; + for (let i = 0; i < contour.length; i++) { + const next = contour[(i + 1) % contour.length]; + area += contour[i].x * next.y - next.x * contour[i].y; + } + if (area > 0 !== (index === 0)) { + contour.reverse(); + } + return contour; + }); + } + + static triangulateContours(contours: Vector2[][]): { points: Vector2[]; indices: number[] } { + const points: Vector2[] = []; + const holes: number[] = []; + for (let i = 0; i < contours.length; i++) { + if (i > 0) { + holes.push(points.length); + } + for (const point of contours[i]) { + points.push(point); + } + } + const coordinates = new Float64Array(points.length * 2); + for (let i = 0; i < points.length; i++) { + coordinates[2 * i] = points[i].x; + coordinates[2 * i + 1] = points[i].y; + } + const indices = PolygonUtils.triangulate(coordinates, holes); + for (let i = 0; i < indices.length; i += 3) { + const a = points[indices[i]]; + const b = points[indices[i + 1]]; + const c = points[indices[i + 2]]; + if ((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) < 0) { + [indices[i + 1], indices[i + 2]] = [indices[i + 2], indices[i + 1]]; + } + } + return { points, indices }; + } + + static triangulate(data: ArrayLike, holeIndices: ArrayLike = []): number[] { + const hasHoles = holeIndices.length > 0; + const outerLen = hasHoles ? holeIndices[0] * 2 : data.length; + let outerNode = PolygonUtils._linkedList(data, 0, outerLen, true); + const triangles: number[] = []; + if (!outerNode || outerNode.next === outerNode.prev) { + return triangles; + } + let minX = 0, + minY = 0, + invSize = 0; + if (hasHoles) { + outerNode = PolygonUtils._eliminateHoles(data, holeIndices, outerNode); + } + // Spatial indexing avoids testing every vertex against each ear in large polygons + if (data.length > 160) { + minX = data[0]; + minY = data[1]; + let maxX = minX; + let maxY = minY; + for (let i = 2; i < outerLen; i += 2) { + const x = data[i]; + const y = data[i + 1]; + if (x < minX) { + minX = x; + } + if (y < minY) { + minY = y; + } + if (x > maxX) { + maxX = x; + } + if (y > maxY) { + maxY = y; + } + } + // Morton codes use 15 bits per coordinate + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + PolygonUtils._earcutLinked(outerNode, triangles, minX, minY, invSize, 0); + return triangles; + } + + private static _linkedList( + data: ArrayLike, + start: number, + end: number, + clockwise: boolean + ): TriangulationNode | null { + let last: TriangulationNode | null = null; + if (clockwise === PolygonUtils._signedArea(data, start, end) > 0) { + for (let i = start; i < end; i += 2) { + last = PolygonUtils._insertNode((i / 2) | 0, data[i], data[i + 1], last); + } + } else { + for (let i = end - 2; i >= start; i -= 2) { + last = PolygonUtils._insertNode((i / 2) | 0, data[i], data[i + 1], last); + } + } + if (last && PolygonUtils._equals(last, last.next)) { + PolygonUtils._removeNode(last); + last = last.next; + } + return last; + } + + private static _filterPoints(start: TriangulationNode, end: TriangulationNode = start): TriangulationNode { + let p = start; + let again: boolean; + do { + again = false; + if (!p.steiner && (PolygonUtils._equals(p, p.next) || PolygonUtils._area(p.prev, p, p.next) === 0)) { + PolygonUtils._removeNode(p); + p = end = p.prev; + if (p === p.next) { + break; + } + again = true; + } else { + p = p.next; + } + } while (again || p !== end); + return end; + } + + private static _earcutLinked( + ear: TriangulationNode, + triangles: number[], + minX: number, + minY: number, + invSize: number, + pass: number + ): void { + if (!pass && invSize) { + PolygonUtils._indexCurve(ear, minX, minY, invSize); + } + let stop = ear; + while (ear.prev !== ear.next) { + const prev = ear.prev; + const next = ear.next; + if (invSize ? PolygonUtils._isEarHashed(ear, minX, minY, invSize) : PolygonUtils._isEar(ear)) { + triangles.push(prev.i, ear.i, next.i); + PolygonUtils._removeNode(ear); + // Skipping the adjacent vertex reduces narrow triangles + ear = next.next; + stop = next.next; + continue; + } + ear = next; + if (ear === stop) { + // Retry after removing degeneracies, then heal intersections or split the ring + if (!pass) { + PolygonUtils._earcutLinked(PolygonUtils._filterPoints(ear), triangles, minX, minY, invSize, 1); + } else if (pass === 1) { + ear = PolygonUtils._cureLocalIntersections(PolygonUtils._filterPoints(ear), triangles); + PolygonUtils._earcutLinked(ear, triangles, minX, minY, invSize, 2); + } else if (pass === 2) { + PolygonUtils._splitEarcut(ear, triangles, minX, minY, invSize); + } + break; + } + } + } + + private static _isEar(ear: TriangulationNode): boolean { + const a = ear.prev, + b = ear, + c = ear.next; + if (PolygonUtils._area(a, b, c) >= 0) { + return false; + } + const ax = a.x, + bx = b.x, + cx = c.x, + ay = a.y, + by = b.y, + cy = c.y; + const x0 = Math.min(ax, bx, cx), + y0 = Math.min(ay, by, cy), + x1 = Math.max(ax, bx, cx), + y1 = Math.max(ay, by, cy); + let p = c.next; + while (p !== a) { + if ( + p.x >= x0 && + p.x <= x1 && + p.y >= y0 && + p.y <= y1 && + PolygonUtils._pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && + PolygonUtils._area(p.prev, p, p.next) >= 0 + ) { + return false; + } + p = p.next; + } + return true; + } + + private static _isEarHashed(ear: TriangulationNode, minX: number, minY: number, invSize: number): boolean { + const a = ear.prev, + b = ear, + c = ear.next; + if (PolygonUtils._area(a, b, c) >= 0) { + return false; + } + const ax = a.x, + bx = b.x, + cx = c.x, + ay = a.y, + by = b.y, + cy = c.y; + const x0 = Math.min(ax, bx, cx), + y0 = Math.min(ay, by, cy), + x1 = Math.max(ax, bx, cx), + y1 = Math.max(ay, by, cy); + const minZ = PolygonUtils._zOrder(x0, y0, minX, minY, invSize), + maxZ = PolygonUtils._zOrder(x1, y1, minX, minY, invSize); + let p = ear.prevZ, + n = ear.nextZ; + while (p && p.z >= minZ && n && n.z <= maxZ) { + if ( + p.x >= x0 && + p.x <= x1 && + p.y >= y0 && + p.y <= y1 && + p !== a && + p !== c && + PolygonUtils._pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && + PolygonUtils._area(p.prev, p, p.next) >= 0 + ) { + return false; + } + p = p.prevZ; + if ( + n.x >= x0 && + n.x <= x1 && + n.y >= y0 && + n.y <= y1 && + n !== a && + n !== c && + PolygonUtils._pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && + PolygonUtils._area(n.prev, n, n.next) >= 0 + ) { + return false; + } + n = n.nextZ; + } + while (p && p.z >= minZ) { + if ( + p.x >= x0 && + p.x <= x1 && + p.y >= y0 && + p.y <= y1 && + p !== a && + p !== c && + PolygonUtils._pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && + PolygonUtils._area(p.prev, p, p.next) >= 0 + ) { + return false; + } + p = p.prevZ; + } + while (n && n.z <= maxZ) { + if ( + n.x >= x0 && + n.x <= x1 && + n.y >= y0 && + n.y <= y1 && + n !== a && + n !== c && + PolygonUtils._pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && + PolygonUtils._area(n.prev, n, n.next) >= 0 + ) { + return false; + } + n = n.nextZ; + } + return true; + } + + private static _cureLocalIntersections(start: TriangulationNode, triangles: number[]): TriangulationNode { + let p = start; + do { + const a = p.prev, + b = p.next.next; + if ( + !PolygonUtils._equals(a, b) && + PolygonUtils._intersects(a, p, p.next, b) && + PolygonUtils._locallyInside(a, b) && + PolygonUtils._locallyInside(b, a) + ) { + triangles.push(a.i, p.i, b.i); + PolygonUtils._removeNode(p); + PolygonUtils._removeNode(p.next); + p = start = b; + } + p = p.next; + } while (p !== start); + return PolygonUtils._filterPoints(p); + } + + private static _splitEarcut( + start: TriangulationNode, + triangles: number[], + minX: number, + minY: number, + invSize: number + ): void { + let a = start; + do { + let b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && PolygonUtils._isValidDiagonal(a, b)) { + let c = PolygonUtils._splitPolygon(a, b); + a = PolygonUtils._filterPoints(a, a.next); + c = PolygonUtils._filterPoints(c, c.next); + PolygonUtils._earcutLinked(a, triangles, minX, minY, invSize, 0); + PolygonUtils._earcutLinked(c, triangles, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); + } + + private static _eliminateHoles( + data: ArrayLike, + holeIndices: ArrayLike, + outerNode: TriangulationNode + ): TriangulationNode { + const queue: TriangulationNode[] = []; + for (let i = 0, len = holeIndices.length; i < len; i++) { + const start = holeIndices[i] * 2; + const end = i < len - 1 ? holeIndices[i + 1] * 2 : data.length; + const list = PolygonUtils._linkedList(data, start, end, false)!; + if (list === list.next) { + list.steiner = true; + } + queue.push(PolygonUtils._getLeftmost(list)); + } + queue.sort(PolygonUtils._compareXYSlope); + for (let i = 0; i < queue.length; i++) { + outerNode = PolygonUtils._eliminateHole(queue[i], outerNode); + } + return outerNode; + } + + private static _compareXYSlope(a: TriangulationNode, b: TriangulationNode): number { + let result = a.x - b.x; + // Touching holes must be bridged in counterclockwise order at their shared vertex + if (result === 0) { + result = a.y - b.y; + if (result === 0) { + const aSlope = (a.next.y - a.y) / (a.next.x - a.x); + const bSlope = (b.next.y - b.y) / (b.next.x - b.x); + result = aSlope - bSlope; + } + } + return result; + } + + private static _eliminateHole(hole: TriangulationNode, outerNode: TriangulationNode): TriangulationNode { + const bridge = PolygonUtils._findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } + const bridgeReverse = PolygonUtils._splitPolygon(bridge, hole); + // Joining rings can introduce collinear vertices on either side of the bridge + PolygonUtils._filterPoints(bridgeReverse, bridgeReverse.next); + return PolygonUtils._filterPoints(bridge, bridge.next); + } + + private static _findHoleBridge(hole: TriangulationNode, outerNode: TriangulationNode): TriangulationNode | null { + let p = outerNode; + const hx = hole.x; + const hy = hole.y; + let qx = -Infinity; + let m: TriangulationNode | null = null; + // Cast left from the hole and choose a visible endpoint on the nearest intersected edge + if (PolygonUtils._equals(hole, p)) { + return p; + } + do { + if (PolygonUtils._equals(hole, p.next)) { + return p.next; + } else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + const x = p.x + ((hy - p.y) * (p.next.x - p.x)) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) { + return m; + } + } + } + p = p.next; + } while (p !== outerNode); + if (!m) { + return null; + } + // A vertex inside the candidate triangle may provide a closer visible bridge + const stop = m; + const mx = m.x; + const my = m.y; + let tanMin = Infinity; + p = m; + do { + if ( + hx >= p.x && + p.x >= mx && + hx !== p.x && + PolygonUtils._pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y) + ) { + const tan = Math.abs(hy - p.y) / (hx - p.x); + if ( + PolygonUtils._locallyInside(p, hole) && + (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && PolygonUtils._sectorContainsSector(m, p))))) + ) { + m = p; + tanMin = tan; + } + } + p = p.next; + } while (p !== stop); + return m; + } + + private static _sectorContainsSector(m: TriangulationNode, p: TriangulationNode): boolean { + return PolygonUtils._area(m.prev, m, p.prev) < 0 && PolygonUtils._area(p.next, m, m.next) < 0; + } + + private static _indexCurve(start: TriangulationNode, minX: number, minY: number, invSize: number): void { + let p = start; + do { + if (p.z === 0) { + p.z = PolygonUtils._zOrder(p.x, p.y, minX, minY, invSize); + } + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + p.prevZ!.nextZ = null; + p.prevZ = null; + PolygonUtils._sortLinked(p); + } + + private static _sortLinked(list: TriangulationNode | null): TriangulationNode | null { + // Bottom-up merge sort keeps the Morton-code list linked without allocating an array + let numMerges: number; + let inSize = 1; + do { + let p = list; + let e: TriangulationNode; + list = null; + let tail: TriangulationNode | null = null; + numMerges = 0; + while (p) { + numMerges++; + let q: TriangulationNode | null = p; + let pSize = 0; + for (let i = 0; i < inSize; i++) { + pSize++; + q = q!.nextZ; + if (!q) { + break; + } + } + let qSize = inSize; + while (pSize > 0 || (qSize > 0 && q)) { + if (pSize !== 0 && (qSize === 0 || !q || p!.z <= q.z)) { + e = p!; + p = p!.nextZ; + pSize--; + } else { + e = q!; + q = q!.nextZ; + qSize--; + } + if (tail) { + tail.nextZ = e; + } else { + list = e; + } + e.prevZ = tail; + tail = e; + } + p = q; + } + tail!.nextZ = null; + inSize *= 2; + } while (numMerges > 1); + return list; + } + + private static _zOrder(x: number, y: number, minX: number, minY: number, invSize: number): number { + x = ((x - minX) * invSize) | 0; + y = ((y - minY) * invSize) | 0; + x = (x | (x << 8)) & 0x00ff00ff; + x = (x | (x << 4)) & 0x0f0f0f0f; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + y = (y | (y << 8)) & 0x00ff00ff; + y = (y | (y << 4)) & 0x0f0f0f0f; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + return x | (y << 1); + } + + private static _getLeftmost(start: TriangulationNode): TriangulationNode { + let p = start, + leftmost = start; + do { + if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) { + leftmost = p; + } + p = p.next; + } while (p !== start); + return leftmost; + } + + private static _pointInTriangle( + ax: number, + ay: number, + bx: number, + by: number, + cx: number, + cy: number, + px: number, + py: number + ): boolean { + return ( + (cx - px) * (ay - py) >= (ax - px) * (cy - py) && + (ax - px) * (by - py) >= (bx - px) * (ay - py) && + (bx - px) * (cy - py) >= (cx - px) * (by - py) + ); + } + + private static _pointInTriangleExceptFirst( + ax: number, + ay: number, + bx: number, + by: number, + cx: number, + cy: number, + px: number, + py: number + ): boolean { + return !(ax === px && ay === py) && PolygonUtils._pointInTriangle(ax, ay, bx, by, cx, cy, px, py); + } + + private static _isValidDiagonal(a: TriangulationNode, b: TriangulationNode): boolean { + return !!( + a.next.i !== b.i && + a.prev.i !== b.i && + !PolygonUtils._intersectsPolygon(a, b) && + ((PolygonUtils._locallyInside(a, b) && + PolygonUtils._locallyInside(b, a) && + PolygonUtils._middleInside(a, b) && + (PolygonUtils._area(a.prev, a, b.prev) || PolygonUtils._area(a, b.prev, b))) || + (PolygonUtils._equals(a, b) && + PolygonUtils._area(a.prev, a, a.next) > 0 && + PolygonUtils._area(b.prev, b, b.next) > 0)) + ); + } + + private static _area(p: TriangulationNode, q: TriangulationNode, r: TriangulationNode): number { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); + } + + private static _equals(p1: TriangulationNode, p2: TriangulationNode): boolean { + return p1.x === p2.x && p1.y === p2.y; + } + + private static _intersects( + p1: TriangulationNode, + q1: TriangulationNode, + p2: TriangulationNode, + q2: TriangulationNode + ): boolean { + const o1 = PolygonUtils._sign(PolygonUtils._area(p1, q1, p2)); + const o2 = PolygonUtils._sign(PolygonUtils._area(p1, q1, q2)); + const o3 = PolygonUtils._sign(PolygonUtils._area(p2, q2, p1)); + const o4 = PolygonUtils._sign(PolygonUtils._area(p2, q2, q1)); + if (o1 !== o2 && o3 !== o4) { + return true; + } + if (o1 === 0 && PolygonUtils._onSegment(p1, p2, q1)) { + return true; + } + if (o2 === 0 && PolygonUtils._onSegment(p1, q2, q1)) { + return true; + } + if (o3 === 0 && PolygonUtils._onSegment(p2, p1, q2)) { + return true; + } + if (o4 === 0 && PolygonUtils._onSegment(p2, q1, q2)) { + return true; + } + return false; + } + + private static _onSegment(p: TriangulationNode, q: TriangulationNode, r: TriangulationNode): boolean { + return ( + q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y) + ); + } + + private static _sign(num: number): number { + return num > 0 ? 1 : num < 0 ? -1 : 0; + } + + private static _intersectsPolygon(a: TriangulationNode, b: TriangulationNode): boolean { + let p = a; + do { + if ( + p.i !== a.i && + p.next.i !== a.i && + p.i !== b.i && + p.next.i !== b.i && + PolygonUtils._intersects(p, p.next, a, b) + ) { + return true; + } + p = p.next; + } while (p !== a); + return false; + } + + private static _locallyInside(a: TriangulationNode, b: TriangulationNode): boolean { + return PolygonUtils._area(a.prev, a, a.next) < 0 + ? PolygonUtils._area(a, b, a.next) >= 0 && PolygonUtils._area(a, a.prev, b) >= 0 + : PolygonUtils._area(a, b, a.prev) < 0 || PolygonUtils._area(a, a.next, b) < 0; + } + + private static _middleInside(a: TriangulationNode, b: TriangulationNode): boolean { + let p = a; + let inside = false; + const px = (a.x + b.x) / 2; + const py = (a.y + b.y) / 2; + do { + if (p.y > py !== p.next.y > py && px < ((p.next.x - p.x) * (py - p.y)) / (p.next.y - p.y) + p.x) { + inside = !inside; + } + p = p.next; + } while (p !== a); + return inside; + } + + private static _splitPolygon(a: TriangulationNode, b: TriangulationNode): TriangulationNode { + const a2 = new TriangulationNode(a.i, a.x, a.y), + b2 = new TriangulationNode(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + a.next = b; + b.prev = a; + a2.next = an; + an.prev = a2; + b2.next = a2; + a2.prev = b2; + bp.next = b2; + b2.prev = bp; + return b2; + } + + private static _insertNode(i: number, x: number, y: number, last: TriangulationNode | null): TriangulationNode { + const p = new TriangulationNode(i, x, y); + if (last) { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; + } + + private static _removeNode(p: TriangulationNode): void { + p.next.prev = p.prev; + p.prev.next = p.next; + if (p.prevZ) { + p.prevZ.nextZ = p.nextZ; + } + if (p.nextZ) { + p.nextZ.prevZ = p.prevZ; + } + } + + private static _signedArea(data: ArrayLike, start: number, end: number): number { + let sum = 0; + for (let i = start, j = end - 2; i < end; i += 2) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; + } +} + +class TriangulationNode { + readonly i: number; + readonly x: number; + readonly y: number; + prev: TriangulationNode = this; + next: TriangulationNode = this; + z: number = 0; + prevZ: TriangulationNode | null = null; + nextZ: TriangulationNode | null = null; + steiner: boolean = false; + + constructor(i: number, x: number, y: number) { + this.i = i; + this.x = x; + this.y = y; + } +} diff --git a/packages/core/src/mesh/primitive/PrimitiveMeshBuilder.ts b/packages/core/src/mesh/primitive/PrimitiveMeshBuilder.ts new file mode 100644 index 0000000000..177260a0d1 --- /dev/null +++ b/packages/core/src/mesh/primitive/PrimitiveMeshBuilder.ts @@ -0,0 +1,112 @@ +import { Vector2, Vector3 } from "@galacean/engine-math"; + +/** + * @internal + */ +export class PrimitiveMeshBuilder { + vertices: Float32Array; + indices: Uint16Array | Uint32Array; + vertexCount = 0; + indexCount = 0; + groups: { start: number; count: number }[] = []; + boundsExtent?: Vector3; + + constructor(vertexCapacity = 0, indexCapacity = 0) { + this.vertices = new Float32Array(vertexCapacity * 8); + this.indices = vertexCapacity > 65535 ? new Uint32Array(indexCapacity) : new Uint16Array(indexCapacity); + } + + addVertex(x: number, y: number, z: number, nx: number, ny: number, nz: number, u: number, v: number): number { + const index = this.vertexCount++; + this._ensureVertexCapacity(this.vertexCount); + const length = Math.hypot(nx, ny, nz); + const inverse = length > 0 ? 1 / length : 0; + const vertices = this.vertices; + const offset = index * 8; + vertices[offset] = x; + vertices[offset + 1] = y; + vertices[offset + 2] = z; + vertices[offset + 3] = nx * inverse; + vertices[offset + 4] = ny * inverse; + vertices[offset + 5] = nz * inverse; + vertices[offset + 6] = u; + vertices[offset + 7] = v; + return index; + } + + addTriangle(a: number, b: number, c: number): void { + this._ensureIndexCapacity(this.indexCount + 3); + this.indices[this.indexCount++] = a; + this.indices[this.indexCount++] = b; + this.indices[this.indexCount++] = c; + } + + addIndex(index: number): void { + this._ensureIndexCapacity(this.indexCount + 1); + this.indices[this.indexCount++] = index; + } + + addGroup(start: number): void { + const count = this.indexCount - start; + if (count > 0) { + this.groups.push({ start, count }); + } + } + + addFace(a: Vector3, b: Vector3, c: Vector3, uvA: Vector2, uvB: Vector2, uvC: Vector2): void { + const abX = b.x - a.x; + const abY = b.y - a.y; + const abZ = b.z - a.z; + const acX = c.x - a.x; + const acY = c.y - a.y; + const acZ = c.z - a.z; + const nx = abY * acZ - abZ * acY; + const ny = abZ * acX - abX * acZ; + const nz = abX * acY - abY * acX; + const start = this.vertexCount; + this.addVertex(a.x, a.y, a.z, nx, ny, nz, uvA.x, uvA.y); + this.addVertex(b.x, b.y, b.z, nx, ny, nz, uvB.x, uvB.y); + this.addVertex(c.x, c.y, c.z, nx, ny, nz, uvC.x, uvC.y); + this.addTriangle(start, start + 1, start + 2); + } + + setData(vertices: Float32Array, indices: Uint16Array | Uint32Array): void { + this.vertices = vertices; + this.indices = indices; + this.vertexCount = vertices.length / 8; + this.indexCount = indices.length; + } + + trim(): void { + if (this.vertices.length !== this.vertexCount * 8) { + this.vertices = this.vertices.subarray(0, this.vertexCount * 8); + } + if (this.indices.length !== this.indexCount) { + this.indices = this.indices.subarray(0, this.indexCount); + } + const IndexArray = this.vertexCount > 65535 ? Uint32Array : Uint16Array; + if (!(this.indices instanceof IndexArray)) { + this.indices = new IndexArray(this.indices); + } + } + + private _ensureVertexCapacity(count: number): void { + if (count * 8 > this.vertices.length) { + const vertices = new Float32Array(Math.max(count * 8, this.vertices.length * 2, 64)); + vertices.set(this.vertices); + this.vertices = vertices; + } + } + + private _ensureIndexCapacity(count: number): void { + const previous = this.indices; + const useUint32 = this.vertexCount > 65535; + if (count > previous.length || (useUint32 && previous instanceof Uint16Array)) { + const capacity = count > previous.length ? Math.max(count, previous.length * 2, 24) : previous.length; + const IndexArray = useUint32 || previous instanceof Uint32Array ? Uint32Array : Uint16Array; + const indices = new IndexArray(capacity); + indices.set(previous); + this.indices = indices; + } + } +} diff --git a/packages/core/src/mesh/primitive/PrimitiveMeshRestorer.ts b/packages/core/src/mesh/primitive/PrimitiveMeshRestorer.ts new file mode 100644 index 0000000000..20207070a9 --- /dev/null +++ b/packages/core/src/mesh/primitive/PrimitiveMeshRestorer.ts @@ -0,0 +1,46 @@ +import { ContentRestorer } from "../../asset/ContentRestorer"; +import { Buffer } from "../../graphic/Buffer"; +import { ModelMesh } from "../ModelMesh"; +import { MeshTangentUtils } from "../MeshTangentUtils"; +import { PrimitiveMeshBuilder } from "./PrimitiveMeshBuilder"; + +/** + * @internal + */ +export class PrimitiveMeshRestorer extends ContentRestorer { + private _vertexBuffer: Buffer; + private _tangentBuffer: Buffer | undefined; + private _indexBuffer: Buffer; + + constructor( + mesh: ModelMesh, + private _generate: (...args: T) => PrimitiveMeshBuilder, + private _args: T + ) { + super(mesh); + this._vertexBuffer = mesh.vertexBufferBindings[0]!.buffer; + this._tangentBuffer = mesh.vertexBufferBindings[1]?.buffer; + this._indexBuffer = mesh._primitive.indexBufferBinding!._buffer; + } + + override restoreContent(): void { + const mesh = this.resource; + const data = this._generate(...this._args); + data.trim(); + for (const binding of mesh.vertexBufferBindings) { + const buffer = binding?.buffer; + if (!buffer) { + continue; + } + if (buffer === this._vertexBuffer) { + buffer.setData(data.vertices); + } else if (buffer === this._tangentBuffer) { + buffer.setData(MeshTangentUtils.calculateTangentsFromBuffer(data.vertices, data.indices)); + } + } + const indexBuffer = mesh._primitive.indexBufferBinding?._buffer; + if (indexBuffer === this._indexBuffer) { + indexBuffer.setData(data.indices); + } + } +} diff --git a/packages/core/src/mesh/primitive/SubdivisionUtils.ts b/packages/core/src/mesh/primitive/SubdivisionUtils.ts new file mode 100644 index 0000000000..2151689843 --- /dev/null +++ b/packages/core/src/mesh/primitive/SubdivisionUtils.ts @@ -0,0 +1,96 @@ +/** + * @internal + */ +export class SubdivisionUtils { + static subdivideQuads( + positions: ArrayLike, + quads: ArrayLike, + iterations: number + ): { positions: Float32Array; quads: Uint32Array } { + let vertexCount = positions.length / 3; + let faceCount = quads.length / 4; + const growth = Math.pow(4, iterations); + // Each pass adds one face point and two shared edge points per quad on a closed surface + const resultPositions = new Float32Array((vertexCount + faceCount * (growth - 1)) * 3); + const resultQuads = new Uint32Array(quads.length * growth); + resultPositions.set(positions); + resultQuads.set(quads); + const maxFaceCount = iterations > 0 ? (faceCount * growth) / 4 : 0; + const facePoints = new Float64Array(maxFaceCount * 3); + const faceEdges = new Uint32Array(maxFaceCount * 4); + const edgePoints = new Float64Array(maxFaceCount * 6); + const edgeIndices = new Uint32Array(maxFaceCount * 2); + const edges = new Map(); + const edgeOrder = [0, 3, 1, 2]; + + for (let iteration = 0; iteration < iterations; iteration++) { + edges.clear(); + let edgeCount = 0; + for (let faceIndex = 0; faceIndex < faceCount; faceIndex++) { + const faceOffset = faceIndex * 4; + const pointOffset = faceIndex * 3; + let x = 0; + let y = 0; + let z = 0; + for (let corner = 0; corner < 4; corner++) { + const offset = 3 * resultQuads[faceOffset + corner]; + x += 0.25 * resultPositions[offset]; + y += 0.25 * resultPositions[offset + 1]; + z += 0.25 * resultPositions[offset + 2]; + } + facePoints[pointOffset] = x; + facePoints[pointOffset + 1] = y; + facePoints[pointOffset + 2] = z; + for (let corner = 0; corner < 4; corner++) { + const a = resultQuads[faceOffset + corner]; + const b = resultQuads[faceOffset + ((corner + 1) % 4)]; + const key = Math.min(a, b) * vertexCount + Math.max(a, b); + let edge = edges.get(key); + if (edge === undefined) { + edge = edgeCount++; + edges.set(key, edge); + edgeIndices[edge] = 0; + edgePoints[edge * 3] = 0.25 * (resultPositions[3 * a] + resultPositions[3 * b]); + edgePoints[edge * 3 + 1] = 0.25 * (resultPositions[3 * a + 1] + resultPositions[3 * b + 1]); + edgePoints[edge * 3 + 2] = 0.25 * (resultPositions[3 * a + 2] + resultPositions[3 * b + 2]); + } + faceEdges[faceOffset + corner] = edge; + edgePoints[edge * 3] += 0.25 * x; + edgePoints[edge * 3 + 1] += 0.25 * y; + edgePoints[edge * 3 + 2] += 0.25 * z; + } + } + + let nextVertexIndex = vertexCount + faceCount; + for (let faceIndex = 0; faceIndex < faceCount; faceIndex++) { + const facePointIndex = vertexCount + faceIndex; + resultPositions[3 * facePointIndex] = facePoints[3 * faceIndex]; + resultPositions[3 * facePointIndex + 1] = facePoints[3 * faceIndex + 1]; + resultPositions[3 * facePointIndex + 2] = facePoints[3 * faceIndex + 2]; + for (let corner = 0; corner < 4; corner++) { + const edge = faceEdges[faceIndex * 4 + edgeOrder[corner]]; + if (edgeIndices[edge] === 0) { + const index = nextVertexIndex++; + edgeIndices[edge] = index; + resultPositions[3 * index] = edgePoints[3 * edge]; + resultPositions[3 * index + 1] = edgePoints[3 * edge + 1]; + resultPositions[3 * index + 2] = edgePoints[3 * edge + 2]; + } + } + } + // Expand backward so the output cannot overwrite an unread input quad + for (let faceIndex = faceCount - 1; faceIndex >= 0; faceIndex--) { + for (let corner = 3; corner >= 0; corner--) { + const offset = 4 * (4 * faceIndex + corner); + resultQuads[offset] = resultQuads[4 * faceIndex + corner]; + resultQuads[offset + 1] = edgeIndices[faceEdges[4 * faceIndex + corner]]; + resultQuads[offset + 2] = vertexCount + faceIndex; + resultQuads[offset + 3] = edgeIndices[faceEdges[4 * faceIndex + ((corner + 3) % 4)]]; + } + } + vertexCount = nextVertexIndex; + faceCount *= 4; + } + return { positions: resultPositions, quads: resultQuads }; + } +} diff --git a/packages/galacean/skills/engine-knowledge/SKILL.md b/packages/galacean/skills/engine-knowledge/SKILL.md index 39c5480215..45beb14d51 100644 --- a/packages/galacean/skills/engine-knowledge/SKILL.md +++ b/packages/galacean/skills/engine-knowledge/SKILL.md @@ -1,22 +1,24 @@ --- name: engine-knowledge -description: "Use when writing Galacean runtime code that needs lifecycle, motion, rendering or resource-ownership behavior beyond API signatures. Includes version-matched Spine and XR guidance." +description: "Use when writing Galacean Scripts for gameplay, runtime state or Engine capabilities not exposed by the host Editor API. Provides cross-API lifecycle, physics, rendering and resource-ownership guidance, including Spine and XR." --- -# Engine Runtime Knowledge +# Engine Script Knowledge -Runtime semantics for the installed `@galacean/engine` and its supported Spine/XR companions. Use each installed package's declarations for exact API names and signatures; reuse declarations already obtained. +Use this skill to compose the installed `@galacean/engine` and its supported Spine/XR APIs in Scripts. It explains runtime behavior and ownership decisions that individual API signatures do not resolve. -In Editor-managed projects, Scripts instantiate and control authored content. Keep persistent, reusable setup in the Editor API. Runtime construction remains appropriate for procedural content, content determined at runtime, or capabilities the host does not expose. Standalone applications own their scene construction. +In Editor-managed projects, use the current host Editor API for supported, persisted scene and asset configuration. Use Scripts for gameplay, runtime state and Engine capabilities the host does not expose, including initialization needed by those behaviors. Standalone Engine applications also own scene initialization. + +Use each installed package's declarations and TSDoc for exact signatures, options, defaults, units and other per-API contracts. Reuse declarations already obtained. ## Read for the current task -Choose the reference for the current runtime decision; follow links only when another behavior affects it. Verify changes with compiler diagnostics and observable runtime behavior. +Read only the reference and sections needed for the current script decision. Follow another reference only when its behavior affects that decision. Verify changes with compiler diagnostics and observable runtime behavior. - Coordinates, transform composition and screen conversion: [coordinates-and-space.md](references/coordinates-and-space.md). - Script activation and frame order: [lifecycle-and-frame-order.md](references/lifecycle-and-frame-order.md). - Motion ownership, fixed steps, collision callbacks and picking: [physics-setup.md](references/physics-setup.md). -- Primitive dimensions and drawable custom geometry: [mesh-geometry.md](references/mesh-geometry.md). +- Script mesh initialization, generation, sharing and vertex updates: [mesh-geometry.md](references/mesh-geometry.md). - Cloning, reference counts and garbage collection: [resource-ownership.md](references/resource-ownership.md). - Materials, color space, cameras, masks, lighting and post-processing: [rendering-and-color.md](references/rendering-and-color.md). - Spine instances, animation state and rendering: [spine.md](references/spine.md). diff --git a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md index 51face621a..ecf9eb1e4b 100644 --- a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md +++ b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md @@ -1,51 +1,67 @@ # Mesh Geometry -Use this reference when primitive dimensions or orientation affect code, or when uploading custom geometry. Material assignment and draw ordering are covered in [rendering-and-color.md](rendering-and-color.md). +Use this reference when Scripts initialize, generate, share or update geometry. Read the installed factory and mesh declarations for exact inputs, units, UV mapping and material-slot order. -The table describes meshes created with omitted size arguments and an entity scale of `(1, 1, 1)`. +## Initialize or generate geometry -| Primitive | Default extent | Local orientation | -| ------------------ | ------------------------------------------------ | ---------------------------- | -| Cuboid | width 1, height 1, depth 1 | centered at the origin | -| Sphere | radius 0.5 | centered at the origin | -| Subdivision sphere | radius 0.5 | centered at the origin | -| Plane | width 1, depth 1 | lies in XZ and faces +Y | -| Cylinder | radius 0.5, height 2 | centered on Y | -| Cone | radius 0.5, height 2 | centered on Y, tip toward +Y | -| Capsule | radius 0.5, cylindrical height 2, total height 3 | centered on Y | -| Torus | major radius 0.5, tube radius 0.1 | lies in XY around the Z axis | +Reuse a configured mesh when its geometry already meets the task. In Editor-managed projects, keep supported, persisted mesh configuration in the Editor API. A Script can create geometry needed by its behavior, including an initial mesh it later deforms or a shape the host API cannot express. Standalone applications also create their initial scene geometry. -## Placement consequences +Create the mesh during initialization when its inputs are already known. Rebuild when shape inputs change, such as a path chosen during play; changing the input array alone does not update a generated primitive. Keep the mesh while its geometry is unchanged, and use Entity transforms for placement, rotation and per-instance scaling. When only vertex attributes change, update them on the existing mesh. -- A centered primitive rests on a horizontal surface when its center is raised by its scaled half-height. -- A default Plane is already horizontal; rotating it as if it were an XY plane changes the intended ground orientation. -- Capsule `height` describes the cylindrical section between hemisphere centers. Total vertical extent also includes both hemispherical radii. -- Non-uniform entity scale changes the rendered bounds after mesh construction. Do not assume one scalar radius still describes the world-space result. +For Script-generated shapes, use `createRevolvedSurface` for a profile rotated around an axis, `createTube` for a circular section following a path, `createPolygon` for a flat contour, and `createExtrudedPolygon` to extend a contour by a depth or along a path. Choose the factory from the intended shape, then consult its declaration for the exact inputs and settings. -## Visual and collision geometry +The following helper generates a tube from a runtime path and assigns it to an existing Renderer whose material is already configured. Call it when the path changes, and reuse the returned mesh if other Renderers should share it. -Primitive meshes and collider shapes own independent dimensions. Their defaults do not guarantee a visual match: for example, a default Sphere mesh has radius `0.5` while a default `SphereColliderShape` has radius `1`; the default Capsule mesh and `CapsuleColliderShape` also use different radii. Collider dimensions are then affected by the Entity's world scale. +```ts +import { MeshRenderer, ModelMesh, PrimitiveMesh, Vector3 } from "@galacean/engine"; + +export function createRuntimeTube(renderer: MeshRenderer, path: readonly Vector3[], radius: number): ModelMesh { + const mesh = PrimitiveMesh.createTube(renderer.engine, path, radius); + renderer.mesh = mesh; + return mesh; +} +``` + +## Share and replace geometry + +Renderers assigned the same mesh share its geometry. Create an independent mesh when one object's geometry must change independently; Entity transforms can still differ between users of a shared mesh. + +When rebuilding changes the sub-mesh layout, update the Renderer's material assignments to match. Retire replaced meshes according to their remaining users and [resource ownership](resource-ownership.md). Material sharing is covered in [rendering-and-color.md](rendering-and-color.md). + +## Update existing vertex data + +Choose readable data when the Script needs to read or edit vertex attributes later. For primitives, request `keepMeshData: true` at creation. After editing a returned attribute array, call its setter and upload the changes; use `uploadData(false)` while further CPU-side edits are needed. + +If topology changes, keep indices and SubMesh draw ranges consistent with the vertex arrays. + +Update bounds after position changes so culling matches the new geometry. Keep normals and tangents consistent with the deformed surface when the material uses them. Retaining readable data alone does not guarantee that runtime edits survive device loss; use the mesh's restoration contract to plan how its runtime state is regenerated. + +## Place geometry and configure collision -Set collider dimensions from the intended collision geometry. Do not infer them from the assigned mesh or assume entity scale repairs a default mismatch. +Compare rendered bounds in a common space when aligning runtime pieces. To align a piece's bounds with horizontal ground, calculate the vertical offset from its world-space `Renderer.bounds.min.y` to the ground's world Y, and apply that offset to the Entity's world position. These bounds already account for the mesh origin and Entity transforms. -Exact constructor arguments remain declaration-owned. Use this page only for the default spatial semantics that are easy to misremember. +Meshes and collider shapes have independent dimensions: assigning a mesh does not configure its collider. Set collision dimensions from the intended geometry, accounting for Entity scale. See [physics-setup.md](physics-setup.md) for collision and picking. -## Draw-ready custom mesh +## Supply custom vertex geometry -Use this example for procedural geometry created during execution. The caller supplies a Renderer with its material already configured. Fixed geometry and reusable templates are normally authored assets. Vertex data alone is not drawable: the Mesh still needs bounds, an index range and a SubMesh. See [rendering-and-color.md](rendering-and-color.md). +Use `ModelMesh` when the Script supplies vertices and topology. A drawable mesh also needs uploaded data, bounds and a SubMesh draw range. The helper below binds Script-generated triangle geometry to an existing Renderer and retains readable data for later edits. It assumes nonempty, valid triangle data and an unlit, untextured material; supply any additional attributes required by other materials. ```ts -import { Engine, MeshRenderer, ModelMesh, Vector3 } from "@galacean/engine"; +import { BoundingBox, MeshRenderer, ModelMesh, Vector3 } from "@galacean/engine"; -export function createTriangle(engine: Engine, renderer: MeshRenderer): void { - const mesh = new ModelMesh(engine); - mesh.setPositions([new Vector3(-0.5, -0.5, 0), new Vector3(0.5, -0.5, 0), new Vector3(0, 0.5, 0)]); - mesh.setIndices(new Uint16Array([0, 1, 2])); - mesh.bounds.min.set(-0.5, -0.5, -0.001); - mesh.bounds.max.set(0.5, 0.5, 0.001); - mesh.uploadData(true); - mesh.addSubMesh(0, 3); +export function createRuntimeMesh( + renderer: MeshRenderer, + positions: Vector3[], + indices: Uint16Array | Uint32Array +): ModelMesh { + const mesh = new ModelMesh(renderer.engine); + mesh.setPositions(positions); + mesh.setIndices(indices); + BoundingBox.fromPoints(positions, mesh.bounds); + mesh.addSubMesh(0, indices.length); + mesh.uploadData(false); renderer.mesh = mesh; + return mesh; } ``` diff --git a/packages/loader/src/PrimitiveMeshAsset.ts b/packages/loader/src/PrimitiveMeshAsset.ts new file mode 100644 index 0000000000..99711e23b0 --- /dev/null +++ b/packages/loader/src/PrimitiveMeshAsset.ts @@ -0,0 +1,285 @@ +import type { + CapsuleMeshOptions, + CircleMeshOptions, + ConeMeshOptions, + CuboidMeshOptions, + CylinderMeshOptions, + LinearExtrudedPolygonMeshOptions, + PathExtrudedPolygonMeshOptions, + PlaneMeshOptions, + PolygonMeshOptions, + PolygonShape, + RegularPolyhedronMeshOptions, + RevolvedSurfaceMeshOptions, + RingMeshOptions, + RoundedCuboidMeshOptions, + SphereMeshOptions, + TorusKnotMeshOptions, + TorusMeshOptions, + TruncatedConeMeshOptions, + TubeMeshOptions +} from "@galacean/engine-core"; +import type { Vector2, Vector3 } from "@galacean/engine-math"; + +/** + * @internal + */ +export type SerializedPrimitiveMeshData = { + [Key in keyof T]: SerializedPrimitiveMeshValue; +}; + +type SerializedPrimitiveMeshValue = T extends Vector2 | Vector3 + ? ReturnType + : T extends object + ? SerializedPrimitiveMeshData + : T; + +/** + * Serialized inputs and optional settings for every primitive mesh factory. + * Required inputs use the same units as factory arguments. Vector inputs store their components as plain JSON objects. + */ +export type PrimitiveMeshAsset = + | { + type: "sphere"; + /** + * The radius in local units. + */ + sphereRadius: number; + sphereOptions?: SerializedPrimitiveMeshData; + } + | { + type: "cuboid"; + /** + * The full size along X in local units. + */ + cuboidWidth: number; + /** + * The full size along Y in local units. + */ + cuboidHeight: number; + /** + * The full size along Z in local units. + */ + cuboidDepth: number; + cuboidOptions?: CuboidMeshOptions; + } + | { + type: "plane"; + /** + * The full size along X in local units. + */ + planeWidth: number; + /** + * The full size along Z in local units. + */ + planeDepth: number; + planeOptions?: PlaneMeshOptions; + } + | { + type: "cylinder"; + /** + * The radius in local units. + */ + cylinderRadius: number; + /** + * The full size along Y in local units. + */ + cylinderHeight: number; + cylinderOptions?: SerializedPrimitiveMeshData; + } + | { + type: "truncatedCone"; + /** + * The top radius in local units. + */ + truncatedConeTopRadius: number; + /** + * The bottom radius in local units. + */ + truncatedConeBottomRadius: number; + /** + * The full size along Y in local units. + */ + truncatedConeHeight: number; + truncatedConeOptions?: SerializedPrimitiveMeshData; + } + | { + type: "cone"; + /** + * The bottom radius in local units. + */ + coneRadius: number; + /** + * The full size along Y in local units. + */ + coneHeight: number; + coneOptions?: SerializedPrimitiveMeshData; + } + | { + type: "capsule"; + /** + * The radius of the cylinder and hemispherical ends in local units. + */ + capsuleRadius: number; + /** + * The straight cylindrical section height in local units; total height is `capsuleCylinderHeight + 2 * capsuleRadius`. + */ + capsuleCylinderHeight: number; + capsuleOptions?: CapsuleMeshOptions; + } + | { + type: "torus"; + /** + * The distance from the origin to the tube centerline in local units. + */ + torusRadius: number; + /** + * The radius of the tube cross-section in local units. + */ + torusTubeRadius: number; + torusOptions?: SerializedPrimitiveMeshData; + } + | { + type: "circle"; + /** + * The radius in local units. + */ + circleRadius: number; + circleOptions?: SerializedPrimitiveMeshData; + } + | { + type: "ring"; + /** + * The outer radius in local units. + */ + ringOuterRadius: number; + /** + * The inner radius in local units. + */ + ringInnerRadius: number; + ringOptions?: SerializedPrimitiveMeshData; + } + | { + type: "tetrahedron"; + /** + * The distance from the origin to each vertex in local units. + */ + tetrahedronRadius: number; + tetrahedronOptions?: RegularPolyhedronMeshOptions; + } + | { + type: "octahedron"; + /** + * The distance from the origin to each vertex in local units. + */ + octahedronRadius: number; + octahedronOptions?: RegularPolyhedronMeshOptions; + } + | { + type: "icosahedron"; + /** + * The distance from the origin to each vertex in local units. + */ + icosahedronRadius: number; + icosahedronOptions?: RegularPolyhedronMeshOptions; + } + | { + type: "dodecahedron"; + /** + * The distance from the origin to each vertex in local units. + */ + dodecahedronRadius: number; + dodecahedronOptions?: RegularPolyhedronMeshOptions; + } + | { + type: "revolvedSurface"; + /** + * The profile points in local units; x is the radius from the Y axis and y is the height. + */ + revolvedSurfaceProfile: SerializedPrimitiveMeshData; + revolvedSurfaceOptions?: SerializedPrimitiveMeshData; + } + | { + type: "tube"; + /** + * The centerline points in local coordinates. + */ + tubePath: SerializedPrimitiveMeshData; + /** + * The radius of the cross-section in local units. + */ + tubeRadius: number; + tubeOptions?: TubeMeshOptions; + } + | { + type: "polygon"; + /** + * The polygons in the XY plane, including any holes. + */ + polygonShapes: readonly SerializedPrimitiveMeshData[]; + polygonOptions?: PolygonMeshOptions; + } + | { + type: "extrudedPolygon"; + /** + * The total extrusion depth in local units, including both bevels. + */ + extrudedPolygonDepth: number; + /** + * The cross-section contours and optional holes in local XY coordinates. + */ + extrudedPolygonShapes: readonly SerializedPrimitiveMeshData[]; + extrudedPolygonOptions?: LinearExtrudedPolygonMeshOptions; + } + | { + type: "extrudedPolygon"; + /** + * The path points in local coordinates. + */ + extrudedPolygonPath: SerializedPrimitiveMeshData; + /** + * The cross-section contours and optional holes in local XY coordinates. + */ + extrudedPolygonShapes: readonly SerializedPrimitiveMeshData[]; + extrudedPolygonOptions?: PathExtrudedPolygonMeshOptions; + } + | { + type: "torusKnot"; + /** + * The base radius of the torus in local units. + */ + torusKnotRadius: number; + /** + * The radius of the tube cross-section in local units. + */ + torusKnotTubeRadius: number; + /** + * The signed integer revolution count around the torus axis. + */ + torusKnotAxisTurns: number; + /** + * The signed integer revolution count around the torus cross-section. + */ + torusKnotCrossSectionTurns: number; + torusKnotOptions?: TorusKnotMeshOptions; + } + | { + type: "roundedCuboid"; + /** + * The full size along X in local units. + */ + roundedCuboidWidth: number; + /** + * The full size along Y in local units. + */ + roundedCuboidHeight: number; + /** + * The full size along Z in local units. + */ + roundedCuboidDepth: number; + /** + * The edge and corner radius in local units, clamped to half the smallest dimension. + */ + roundedCuboidCornerRadius: number; + roundedCuboidOptions?: RoundedCuboidMeshOptions; + }; diff --git a/packages/loader/src/PrimitiveMeshLoader.ts b/packages/loader/src/PrimitiveMeshLoader.ts index 4f98fa25b5..424857344e 100644 --- a/packages/loader/src/PrimitiveMeshLoader.ts +++ b/packages/loader/src/PrimitiveMeshLoader.ts @@ -1,115 +1,166 @@ import { AssetPromise, AssetType, + Engine, LoadItem, Loader, ModelMesh, + PolygonShape, PrimitiveMesh, ResourceManager, resourceLoader } from "@galacean/engine-core"; +import { Vector2, Vector3 } from "@galacean/engine-math"; +import type { PrimitiveMeshAsset, SerializedPrimitiveMeshData } from "./PrimitiveMeshAsset"; @resourceLoader(AssetType.PrimitiveMesh, ["mesh"], false) class PrimitiveMeshLoader extends Loader { load(item: LoadItem, resourceManager: ResourceManager): AssetPromise { - const { engine } = resourceManager; return resourceManager - ._request(item.url!, { - ...item, - type: "json" - }) - .then((data) => { - switch (data.type) { - case PrimitiveMeshType.Sphere: - return PrimitiveMesh.createSubdivisionSurfaceSphere(engine, data.sphereRadius, data.sphereStep); - case PrimitiveMeshType.Capsule: - return PrimitiveMesh.createCapsule( - engine, - data.capsuleRadius, - data.capsuleHeight, - data.capsuleRadialSegments, - data.capsuleHeightSegments - ); - case PrimitiveMeshType.Cone: - return PrimitiveMesh.createCone( - engine, - data.coneRadius, - data.coneHeight, - data.coneRadialSegment, - data.coneHeightSegment - ); - case PrimitiveMeshType.Cuboid: - return PrimitiveMesh.createCuboid(engine, data.cuboidWidth, data.cuboidHeight, data.cuboidDepth); - case PrimitiveMeshType.Cylinder: - return PrimitiveMesh.createCylinder( - engine, - data.cylinderRadiusTop, - data.cylinderRadiusBottom, - data.cylinderHeight, - data.cylinderRadialSegment, - data.cylinderHeightSegment - ); - case PrimitiveMeshType.Plane: - return PrimitiveMesh.createPlane( - engine, - data.planeWidth, - data.planeHeight, - data.planeHorizontalSegments, - data.planeVerticalSegments - ); - case PrimitiveMeshType.Torus: - return PrimitiveMesh.createTorus( - engine, - data.torusRadius, - data.torusTubeRadius, - data.torusRadialSegments, - data.torusTubularSegments, - data.torusArc - ); + ._request(item.url!, { ...item, type: "json" }) + .then((data) => this._createPrimitiveMesh(resourceManager.engine, data)); + } + + private _createPrimitiveMesh(engine: Engine, data: PrimitiveMeshAsset): ModelMesh { + const { type } = data; + switch (type) { + case "sphere": + return PrimitiveMesh.createSphere(engine, data.sphereRadius, this._parseRangeOptions(data.sphereOptions)); + case "cuboid": + return PrimitiveMesh.createCuboid( + engine, + data.cuboidWidth, + data.cuboidHeight, + data.cuboidDepth, + data.cuboidOptions + ); + case "plane": + return PrimitiveMesh.createPlane(engine, data.planeWidth, data.planeDepth, data.planeOptions); + case "cylinder": + return PrimitiveMesh.createCylinder( + engine, + data.cylinderRadius, + data.cylinderHeight, + this._parseRangeOptions(data.cylinderOptions) + ); + case "truncatedCone": + return PrimitiveMesh.createTruncatedCone( + engine, + data.truncatedConeTopRadius, + data.truncatedConeBottomRadius, + data.truncatedConeHeight, + this._parseRangeOptions(data.truncatedConeOptions) + ); + case "cone": + return PrimitiveMesh.createCone( + engine, + data.coneRadius, + data.coneHeight, + this._parseRangeOptions(data.coneOptions) + ); + case "capsule": + return PrimitiveMesh.createCapsule(engine, data.capsuleRadius, data.capsuleCylinderHeight, data.capsuleOptions); + case "torus": + return PrimitiveMesh.createTorus( + engine, + data.torusRadius, + data.torusTubeRadius, + this._parseRangeOptions(data.torusOptions) + ); + case "circle": + return PrimitiveMesh.createCircle(engine, data.circleRadius, this._parseRangeOptions(data.circleOptions)); + case "ring": + return PrimitiveMesh.createRing( + engine, + data.ringOuterRadius, + data.ringInnerRadius, + this._parseRangeOptions(data.ringOptions) + ); + case "tetrahedron": + return PrimitiveMesh.createTetrahedron(engine, data.tetrahedronRadius, data.tetrahedronOptions); + case "octahedron": + return PrimitiveMesh.createOctahedron(engine, data.octahedronRadius, data.octahedronOptions); + case "icosahedron": + return PrimitiveMesh.createIcosahedron(engine, data.icosahedronRadius, data.icosahedronOptions); + case "dodecahedron": + return PrimitiveMesh.createDodecahedron(engine, data.dodecahedronRadius, data.dodecahedronOptions); + case "revolvedSurface": + return PrimitiveMesh.createRevolvedSurface( + engine, + this._parseVector2s(data.revolvedSurfaceProfile), + this._parseRangeOptions(data.revolvedSurfaceOptions) + ); + case "tube": + return PrimitiveMesh.createTube(engine, this._parseVector3s(data.tubePath), data.tubeRadius, data.tubeOptions); + case "polygon": + return PrimitiveMesh.createPolygon(engine, this._parseShapes(data.polygonShapes), data.polygonOptions); + case "extrudedPolygon": + if ("extrudedPolygonPath" in data) { + return PrimitiveMesh.createExtrudedPolygon( + engine, + this._parseShapes(data.extrudedPolygonShapes), + this._parseVector3s(data.extrudedPolygonPath), + data.extrudedPolygonOptions + ); } - }); + return PrimitiveMesh.createExtrudedPolygon( + engine, + this._parseShapes(data.extrudedPolygonShapes), + data.extrudedPolygonDepth, + data.extrudedPolygonOptions + ); + case "torusKnot": + return PrimitiveMesh.createTorusKnot( + engine, + data.torusKnotRadius, + data.torusKnotTubeRadius, + data.torusKnotAxisTurns, + data.torusKnotCrossSectionTurns, + data.torusKnotOptions + ); + case "roundedCuboid": + return PrimitiveMesh.createRoundedCuboid( + engine, + data.roundedCuboidWidth, + data.roundedCuboidHeight, + data.roundedCuboidDepth, + data.roundedCuboidCornerRadius, + data.roundedCuboidOptions + ); + default: { + const unsupportedType: never = type; + throw new Error(`Unknown primitive mesh type: ${unsupportedType}`); + } + } } -} -/** @internal */ -enum PrimitiveMeshType { - Sphere = "sphere", - Cuboid = "cuboid", - Plane = "plane", - Cylinder = "cylinder", - Torus = "torus", - Cone = "cone", - Capsule = "capsule" -} + private _parseRangeOptions(options: SerializedPrimitiveMeshData | undefined): T | undefined { + if (!options) { + return; + } + let result: T | undefined; + for (const key in options) { + const value: unknown = options[key]; + if (value && typeof value === "object") { + const range = value as { x: number; y: number }; + (result ??= { ...options } as T)[key] = new Vector2(range.x, range.y) as T[typeof key]; + } + } + return result ?? (options as T); + } -/** @internal */ -type IPrimitiveMesh = { - type: PrimitiveMeshType; - sphereRadius: number; - sphereStep: number; - capsuleRadius: number; - capsuleHeight: number; - capsuleRadialSegments: number; - capsuleHeightSegments: number; - coneRadius: number; - coneHeight: number; - coneRadialSegment: number; - coneHeightSegment: number; - cuboidWidth: number; - cuboidHeight: number; - cuboidDepth: number; - cylinderRadiusTop: number; - cylinderRadiusBottom: number; - cylinderHeight: number; - cylinderRadialSegment: number; - cylinderHeightSegment: number; - planeWidth: number; - planeHeight: number; - planeHorizontalSegments: number; - planeVerticalSegments: number; - torusRadius: number; - torusTubeRadius: number; - torusRadialSegments: number; - torusTubularSegments: number; - torusArc: number; -}; + private _parseVector2s(points: SerializedPrimitiveMeshData): Vector2[] { + return points.map(({ x, y }) => new Vector2(x, y)); + } + + private _parseVector3s(points: SerializedPrimitiveMeshData): Vector3[] { + return points.map(({ x, y, z }) => new Vector3(x, y, z)); + } + + private _parseShapes(shapes: readonly SerializedPrimitiveMeshData[]): PolygonShape[] { + return shapes.map(({ points, holes }) => ({ + points: this._parseVector2s(points), + holes: holes?.map((hole) => this._parseVector2s(hole)) + })); + } +} diff --git a/packages/loader/src/index.ts b/packages/loader/src/index.ts index 58381544c9..0b487b9937 100644 --- a/packages/loader/src/index.ts +++ b/packages/loader/src/index.ts @@ -27,6 +27,7 @@ export { GLTFLoader } from "./GLTFLoader"; export type { GLTFParams } from "./GLTFLoader"; import "./SceneLoader"; export type { TextureParams } from "./TextureLoader"; +export type { PrimitiveMeshAsset } from "./PrimitiveMeshAsset"; export { parseSingleKTX } from "./compressed-texture"; export * from "./gltf"; export { KTX2Loader } from "./ktx2/KTX2Loader"; diff --git a/tests/package-consumer/PrimitiveMeshApi.test.ts b/tests/package-consumer/PrimitiveMeshApi.test.ts new file mode 100644 index 0000000000..6c83e6cf63 --- /dev/null +++ b/tests/package-consumer/PrimitiveMeshApi.test.ts @@ -0,0 +1,109 @@ +import { fileURLToPath } from "node:url"; +import ts from "typescript"; +import { expect, it } from "vitest"; + +it.each(["PrimitiveMeshApi", "PrimitiveMeshAsset"])("type-checks %s and rejects invalid inputs", (name) => { + const fixture = fileURLToPath(new URL(`./fixtures/${name}.ts`, import.meta.url)); + const program = ts.createProgram([fixture], { + noEmit: true, + strict: true, + skipLibCheck: true, + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Node10 + }); + const diagnostics = ts.getPreEmitDiagnostics(program).map((diagnostic) => { + const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); + const line = + diagnostic.file && diagnostic.start !== undefined + ? diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start).line + 1 + : 0; + return `${line}: ${message}`; + }); + expect(diagnostics).toEqual([]); + + if (name === "PrimitiveMeshApi") { + const source = program.getSourceFile(fixture)!; + const checker = program.getTypeChecker(); + const meshes = source.statements + .filter(ts.isVariableStatement) + .flatMap((statement) => Array.from(statement.declarationList.declarations)) + .find((declaration) => declaration.name.getText(source) === "meshes"); + if (!meshes?.initializer || !ts.isArrayLiteralExpression(meshes.initializer)) { + throw new Error("PrimitiveMeshApi must list its valid calls in the meshes array."); + } + const calls = meshes.initializer.elements.filter(ts.isCallExpression); + const constructor = (calls[0].expression as ts.PropertyAccessExpression).expression; + const factories = checker + .getTypeAtLocation(constructor) + .getProperties() + .filter((property) => property.name.startsWith("create")); + + for (const factory of factories) { + const signatures = checker.getTypeOfSymbolAtLocation(factory, source).getCallSignatures(); + expect(signatures, `Unexpected overload count: ${factory.name}`).toHaveLength( + factory.name === "createExtrudedPolygon" ? 2 : 1 + ); + const examples = calls.filter( + (call) => ts.isPropertyAccessExpression(call.expression) && call.expression.name.text === factory.name + ); + for (const signature of signatures) { + const overloadExamples = examples.filter( + (call) => checker.getResolvedSignature(call)?.getDeclaration() === signature.getDeclaration() + ); + expect( + overloadExamples.length, + `Missing overload example: ${factory.name}${checker.signatureToString(signature)}` + ).toBeGreaterThan(0); + + const optionsIndex = signature.getParameters().findIndex((parameter) => parameter.name === "options"); + const optionsType = checker.getNonNullableType( + checker.getTypeOfSymbolAtLocation(signature.getParameters()[optionsIndex], source) + ); + const optionTypes = optionsType.isUnion() ? optionsType.types : [optionsType]; + const inputNames = signature + .getParameters() + .slice(0, optionsIndex) + .map((parameter) => parameter.name); + for (const parameter of signature.getDeclaration()!.parameters.slice(0, optionsIndex)) { + expect( + parameter.questionToken, + `Optional core input: ${factory.name}.${parameter.name.getText()}` + ).toBeUndefined(); + expect( + parameter.initializer, + `Default core input: ${factory.name}.${parameter.name.getText()}` + ).toBeUndefined(); + } + const documentedFields = new Set( + overloadExamples.flatMap((call) => { + const options = call.arguments[optionsIndex]; + return options + ? checker + .getTypeAtLocation(options) + .getProperties() + .map((field) => field.name) + : []; + }) + ); + for (const type of optionTypes) { + for (const field of type.getProperties()) { + expect(field.flags & ts.SymbolFlags.Optional, `Required option: ${factory.name}.${field.name}`).not.toBe(0); + expect(inputNames.includes(field.name), `Duplicated core input: ${factory.name}.${field.name}`).toBe(false); + expect(documentedFields.has(field.name), `Missing option example: ${factory.name}.${field.name}`).toBe( + true + ); + } + } + const parameters = signature.getDeclaration()!.parameters; + const minimum = parameters.filter((parameter) => !parameter.questionToken && !parameter.initializer).length; + for (let count = minimum; count <= parameters.length; count++) { + expect( + overloadExamples.some((call) => call.arguments.length === count), + `Missing optional-argument example: ${factory.name}${checker.signatureToString(signature)} with ${count} arguments` + ).toBe(true); + } + } + } + } +}); diff --git a/tests/package-consumer/fixtures/PrimitiveMeshApi.ts b/tests/package-consumer/fixtures/PrimitiveMeshApi.ts new file mode 100644 index 0000000000..76ed7b2ed2 --- /dev/null +++ b/tests/package-consumer/fixtures/PrimitiveMeshApi.ts @@ -0,0 +1,345 @@ +import { Engine, ModelMesh, PolygonShape, PrimitiveMesh, PrimitiveMeshCapMode } from "../../../packages/core/types"; +import type { + CapsuleMeshOptions, + CircleMeshOptions, + ConeMeshOptions, + CuboidMeshOptions, + CylinderMeshOptions, + LinearExtrudedPolygonMeshOptions, + PathExtrudedPolygonMeshOptions, + PlaneMeshOptions, + PolygonMeshOptions, + PrimitiveMeshOptions, + RegularPolyhedronMeshOptions, + RevolvedSurfaceMeshOptions, + RingMeshOptions, + RoundedCuboidMeshOptions, + SphereMeshOptions, + TorusKnotMeshOptions, + TorusMeshOptions, + TruncatedConeMeshOptions, + TubeMeshOptions +} from "../../../packages/galacean/types"; +import { Vector2, Vector3 } from "../../../packages/math/types"; + +declare const engine: Engine; + +const contour: readonly Vector2[] = [new Vector2(-1, -1), new Vector2(1, -1), new Vector2(1, 1), new Vector2(-1, 1)]; +const hole: readonly Vector2[] = [ + new Vector2(-0.5, -0.5), + new Vector2(-0.5, 0.5), + new Vector2(0.5, 0.5), + new Vector2(0.5, -0.5) +]; +const polygon: PolygonShape = { points: contour, holes: [hole] }; +const polygons: readonly PolygonShape[] = [polygon, { points: contour }]; +const profile: readonly Vector2[] = [new Vector2(0.25, -1), new Vector2(1, 0), new Vector2(0.5, 1)]; +const path: readonly Vector3[] = [new Vector3(0, 0, 0), new Vector3(0, 1, 1), new Vector3(1, 2, 2)]; + +const commonOptions = { keepMeshData: true } satisfies PrimitiveMeshOptions; +const sphereOptions = { + subdivisionLevel: 4, + horizontalAngleRange: new Vector2(350, 370), + verticalAngleRange: new Vector2(30, 150), + keepMeshData: true +} satisfies SphereMeshOptions; +const cuboidOptions = { + widthSegments: 2, + heightSegments: 3, + depthSegments: 4, + separateMaterialSlots: true, + keepMeshData: true +} satisfies CuboidMeshOptions; +const planeOptions = { widthSegments: 4, depthSegments: 2, keepMeshData: true } satisfies PlaneMeshOptions; +const cylinderOptions = { + radialSegments: 32, + heightSegments: 4, + caps: PrimitiveMeshCapMode.Bottom, + angleRange: new Vector2(0, 270), + separateMaterialSlots: true, + keepMeshData: true +} satisfies CylinderMeshOptions; +const truncatedConeOptions = { + radialSegments: 32, + heightSegments: 4, + caps: PrimitiveMeshCapMode.None, + angleRange: new Vector2(0, 270), + separateMaterialSlots: true, + keepMeshData: true +} satisfies TruncatedConeMeshOptions; +const coneOptions = { + radialSegments: 32, + heightSegments: 4, + cap: false, + angleRange: new Vector2(0, 270), + separateMaterialSlots: true, + keepMeshData: true +} satisfies ConeMeshOptions; +const capsuleOptions = { + radialSegments: 12, + capSegments: 6, + heightSegments: 3, + keepMeshData: true +} satisfies CapsuleMeshOptions; +const torusOptions = { + ringSegments: 64, + radialSegments: 16, + ringAngleRange: new Vector2(0, 270), + tubeAngleRange: new Vector2(0, 180), + keepMeshData: true +} satisfies TorusMeshOptions; +const circleOptions = { segments: 32, angleRange: new Vector2(0, 180), keepMeshData: true } satisfies CircleMeshOptions; +const ringOptions = { + ringSegments: 32, + widthSegments: 4, + angleRange: new Vector2(0, 270), + keepMeshData: true +} satisfies RingMeshOptions; +const regularPolyhedronOptions = { edgeSegments: 2, keepMeshData: true } satisfies RegularPolyhedronMeshOptions; +const revolvedSurfaceOptions = { + segments: 32, + angleRange: new Vector2(0, 270), + keepMeshData: true +} satisfies RevolvedSurfaceMeshOptions; +const tubeOptions = { + pathSegments: 64, + radialSegments: 8, + closedPath: true, + keepMeshData: true +} satisfies TubeMeshOptions; +const polygonOptions = { separateMaterialSlots: true, keepMeshData: true } satisfies PolygonMeshOptions; +const linearExtrudedPolygonOptions = { + depthSegments: 4, + bevelWidth: 0.1, + bevelDepth: 0.2, + contourOffset: 0.1, + bevelSegments: 3, + separateMaterialSlots: true, + keepMeshData: true +} satisfies LinearExtrudedPolygonMeshOptions; +const torusKnotOptions = { pathSegments: 64, radialSegments: 12, keepMeshData: true } satisfies TorusKnotMeshOptions; +const roundedCuboidOptions = { + roundingSegments: 4, + separateMaterialSlots: true, + keepMeshData: true +} satisfies RoundedCuboidMeshOptions; +const pathExtrudedPolygonOptions = { + pathSegments: 32, + closedPath: true, + separateMaterialSlots: true, + keepMeshData: true +} satisfies PathExtrudedPolygonMeshOptions; +const extrudedPolygonOptions: LinearExtrudedPolygonMeshOptions | PathExtrudedPolygonMeshOptions = + pathExtrudedPolygonOptions; + +// Every factory lists its required inputs and a configuration containing all optional fields +const meshes: ModelMesh[] = [ + PrimitiveMesh.createSphere(engine, 0.5), + PrimitiveMesh.createSphere(engine, 1, sphereOptions), + PrimitiveMesh.createCuboid(engine, 1, 1, 1), + PrimitiveMesh.createCuboid(engine, 2, 3, 4, cuboidOptions), + PrimitiveMesh.createPlane(engine, 1, 1), + PrimitiveMesh.createPlane(engine, 10, 5, planeOptions), + PrimitiveMesh.createCylinder(engine, 0.5, 2), + PrimitiveMesh.createCylinder(engine, 1, 2, cylinderOptions), + PrimitiveMesh.createTruncatedCone(engine, 0.25, 0.5, 2), + PrimitiveMesh.createTruncatedCone(engine, 0.5, 1, 2, truncatedConeOptions), + PrimitiveMesh.createCone(engine, 0.5, 2), + PrimitiveMesh.createCone(engine, 1, 2, coneOptions), + PrimitiveMesh.createCapsule(engine, 0.5, 2), + PrimitiveMesh.createCapsule(engine, 0.5, 2, capsuleOptions), + PrimitiveMesh.createTorus(engine, 0.5, 0.1), + PrimitiveMesh.createTorus(engine, 1, 0.2, torusOptions), + PrimitiveMesh.createCircle(engine, 0.5), + PrimitiveMesh.createCircle(engine, 1, circleOptions), + PrimitiveMesh.createRing(engine, 0.5, 0.25), + PrimitiveMesh.createRing(engine, 1, 0.5, ringOptions), + PrimitiveMesh.createTetrahedron(engine, 0.5), + PrimitiveMesh.createTetrahedron(engine, 1, regularPolyhedronOptions), + PrimitiveMesh.createOctahedron(engine, 0.5), + PrimitiveMesh.createOctahedron(engine, 1, regularPolyhedronOptions), + PrimitiveMesh.createIcosahedron(engine, 0.5), + PrimitiveMesh.createIcosahedron(engine, 1, regularPolyhedronOptions), + PrimitiveMesh.createDodecahedron(engine, 0.5), + PrimitiveMesh.createDodecahedron(engine, 1, regularPolyhedronOptions), + PrimitiveMesh.createRevolvedSurface(engine, profile), + PrimitiveMesh.createRevolvedSurface(engine, profile, revolvedSurfaceOptions), + PrimitiveMesh.createTube(engine, path, 0.5), + PrimitiveMesh.createTube(engine, path, 0.1, tubeOptions), + PrimitiveMesh.createPolygon(engine, contour), + PrimitiveMesh.createPolygon(engine, contour, polygonOptions), + PrimitiveMesh.createExtrudedPolygon(engine, contour, 1), + PrimitiveMesh.createExtrudedPolygon(engine, contour, 2, linearExtrudedPolygonOptions), + PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2, 3), + PrimitiveMesh.createTorusKnot(engine, 1, 0.2, 2, 3, torusKnotOptions), + PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.1), + PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0.2, roundedCuboidOptions), + PrimitiveMesh.createPolygon(engine, polygon), + PrimitiveMesh.createPolygon(engine, polygon, polygonOptions), + PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2), + PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, linearExtrudedPolygonOptions), + PrimitiveMesh.createPolygon(engine, polygons), + PrimitiveMesh.createPolygon(engine, polygons, polygonOptions), + PrimitiveMesh.createExtrudedPolygon(engine, polygons, 2), + PrimitiveMesh.createExtrudedPolygon(engine, polygons, 2, linearExtrudedPolygonOptions), + PrimitiveMesh.createExtrudedPolygon(engine, contour, path), + PrimitiveMesh.createExtrudedPolygon(engine, contour, path, pathExtrudedPolygonOptions), + PrimitiveMesh.createExtrudedPolygon(engine, polygon, path), + PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, pathExtrudedPolygonOptions), + PrimitiveMesh.createExtrudedPolygon(engine, polygons, path), + PrimitiveMesh.createExtrudedPolygon(engine, polygons, path, pathExtrudedPolygonOptions), + PrimitiveMesh.createExtrudedPolygon(engine, polygons, path, extrudedPolygonOptions), + PrimitiveMesh.createSphere(engine, 1, commonOptions), + PrimitiveMesh.createSphere(engine, 1, { subdivisionLevel: 4 }), + PrimitiveMesh.createCylinder(engine, 0.5, 2, { caps: PrimitiveMeshCapMode.Both }), + PrimitiveMesh.createCylinder(engine, 0.5, 2, { caps: PrimitiveMeshCapMode.Top }) +]; +void meshes; + +// @ts-expect-error Sphere requires every core shape input +PrimitiveMesh.createSphere(engine); +// @ts-expect-error Cuboid requires every core shape input +PrimitiveMesh.createCuboid(engine, 1, 1); +// @ts-expect-error Plane requires every core shape input +PrimitiveMesh.createPlane(engine, 1); +// @ts-expect-error Cylinder requires every core shape input +PrimitiveMesh.createCylinder(engine, 0.5); +// @ts-expect-error TruncatedCone requires every core shape input +PrimitiveMesh.createTruncatedCone(engine, 0.25, 0.5); +// @ts-expect-error Cone requires every core shape input +PrimitiveMesh.createCone(engine, 0.5); +// @ts-expect-error Capsule requires every core shape input +PrimitiveMesh.createCapsule(engine, 0.5); +// @ts-expect-error Torus requires every core shape input +PrimitiveMesh.createTorus(engine, 0.5); +// @ts-expect-error Circle requires every core shape input +PrimitiveMesh.createCircle(engine); +// @ts-expect-error Ring requires every core shape input +PrimitiveMesh.createRing(engine, 0.5); +// @ts-expect-error Tetrahedron requires every core shape input +PrimitiveMesh.createTetrahedron(engine); +// @ts-expect-error Octahedron requires every core shape input +PrimitiveMesh.createOctahedron(engine); +// @ts-expect-error Icosahedron requires every core shape input +PrimitiveMesh.createIcosahedron(engine); +// @ts-expect-error Dodecahedron requires every core shape input +PrimitiveMesh.createDodecahedron(engine); +// @ts-expect-error Revolved surface requires every core shape input +PrimitiveMesh.createRevolvedSurface(engine); +// @ts-expect-error Tube requires every core shape input +PrimitiveMesh.createTube(engine, path); +// @ts-expect-error Polygon requires every core shape input +PrimitiveMesh.createPolygon(engine); +// @ts-expect-error Extrusion requires every core shape input +PrimitiveMesh.createExtrudedPolygon(engine, contour); +// @ts-expect-error TorusKnot requires every core shape input +PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2); +// @ts-expect-error RoundedCuboid requires every core shape input +PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1); + +// @ts-expect-error radius is a required input rather than an option +PrimitiveMesh.createSphere(engine, 0.5, { radius: 1 }); +// @ts-expect-error width is a required input rather than an option +PrimitiveMesh.createCuboid(engine, 1, 1, 1, { width: 1 }); +// @ts-expect-error width is a required input rather than an option +PrimitiveMesh.createPlane(engine, 1, 1, { width: 1 }); +// @ts-expect-error radius is a required input rather than an option +PrimitiveMesh.createCylinder(engine, 0.5, 2, { radius: 1 }); +// @ts-expect-error topRadius is a required input rather than an option +PrimitiveMesh.createTruncatedCone(engine, 0.25, 0.5, 2, { topRadius: 1 }); +// @ts-expect-error radius is a required input rather than an option +PrimitiveMesh.createCone(engine, 0.5, 2, { radius: 1 }); +// @ts-expect-error radius is a required input rather than an option +PrimitiveMesh.createCapsule(engine, 0.5, 2, { radius: 1 }); +// @ts-expect-error radius is a required input rather than an option +PrimitiveMesh.createTorus(engine, 0.5, 0.1, { radius: 1 }); +// @ts-expect-error radius is a required input rather than an option +PrimitiveMesh.createCircle(engine, 0.5, { radius: 1 }); +// @ts-expect-error outerRadius is a required input rather than an option +PrimitiveMesh.createRing(engine, 0.5, 0.25, { outerRadius: 1 }); +// @ts-expect-error radius is a required input rather than an option +PrimitiveMesh.createTetrahedron(engine, 0.5, { radius: 1 }); +// @ts-expect-error radius is a required input rather than an option +PrimitiveMesh.createOctahedron(engine, 0.5, { radius: 1 }); +// @ts-expect-error radius is a required input rather than an option +PrimitiveMesh.createIcosahedron(engine, 0.5, { radius: 1 }); +// @ts-expect-error radius is a required input rather than an option +PrimitiveMesh.createDodecahedron(engine, 0.5, { radius: 1 }); +// @ts-expect-error radius is a required input rather than an option +PrimitiveMesh.createTube(engine, path, 0.5, { radius: 1 }); +// @ts-expect-error depth is a required input rather than an option +PrimitiveMesh.createExtrudedPolygon(engine, contour, 1, { depth: 1 }); +// @ts-expect-error radius is a required input rather than an option +PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2, 3, { radius: 1 }); +// @ts-expect-error width is a required input rather than an option +PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.1, { width: 1 }); + +// @ts-expect-error Sphere radius is a number +PrimitiveMesh.createSphere(engine, {}); +// @ts-expect-error Spheres do not define material groups +PrimitiveMesh.createSphere(engine, 1, { separateMaterialSlots: true }); +// @ts-expect-error Planes do not define material groups +PrimitiveMesh.createPlane(engine, 1, 1, { separateMaterialSlots: true }); +// @ts-expect-error Tori do not define material groups +PrimitiveMesh.createTorus(engine, 1, 0.2, { separateMaterialSlots: true }); +// @ts-expect-error Tubes do not define material groups +PrimitiveMesh.createTube(engine, path, 0.1, { separateMaterialSlots: true }); +// @ts-expect-error Spheres have one canonical creation method +PrimitiveMesh.createSubdivisionSphere(engine); +// @ts-expect-error Arbitrary polyhedra are not a scene-building primitive +PrimitiveMesh.createPolyhedron(engine, [], []); +// @ts-expect-error Spheres use one subdivision level rather than independent segment counts +PrimitiveMesh.createSphere(engine, 1, { horizontalSegments: 32 }); +// @ts-expect-error Angular ranges use Vector2 rather than arrays +PrimitiveMesh.createCircle(engine, 1, { angleRange: [0, 180] }); +// @ts-expect-error Runtime ranges require Vector2 instances +PrimitiveMesh.createSphere(engine, 1, { horizontalAngleRange: { x: 0, y: 180 } }); +// @ts-expect-error A cylinder cap selection must describe a supported combination +PrimitiveMesh.createCylinder(engine, 0.5, 2, { caps: "left" }); +// @ts-expect-error Cap modes use the exported enum rather than raw strings +PrimitiveMesh.createCylinder(engine, 0.5, 2, { caps: "top" }); +// @ts-expect-error Truncated cones use the same cap-mode enum +PrimitiveMesh.createTruncatedCone(engine, 0.25, 0.5, 2, { caps: "none" }); + +// @ts-expect-error Path extrusion settings do not include bevels +PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, { bevelWidth: 0.1 }); +// @ts-expect-error Path extrusion settings do not include contour offsets +PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, { contourOffset: 0.1 }); +// @ts-expect-error Linear extrusion settings do not include path closure +PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { closedPath: true }); +// @ts-expect-error Linear extrusion settings do not include path subdivisions +PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { pathSegments: 8 }); +// @ts-expect-error Bevel offsets use numeric local units +PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { contourOffset: "0.1" }); +// @ts-expect-error Explicit linear settings do not declare path closure +const invalidLinearOptions: LinearExtrudedPolygonMeshOptions = { closedPath: true }; +// @ts-expect-error Explicit path settings do not declare bevels +const invalidPathOptions: PathExtrudedPolygonMeshOptions = { bevelWidth: 0.1 }; + +const samplePath = (t: number, out: Vector3): void => { + out.set(t, t * t, 0); +}; +// @ts-expect-error Tube paths accept point arrays +PrimitiveMesh.createTube(engine, samplePath, 0.1); +// @ts-expect-error Extrusion paths accept point arrays +PrimitiveMesh.createExtrudedPolygon(engine, polygon, samplePath); + +const serializedContour = [ + { x: 0, y: 0 }, + { x: 1, y: 0 }, + { x: 0, y: 1 } +]; +const serializedPath = [ + { x: 0, y: 0, z: 0 }, + { x: 0, y: 0, z: 1 } +]; +// @ts-expect-error Revolved surface profiles use Vector2 instances +PrimitiveMesh.createRevolvedSurface(engine, serializedContour); +// @ts-expect-error Polygon contours use Vector2 instances +PrimitiveMesh.createPolygon(engine, serializedContour); +// @ts-expect-error Polygon holes also use Vector2 instances +PrimitiveMesh.createPolygon(engine, { points: contour, holes: [serializedContour] }); +// @ts-expect-error Path points use Vector3 instances +PrimitiveMesh.createTube(engine, serializedPath, 0.1); +// @ts-expect-error Path extrusion points use Vector3 instances +PrimitiveMesh.createExtrudedPolygon(engine, polygon, serializedPath); diff --git a/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts new file mode 100644 index 0000000000..1db1aabdc8 --- /dev/null +++ b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts @@ -0,0 +1,210 @@ +import { PrimitiveMesh } from "../../../packages/core/types"; +import { PrimitiveMeshCapMode } from "../../../packages/galacean/types"; +import type { PrimitiveMeshAsset } from "../../../packages/loader/types"; +import type { PrimitiveMeshAsset as EnginePrimitiveMeshAsset } from "../../../packages/galacean/types"; + +type CreationType = { + [Name in keyof typeof PrimitiveMesh]: Name extends `create${infer Shape}` ? Uncapitalize : never; +}[keyof typeof PrimitiveMesh]; +const everyFactoryHasAnAsset: Exclude extends never ? true : never = true; +const everyAssetHasAFactory: Exclude extends never ? true : never = true; + +const sphere: PrimitiveMeshAsset = { + type: "sphere", + sphereRadius: 1, + sphereOptions: { verticalAngleRange: { x: 0, y: 90 }, keepMeshData: true, subdivisionLevel: 3 } +}; +const exportedFromEngine: EnginePrimitiveMeshAsset = sphere; +const sphereSection: PrimitiveMeshAsset = { + type: "sphere", + sphereRadius: 1, + sphereOptions: { + horizontalAngleRange: { x: 350, y: 370 }, + verticalAngleRange: { x: 30, y: 150 }, + subdivisionLevel: 3 + } +}; +const ungroupedSphere: PrimitiveMeshAsset = { + type: "sphere", + sphereRadius: 0.5, + // @ts-expect-error Sphere assets do not define material groups + sphereOptions: { separateMaterialSlots: true } +}; +const path = [ + { x: 0, y: 0, z: 0 }, + { x: 0, y: 0, z: 2 } +] as const; +const shapes = [ + { + points: [ + { x: 0, y: 0 }, + { x: 1, y: 0 }, + { x: 0, y: 1 } + ] + } +] as const; + +type SerializedPolygon = Extract["polygonShapes"][number]; +const polygonWithHoles: SerializedPolygon = { points: shapes[0].points, holes: [shapes[0].points] }; +// @ts-expect-error Serialized contour points remain readonly +polygonWithHoles.points.push({ x: 0, y: 0 }); +// @ts-expect-error Serialized hole lists remain readonly +polygonWithHoles.holes!.push(shapes[0].points); +// @ts-expect-error Serialized hole points remain readonly +polygonWithHoles.holes![0].push({ x: 0, y: 0 }); +// @ts-expect-error Serialized contour points have no Vector2 methods +polygonWithHoles.points[0].clone(); +const invalidHolePoint: SerializedPolygon = { + points: shapes[0].points, + // @ts-expect-error Hole points contain two-dimensional coordinates + holes: [[{ x: 0, y: 0, z: 0 }]] +}; +const invalidPathPoint: PrimitiveMeshAsset = { + type: "tube", + tubeRadius: 0.5, + // @ts-expect-error Path points require three-dimensional coordinates + tubePath: [{ x: 0, y: 0 }] +}; + +const tube: PrimitiveMeshAsset = { type: "tube", tubeRadius: 0.5, tubePath: path, tubeOptions: { closedPath: true } }; +const polygon: PrimitiveMeshAsset = { type: "polygon", polygonShapes: shapes }; +const extrudedPolygon: PrimitiveMeshAsset = { + type: "extrudedPolygon", + extrudedPolygonDepth: 2, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { bevelWidth: 0.1, contourOffset: 0.2, separateMaterialSlots: true } +}; +const pathExtrusion: PrimitiveMeshAsset = { + type: "extrudedPolygon", + extrudedPolygonPath: path, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { closedPath: true } +}; +const torusKnot: PrimitiveMeshAsset = { + type: "torusKnot", + torusKnotRadius: 0.5, + torusKnotTubeRadius: 0.1, + torusKnotAxisTurns: -2, + torusKnotCrossSectionTurns: -3 +}; +const cylinder: PrimitiveMeshAsset = { + type: "cylinder", + cylinderRadius: 0.5, + cylinderHeight: 2, + cylinderOptions: { caps: PrimitiveMeshCapMode.Bottom } +}; +const truncatedCone: PrimitiveMeshAsset = { + type: "truncatedCone", + truncatedConeTopRadius: 0.25, + truncatedConeBottomRadius: 0.5, + truncatedConeHeight: 2, + truncatedConeOptions: { caps: PrimitiveMeshCapMode.Top } +}; + +// @ts-expect-error Primitive types must name a supported factory +const invalidType: PrimitiveMeshAsset = { type: "star" }; +// @ts-expect-error A tube asset needs a serializable path +const missingPath: PrimitiveMeshAsset = { type: "tube", tubeRadius: 0.5 }; +// @ts-expect-error Asset paths contain coordinates, not callbacks +const callbackPath: PrimitiveMeshAsset = { type: "tube", tubeRadius: 0.5, tubePath: (t: number) => t }; +// @ts-expect-error A polygon asset needs its contours +const missingShapes: PrimitiveMeshAsset = { type: "polygon" }; +const mixedExtrusion: PrimitiveMeshAsset = { + type: "extrudedPolygon", + extrudedPolygonDepth: 2, + extrudedPolygonPath: path, + extrudedPolygonShapes: shapes +}; +// @ts-expect-error Path extrusion assets do not use linear bevel settings +const beveledPath: PrimitiveMeshAsset = { + type: "extrudedPolygon", + extrudedPolygonPath: path, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { bevelWidth: 1 } +}; +// @ts-expect-error Path extrusion assets do not use linear contour offsets +const offsetPath: PrimitiveMeshAsset = { + type: "extrudedPolygon", + extrudedPolygonPath: path, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { contourOffset: 0.1 } +}; +// @ts-expect-error Linear extrusion assets do not use path closure +const closedDepth: PrimitiveMeshAsset = { + type: "extrudedPolygon", + extrudedPolygonDepth: 2, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { closedPath: true } +}; +const wrongOptions: PrimitiveMeshAsset = { + type: "sphere", + sphereRadius: 0.5, + // @ts-expect-error Shape options cannot be applied to another primitive + sphereOptions: { caps: PrimitiveMeshCapMode.Both } +}; +const stringCap: PrimitiveMeshAsset = { + type: "cylinder", + cylinderRadius: 0.5, + cylinderHeight: 2, + // @ts-expect-error TypeScript assets use the cap-mode enum + cylinderOptions: { caps: "top" } +}; +// @ts-expect-error Serialized angular ranges use coordinate objects rather than arrays +const wrongRange: PrimitiveMeshAsset = { type: "circle", circleRadius: 0.5, circleOptions: { angleRange: [0, 180] } }; +const segmentedSphere: PrimitiveMeshAsset = { + type: "sphere", + sphereRadius: 0.5, + // @ts-expect-error Spheres use one subdivision level rather than independent segment counts + sphereOptions: { horizontalSegments: 32 } +}; +// @ts-expect-error Spheres have one canonical asset type +const duplicateSphere: PrimitiveMeshAsset = { type: "subdivisionSphere" }; +const endRadiiAsCylinder: PrimitiveMeshAsset = { + type: "cylinder", + cylinderRadius: 0.5, + cylinderHeight: 2, + // @ts-expect-error End radii belong to truncatedCone + cylinderOptions: { radiusTop: 1 } +}; + +void [ + everyFactoryHasAnAsset, + everyAssetHasAFactory, + exportedFromEngine, + sphereSection, + ungroupedSphere, + polygonWithHoles, + invalidHolePoint, + invalidPathPoint, + tube, + polygon, + extrudedPolygon, + pathExtrusion, + torusKnot, + cylinder, + truncatedCone, + invalidType, + missingPath, + callbackPath, + missingShapes, + mixedExtrusion, + beveledPath, + offsetPath, + closedDepth, + wrongOptions, + stringCap, + wrongRange, + segmentedSphere, + duplicateSphere, + endRadiiAsCylinder +]; + +// @ts-expect-error A sphere asset requires its radius +const missingRadius: PrimitiveMeshAsset = { type: "sphere" }; +// @ts-expect-error A cuboid asset requires all dimensions +const missingDepth: PrimitiveMeshAsset = { type: "cuboid", cuboidWidth: 1, cuboidHeight: 1 }; +// @ts-expect-error An extrusion asset requires a depth or path +const missingExtrusionInput: PrimitiveMeshAsset = { type: "extrudedPolygon", extrudedPolygonShapes: shapes }; +// @ts-expect-error Dimensions no longer belong to optional settings +const radiusInOptions: PrimitiveMeshAsset = { type: "sphere", sphereRadius: 1, sphereOptions: { radius: 2 } }; +void [missingRadius, missingDepth, missingExtrusionInput, radiusInOptions]; diff --git a/tests/src/core/ModelMesh.test.ts b/tests/src/core/ModelMesh.test.ts index ed7931eaf5..23b7098661 100644 --- a/tests/src/core/ModelMesh.test.ts +++ b/tests/src/core/ModelMesh.test.ts @@ -7,12 +7,13 @@ import { IndexFormat, ModelMesh, VertexAttribute, + VertexBufferBinding, VertexElement, VertexElementFormat } from "@galacean/engine-core"; import { Color, Vector2, Vector3, Vector4 } from "@galacean/engine-math"; import { WebGLEngine } from "@galacean/engine"; -import { describe, beforeAll, expect, it } from "vitest"; +import { describe, beforeAll, expect, it, vi } from "vitest"; describe("ModelMesh Test", async function () { let engine: Engine; @@ -344,6 +345,101 @@ describe("ModelMesh Test", async function () { expect(vertexBufferBindings.length).eq(1); }); + it("reuses a listener when vertex buffers are rebound", () => { + const mesh = new ModelMesh(engine); + const first = new Buffer( + engine, + BufferBindFlag.VertexBuffer, + new Float32Array([1, 0, 0]), + BufferUsage.Static, + true + ); + const second = new Buffer( + engine, + BufferBindFlag.VertexBuffer, + new Float32Array([2, 0, 0]), + BufferUsage.Static, + true + ); + const addFirst = vi.spyOn(first._dataUpdateManager, "addListener"); + const removeFirst = vi.spyOn(first._dataUpdateManager, "removeListener"); + const addSecond = vi.spyOn(second._dataUpdateManager, "addListener"); + const removeSecond = vi.spyOn(second._dataUpdateManager, "removeListener"); + try { + mesh.setVertexElements([new VertexElement(VertexAttribute.Position, 0, VertexElementFormat.Vector3, 3)]); + mesh.setVertexBufferBinding(first, 12, 3); + const listener = addFirst.mock.calls[0][0]; + mesh.setVertexBufferBinding(first, 12, 3); + mesh.setVertexBufferBindings([new VertexBufferBinding(second, 12)], 3); + mesh.setVertexBufferBinding(first, 12, 3); + expect(addFirst.mock.calls).toEqual([[listener], [listener], [listener]]); + expect(addSecond.mock.calls).toEqual([[listener]]); + expect(removeFirst.mock.calls).toEqual([[listener], [listener]]); + expect(removeSecond.mock.calls).toEqual([[listener]]); + + mesh.setPositions([new Vector3(9, 0, 0)]); + second.setData(new Float32Array([4, 0, 0])); + expect(mesh.getPositions()![0].x).toBe(9); + first.setData(new Float32Array([5, 0, 0])); + expect(mesh.getPositions()![0].x).toBe(5); + + mesh.destroy(); + expect(removeFirst.mock.calls).toEqual([[listener], [listener], [listener]]); + } finally { + mesh.destroy(); + first.destroy(); + second.destroy(); + addFirst.mockRestore(); + removeFirst.mockRestore(); + addSecond.mockRestore(); + removeSecond.mockRestore(); + } + }); + + it("removes only the destroyed mesh's listeners from a shared vertex buffer", () => { + const first = new ModelMesh(engine); + const second = new ModelMesh(engine); + const buffer = new Buffer( + engine, + BufferBindFlag.VertexBuffer, + new Float32Array([1, 0, 0]), + BufferUsage.Static, + true + ); + const addListener = vi.spyOn(buffer._dataUpdateManager, "addListener"); + const removeListener = vi.spyOn(buffer._dataUpdateManager, "removeListener"); + try { + first.setVertexElements([ + new VertexElement(VertexAttribute.Position, 0, VertexElementFormat.Vector3, 0), + new VertexElement(VertexAttribute.Normal, 0, VertexElementFormat.Vector3, 3) + ]); + second.setVertexElements([new VertexElement(VertexAttribute.Position, 0, VertexElementFormat.Vector3, 0)]); + first.setVertexBufferBinding(buffer, 12, 0); + first.setVertexBufferBinding(buffer, 12, 3); + second.setVertexBufferBinding(buffer, 12, 0); + const listeners = addListener.mock.calls.map(([listener]) => listener); + expect(new Set(listeners).size).toBe(3); + + buffer.setData(new Float32Array([2, 0, 0])); + expect(first.getPositions()![0].x).toBe(2); + expect(first.getNormals()![0].x).toBe(2); + expect(second.getPositions()![0].x).toBe(2); + + first.destroy(); + expect(removeListener.mock.calls).toEqual([[listeners[0]], [listeners[1]]]); + buffer.setData(new Float32Array([3, 0, 0])); + expect(second.getPositions()![0].x).toBe(3); + second.destroy(); + expect(removeListener.mock.calls).toEqual([[listeners[0]], [listeners[1]], [listeners[2]]]); + } finally { + first.destroy(); + second.destroy(); + buffer.destroy(); + addListener.mockRestore(); + removeListener.mockRestore(); + } + }); + it("Test non-contiguous custom vertex buffer", () => { const vertexCount = 4; const halfWidth = 0.5; diff --git a/tests/src/core/ShaderIdentity.test.ts b/tests/src/core/ShaderIdentity.test.ts index 718051793a..89e475586f 100644 --- a/tests/src/core/ShaderIdentity.test.ts +++ b/tests/src/core/ShaderIdentity.test.ts @@ -100,7 +100,7 @@ describe("Shader object identity", () => { camera.orthographicSize = 1; const texture = new Texture2D(engine, 64, 32, undefined, false); camera.renderTarget = new RenderTarget(engine, 64, 32, texture); - const mesh = PrimitiveMesh.createCuboid(engine); + const mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); const redRenderer = scene.createRootEntity("Red").addComponent(MeshRenderer); redRenderer.entity.transform.setPosition(-1, 0, 0); redRenderer.mesh = mesh; diff --git a/tests/src/core/mesh/BlendShape.test.ts b/tests/src/core/mesh/BlendShape.test.ts index 2346126886..405162c29d 100644 --- a/tests/src/core/mesh/BlendShape.test.ts +++ b/tests/src/core/mesh/BlendShape.test.ts @@ -176,7 +176,7 @@ describe("BlendShape", () => { blendShape.addFrame(0.4, deltaPositions, deltaNormals, null); blendShape.addFrame(0.7, deltaPositions, null, deltaTangents); - const modelMesh = PrimitiveMesh.createPlane(engine, 1, 1, 1, 1); + const modelMesh = PrimitiveMesh.createPlane(engine, 1, 1); modelMesh.addBlendShape(blendShape); modelMesh.uploadData(true); diff --git a/tests/src/core/mesh/BlendShapeManager.test.ts b/tests/src/core/mesh/BlendShapeManager.test.ts index 999b90fce9..387696b963 100644 --- a/tests/src/core/mesh/BlendShapeManager.test.ts +++ b/tests/src/core/mesh/BlendShapeManager.test.ts @@ -217,7 +217,12 @@ describe("BlendShapeManager", () => { ] ); blendShapeWeights0_7.addFrame(frame); - const modelMeshWebgl2 = PrimitiveMesh.createCuboid(engineWebGL2, 1, 1, 1, false); + const modelMeshWebgl2 = PrimitiveMesh.createCuboid(engineWebGL2, 1, 1, 1, { + keepMeshData: true, + widthSegments: 1, + heightSegments: 1, + depthSegments: 1 + }); modelMeshWebgl2.addBlendShape(blendShapeWeights0_5); modelMeshWebgl2.addBlendShape(blendShapeWeights0_7); modelMeshWebgl2.addBlendShape(blendShapeWeights0_7); @@ -294,7 +299,7 @@ describe("BlendShapeManager", () => { }); it("_addBlendShape and _clearBlendShapes", () => { - const modelMesh = PrimitiveMesh.createPlane(engineWebGL2, 1, 1, 1, 1); + const modelMesh = PrimitiveMesh.createPlane(engineWebGL2, 1, 1); modelMesh.addBlendShape(new BlendShape("BlendShape1")); modelMesh.addBlendShape(new BlendShape("BlendShape2")); expect(modelMesh.blendShapeCount).to.be.equal(2); @@ -310,7 +315,7 @@ describe("BlendShapeManager", () => { }); it("_update", () => { - const modelMesh = PrimitiveMesh.createPlane(engineWebGL2, 1, 1, 1, 1); + const modelMesh = PrimitiveMesh.createPlane(engineWebGL2, 1, 1); const blendShape = new BlendShape("BlendShape1"); modelMesh.addBlendShape(blendShape); blendShape.addFrame(0.7, [new Vector3(1, 0, 0)], [new Vector3(0, 0, 1)], [new Vector3(1, 1, 1)]); @@ -320,7 +325,7 @@ describe("BlendShapeManager", () => { modelMesh.uploadData(true); }).to.throw("BlendShape frame deltaPositions length must same with mesh vertexCount"); - const modelMesh2 = PrimitiveMesh.createPlane(engineWebGL2, 1, 1, 1); + const modelMesh2 = PrimitiveMesh.createPlane(engineWebGL2, 1, 1); blendShape.frames[0].deltaPositions = [ new Vector3(1, 0, 0), new Vector3(0, 1, 1), diff --git a/tests/src/core/mesh/PrimitiveMesh.test.ts b/tests/src/core/mesh/PrimitiveMesh.test.ts index 1956ba4574..97e2a42251 100644 --- a/tests/src/core/mesh/PrimitiveMesh.test.ts +++ b/tests/src/core/mesh/PrimitiveMesh.test.ts @@ -1,7 +1,7 @@ import { Camera, GLCapabilityType, PrimitiveMesh } from "@galacean/engine-core"; import { WebGLEngine } from "@galacean/engine"; -import { Vector3 } from "@galacean/engine-math"; -import { describe, beforeAll, expect, it } from "vitest"; +import { Vector2, Vector3 } from "@galacean/engine-math"; +import { describe, beforeAll, expect, it, vi } from "vitest"; describe("PrimitiveMesh", () => { let engine: WebGLEngine; @@ -19,31 +19,16 @@ describe("PrimitiveMesh", () => { }); it("createSphere", () => { - // Test that createSphere works correctly. - const radius = 1.333; - const segments = 20.555556; - const floorSegments = Math.floor(segments); - const sphereMesh = PrimitiveMesh.createSphere(engine, radius, segments, false); - - const count = floorSegments + 1; - expect(sphereMesh.vertexCount).equal(count * count); - expect(sphereMesh.vertexElements.length).equal(4); - expect(sphereMesh.bounds.min).to.deep.include({ x: -radius, y: -radius, z: -radius }); - expect(sphereMesh.bounds.max).to.deep.include({ x: radius, y: radius, z: radius }); - expect(sphereMesh.getIndices().length).equal(floorSegments * floorSegments * 6); - expect(sphereMesh.vertexBufferBindings.length).equal(2); - }); - - it("createSubdivisionSurfaceSphere", () => { - // Test that createSphere works correctly. const radius = 2.333; - const steps = 3.2; - const sphereMesh = PrimitiveMesh.createSubdivisionSurfaceSphere(engine, radius, steps, false); + const subdivisionLevel = 3.2; + const sphereMesh = PrimitiveMesh.createSphere(engine, radius, { keepMeshData: true, subdivisionLevel }); expect(sphereMesh.vertexCount).equal(417); + expect(sphereMesh.vertexElements.length).equal(4); expect(sphereMesh.bounds.min).to.deep.include({ x: -radius, y: -radius, z: -radius }); expect(sphereMesh.bounds.max).to.deep.include({ x: radius, y: radius, z: radius }); expect(sphereMesh.getIndices().length).equal(2304); + expect(sphereMesh.vertexBufferBindings.length).equal(2); }); it("createCuboid", () => { @@ -51,7 +36,12 @@ describe("PrimitiveMesh", () => { const width = 2.3; const height = 3.2; const depth = 4.5; - const cuboidMesh = PrimitiveMesh.createCuboid(engine, width, height, depth, false); + const cuboidMesh = PrimitiveMesh.createCuboid(engine, width, height, depth, { + keepMeshData: true, + widthSegments: 1, + heightSegments: 1, + depthSegments: 1 + }); expect(cuboidMesh.vertexCount).equal(24); expect(cuboidMesh.vertexElements.length).equal(4); @@ -61,8 +51,8 @@ describe("PrimitiveMesh", () => { expect(cuboidMesh.vertexBufferBindings.length).equal(2); }); - it("createCylinder", () => { - // Test that createCylinder works correctly. + it("createTruncatedCone", () => { + // Test that createTruncatedCone works correctly. const radiusTop = 2; const radiusBottom = 3; const height = 2; @@ -70,27 +60,23 @@ describe("PrimitiveMesh", () => { const heightSegments = 1.00001; const floorRadialSegments = Math.floor(radialSegments); const floorHeightSegments = Math.floor(heightSegments); - const cylinderMesh = PrimitiveMesh.createCylinder( - engine, - radiusTop, - radiusBottom, - height, + const truncatedConeMesh = PrimitiveMesh.createTruncatedCone(engine, radiusTop, radiusBottom, height, { + keepMeshData: true, radialSegments, - heightSegments, - false - ); + heightSegments + }); const radius = Math.max(radiusTop, radiusBottom); - expect(cylinderMesh.vertexCount).equal( + expect(truncatedConeMesh.vertexCount).equal( (floorRadialSegments + 1) * (floorHeightSegments + 1) + floorRadialSegments * 2 + 2 ); - expect(cylinderMesh.vertexElements.length).equal(4); - expect(cylinderMesh.bounds.min).to.deep.include({ x: -radius, y: 0.5 * -height, z: -radius }); - expect(cylinderMesh.bounds.max).to.deep.include({ x: radius, y: 0.5 * height, z: radius }); - expect(cylinderMesh.getIndices().length).equal( + expect(truncatedConeMesh.vertexElements.length).equal(4); + expect(truncatedConeMesh.bounds.min).to.deep.include({ x: -radius, y: 0.5 * -height, z: -radius }); + expect(truncatedConeMesh.bounds.max).to.deep.include({ x: radius, y: 0.5 * height, z: radius }); + expect(truncatedConeMesh.getIndices().length).equal( floorRadialSegments * floorHeightSegments * 6 + floorRadialSegments * 2 * 3 ); - expect(cylinderMesh.vertexBufferBindings.length).equal(2); + expect(truncatedConeMesh.vertexBufferBindings.length).equal(2); }); it("createTorus", () => { @@ -98,26 +84,23 @@ describe("PrimitiveMesh", () => { const radius = 1; const tubeRadius = 0.5; const radialSegments = 20.9999; - const tubularSegments = 40.0532; + const ringSegments = 40.0532; const floorRadialSegments = Math.floor(radialSegments); - const floorTubularSegments = Math.floor(tubularSegments); + const floorRingSegments = Math.floor(ringSegments); const arc = 180; - const torusMesh = PrimitiveMesh.createTorus( - engine, - radius, - tubeRadius, - radialSegments, - tubularSegments, - arc, - false - ); + const torusMesh = PrimitiveMesh.createTorus(engine, radius, tubeRadius, { + keepMeshData: true, + ringAngleRange: new Vector2(0, 0 + arc), + ringSegments, + radialSegments + }); const outerRadius = radius + tubeRadius; - expect(torusMesh.vertexCount).equal((floorRadialSegments + 1) * (floorTubularSegments + 1)); + expect(torusMesh.vertexCount).equal((floorRadialSegments + 1) * (floorRingSegments + 1)); expect(torusMesh.vertexElements.length).equal(4); expect(torusMesh.bounds.min).to.deep.include({ x: -outerRadius, y: -outerRadius, z: -tubeRadius }); expect(torusMesh.bounds.max).to.deep.include({ x: outerRadius, y: outerRadius, z: tubeRadius }); - expect(torusMesh.getIndices().length).equal(floorRadialSegments * floorTubularSegments * 6); + expect(torusMesh.getIndices().length).equal(floorRadialSegments * floorRingSegments * 6); expect(torusMesh.vertexBufferBindings.length).equal(2); }); @@ -129,7 +112,11 @@ describe("PrimitiveMesh", () => { const vSegments = 9.0001; const floorHSegments = Math.floor(hSegments); const floorVSegments = Math.floor(vSegments); - const planeMesh = PrimitiveMesh.createPlane(engine, width, height, hSegments, vSegments, false); + const planeMesh = PrimitiveMesh.createPlane(engine, width, height, { + keepMeshData: true, + widthSegments: hSegments, + depthSegments: vSegments + }); expect(planeMesh.vertexCount).equal((floorHSegments + 1) * (floorVSegments + 1)); expect(planeMesh.vertexElements.length).equal(4); @@ -147,13 +134,17 @@ describe("PrimitiveMesh", () => { const heightSegments = 1.00001; const floorRadialSegments = Math.floor(radialSegments); const floorHeightSegments = Math.floor(heightSegments); - const coneMesh = PrimitiveMesh.createCone(engine, radius, height, radialSegments, heightSegments, false); + const coneMesh = PrimitiveMesh.createCone(engine, radius, height, { + keepMeshData: true, + radialSegments, + heightSegments + }); expect(coneMesh.vertexCount).equal((floorRadialSegments + 1) * (floorHeightSegments + 1) + floorRadialSegments + 1); expect(coneMesh.vertexElements.length).equal(4); expect(coneMesh.bounds.min).to.deep.include({ x: -radius, y: 0.5 * -height, z: -radius }); expect(coneMesh.bounds.max).to.deep.include({ x: radius, y: 0.5 * height, z: radius }); - expect(coneMesh.getIndices().length).equal(floorRadialSegments * floorHeightSegments * 6 + floorRadialSegments * 3); + expect(coneMesh.getIndices().length).equal(floorRadialSegments * floorHeightSegments * 6); expect(coneMesh.vertexBufferBindings.length).equal(2); }); @@ -164,39 +155,64 @@ describe("PrimitiveMesh", () => { const heightSegments = 30.0001; const floorRadialSegments = Math.floor(radialSegments); const floorHeightSegments = Math.floor(heightSegments); - const capsuleMesh = PrimitiveMesh.createCapsule(engine, radius, height, radialSegments, heightSegments, false); + const capsuleMesh = PrimitiveMesh.createCapsule(engine, radius, height, { + keepMeshData: true, + radialSegments, + capSegments: radialSegments, + heightSegments + }); expect(capsuleMesh.vertexCount).equal( - (floorRadialSegments + 1) * (floorHeightSegments + 1) + 2 * Math.pow(floorRadialSegments + 1, 2) + (floorRadialSegments + 1) * (floorHeightSegments + 2 * floorRadialSegments + 1) ); expect(capsuleMesh.vertexElements.length).equal(4); expect(capsuleMesh.bounds.min).to.deep.include({ x: -radius, y: 0.5 * -height - radius, z: -radius }); expect(capsuleMesh.bounds.max).to.deep.include({ x: radius, y: 0.5 * height + radius, z: radius }); expect(capsuleMesh.getIndices().length).equal( - (floorRadialSegments * floorHeightSegments + 2 * floorRadialSegments * floorRadialSegments) * 6 + floorRadialSegments * (floorHeightSegments + 2 * floorRadialSegments - 1) * 6 ); }); it("test limit vertex count", function () { const radius = 1; const segments = 256; - const floorSegments = Math.floor(segments); const count = segments + 1; if (engine["_hardwareRenderer"].canIUse(GLCapabilityType.elementIndexUint)) { - const sphereMesh = PrimitiveMesh.createSphere(engine, radius, segments, false); - expect(sphereMesh.vertexCount).equal(count * count); - expect(sphereMesh.vertexElements.length).equal(4); - expect(sphereMesh.bounds.min).to.deep.include({ x: -radius, y: -radius, z: -radius }); - expect(sphereMesh.bounds.max).to.deep.include({ x: radius, y: radius, z: radius }); - expect(sphereMesh.getIndices().length).equal(floorSegments * floorSegments * 6); - expect(sphereMesh.vertexBufferBindings.length).equal(2); + const mesh = PrimitiveMesh.createPlane(engine, radius * 2, radius * 2, { + keepMeshData: true, + widthSegments: segments, + depthSegments: segments + }); + expect(mesh.vertexCount).equal(count * count); + expect(mesh.vertexElements.length).equal(4); + expect(mesh.bounds.min).to.deep.include({ x: -radius, y: 0, z: -radius }); + expect(mesh.bounds.max).to.deep.include({ x: radius, y: 0, z: radius }); + expect(mesh.getIndices().length).equal(segments * segments * 6); + expect(mesh.vertexBufferBindings.length).equal(2); } else { - expect(() => { - try { - PrimitiveMesh.createSphere(engine, radius, segments, false); - } catch (e) {} - }).throw("The vertex count is out of range."); + expect(() => + PrimitiveMesh.createPlane(engine, radius * 2, radius * 2, { + keepMeshData: true, + widthSegments: segments, + depthSegments: segments + }) + ).throw("The vertex count is over limit."); + } + }); + + it("rejects large meshes without 32-bit index support", () => { + const renderer = engine._hardwareRenderer; + const canIUse = renderer.canIUse.bind(renderer); + const capability = vi.spyOn(renderer, "canIUse").mockImplementation((type) => { + return type === GLCapabilityType.elementIndexUint ? false : canIUse(type); + }); + try { + expect(() => PrimitiveMesh.createPlane(engine, 2, 2, { widthSegments: 256, depthSegments: 256 })).toThrow( + "The vertex count is over limit." + ); + } finally { + capability.mockRestore(); } }); }); diff --git a/tests/src/core/mesh/ProceduralMesh.test.ts b/tests/src/core/mesh/ProceduralMesh.test.ts new file mode 100644 index 0000000000..ae54494374 --- /dev/null +++ b/tests/src/core/mesh/ProceduralMesh.test.ts @@ -0,0 +1,2013 @@ +import { + Buffer, + BufferBindFlag, + BufferUsage, + EngineEventType, + ModelMesh, + PrimitiveMesh, + PrimitiveMeshCapMode, + SetDataOptions, + Vector2, + Vector3, + Vector4, + VertexAttribute, + VertexElement, + VertexElementFormat, + WebGLEngine +} from "@galacean/engine"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +let engine: WebGLEngine; +beforeAll(async () => { + engine = await WebGLEngine.create({ canvas: document.createElement("canvas") }); +}); +afterAll(() => engine.destroy()); + +const polygon = { + points: [new Vector2(-2, -2), new Vector2(2, -2), new Vector2(2, 2), new Vector2(-2, 2)], + holes: [[new Vector2(-1, -1), new Vector2(-1, 1), new Vector2(1, 1), new Vector2(1, -1)]] +}; +const path = [new Vector3(0, 0, 0), new Vector3(0, 1, 1), new Vector3(1, 2, 2)]; + +const creators: [string, () => ModelMesh][] = [ + ["sphere", () => PrimitiveMesh.createSphere(engine, 2, { keepMeshData: true, subdivisionLevel: 2 })], + [ + "cuboid", + () => + PrimitiveMesh.createCuboid(engine, 1, 1, 1, { + keepMeshData: true, + widthSegments: 3, + heightSegments: 2, + depthSegments: 2 + }) + ], + ["plane", () => PrimitiveMesh.createPlane(engine, 1, 1, { keepMeshData: true, widthSegments: 3, depthSegments: 2 })], + [ + "cylinder", + () => + PrimitiveMesh.createTruncatedCone(engine, 0.25, 1, 2, { + keepMeshData: true, + radialSegments: 12, + heightSegments: 1 + }) + ], + [ + "cone", + () => PrimitiveMesh.createCone(engine, 0.5, 2, { keepMeshData: true, radialSegments: 12, heightSegments: 1 }) + ], + [ + "capsule", + () => + PrimitiveMesh.createCapsule(engine, 0.5, 2, { + keepMeshData: true, + radialSegments: 12, + capSegments: 4, + heightSegments: 1 + }) + ], + [ + "torus", + () => + PrimitiveMesh.createTorus(engine, 0.5, 0.1, { + keepMeshData: true, + ringAngleRange: new Vector2(0, 360), + ringSegments: 16, + radialSegments: 8 + }) + ], + [ + "circle", + () => PrimitiveMesh.createCircle(engine, 0.5, { keepMeshData: true, angleRange: new Vector2(0, 180), segments: 12 }) + ], + [ + "ring", + () => + PrimitiveMesh.createRing(engine, 0.5, 0.25, { + keepMeshData: true, + angleRange: new Vector2(0, 360), + ringSegments: 12, + widthSegments: 2 + }) + ], + ["tetrahedron", () => PrimitiveMesh.createTetrahedron(engine, 0.5, { keepMeshData: true, edgeSegments: 1 })], + ["octahedron", () => PrimitiveMesh.createOctahedron(engine, 0.5, { keepMeshData: true, edgeSegments: 1 })], + ["icosahedron", () => PrimitiveMesh.createIcosahedron(engine, 0.5, { keepMeshData: true, edgeSegments: 2 })], + ["dodecahedron", () => PrimitiveMesh.createDodecahedron(engine, 0.5, { keepMeshData: true, edgeSegments: 1 })], + [ + "revolvedSurface", + () => + PrimitiveMesh.createRevolvedSurface(engine, [new Vector2(0, -1), new Vector2(1, 0), new Vector2(0, 1)], { + keepMeshData: true, + angleRange: new Vector2(0, 360), + segments: 12 + }) + ], + [ + "tube", + () => PrimitiveMesh.createTube(engine, path, 0.5, { keepMeshData: true, pathSegments: 12, radialSegments: 8 }) + ], + ["polygon", () => PrimitiveMesh.createPolygon(engine, polygon, { keepMeshData: true })], + [ + "extrudedPolygon", + () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { keepMeshData: true, depthSegments: 1 }) + ], + [ + "extrudedPolygon", + () => + PrimitiveMesh.createExtrudedPolygon(engine, polygon, 1, { + keepMeshData: true, + bevelWidth: 0.1, + contourOffset: 0.2, + depthSegments: 1 + }) + ], + [ + "extrudedPolygon", + () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, { keepMeshData: true, pathSegments: 5 }) + ], + [ + "extrudedPolygon", + () => + PrimitiveMesh.createExtrudedPolygon( + engine, + { + points: [ + new Vector2(0, 0), + new Vector2(2, 0), + new Vector2(2, 1), + new Vector2(1, 1), + new Vector2(1, 2), + new Vector2(0, 2) + ] + }, + 1, + { keepMeshData: true, bevelWidth: 0.05, bevelDepth: 0.1, contourOffset: -0.05, depthSegments: 1 } + ) + ], + [ + "torusKnot", + () => + PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2, 3, { keepMeshData: true, pathSegments: 32, radialSegments: 8 }) + ], + [ + "torusKnot", + () => + PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, -2, -3, { + keepMeshData: true, + pathSegments: 32, + radialSegments: 8 + }) + ], + [ + "roundedCuboid", + () => PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.15, { keepMeshData: true, roundingSegments: 3 }) + ] +]; + +describe("primitive mesh defaults", () => { + const options = { keepMeshData: true }; + const profile = [new Vector2(0, -1), new Vector2(1, 0), new Vector2(0, 1)]; + const cases: [string, () => ModelMesh, () => ModelMesh][] = [ + [ + "sphere", + () => PrimitiveMesh.createSphere(engine, 1, { ...options }), + () => PrimitiveMesh.createSphere(engine, 1, { ...options, subdivisionLevel: 3 }) + ], + [ + "cuboid", + () => PrimitiveMesh.createCuboid(engine, 2, 3, 4, { ...options, widthSegments: 3 }), + () => + PrimitiveMesh.createCuboid(engine, 2, 3, 4, { + ...options, + widthSegments: 3, + heightSegments: 3, + depthSegments: 3 + }) + ], + [ + "plane", + () => PrimitiveMesh.createPlane(engine, 2, 3, { ...options, widthSegments: 2 }), + () => PrimitiveMesh.createPlane(engine, 2, 3, { ...options, widthSegments: 2, depthSegments: 2 }) + ], + [ + "cylinder", + () => PrimitiveMesh.createCylinder(engine, 1, 2, { ...options }), + () => PrimitiveMesh.createCylinder(engine, 1, 2, { ...options, radialSegments: 20, heightSegments: 1 }) + ], + [ + "truncated cone", + () => PrimitiveMesh.createTruncatedCone(engine, 0.25, 1, 2, { ...options }), + () => PrimitiveMesh.createTruncatedCone(engine, 0.25, 1, 2, { ...options, radialSegments: 20, heightSegments: 1 }) + ], + [ + "cone", + () => PrimitiveMesh.createCone(engine, 1, 2, { ...options }), + () => PrimitiveMesh.createCone(engine, 1, 2, { ...options, radialSegments: 20, heightSegments: 1 }) + ], + [ + "capsule", + () => PrimitiveMesh.createCapsule(engine, 1, 2, { ...options, radialSegments: 12 }), + () => + PrimitiveMesh.createCapsule(engine, 1, 2, { + ...options, + radialSegments: 12, + capSegments: 12, + heightSegments: 1 + }) + ], + [ + "torus", + () => PrimitiveMesh.createTorus(engine, 1, 0.2, { ...options }), + () => PrimitiveMesh.createTorus(engine, 1, 0.2, { ...options, ringSegments: 30, radialSegments: 30 }) + ], + [ + "circle", + () => PrimitiveMesh.createCircle(engine, 1, { ...options }), + () => PrimitiveMesh.createCircle(engine, 1, { ...options, segments: 32 }) + ], + [ + "ring", + () => PrimitiveMesh.createRing(engine, 1, 0.5, { ...options }), + () => PrimitiveMesh.createRing(engine, 1, 0.5, { ...options, ringSegments: 32, widthSegments: 1 }) + ], + [ + "tetrahedron", + () => PrimitiveMesh.createTetrahedron(engine, 1, { ...options }), + () => PrimitiveMesh.createTetrahedron(engine, 1, { ...options, edgeSegments: 1 }) + ], + [ + "octahedron", + () => PrimitiveMesh.createOctahedron(engine, 1, { ...options }), + () => PrimitiveMesh.createOctahedron(engine, 1, { ...options, edgeSegments: 1 }) + ], + [ + "icosahedron", + () => PrimitiveMesh.createIcosahedron(engine, 1, { ...options }), + () => PrimitiveMesh.createIcosahedron(engine, 1, { ...options, edgeSegments: 1 }) + ], + [ + "dodecahedron", + () => PrimitiveMesh.createDodecahedron(engine, 1, { ...options }), + () => PrimitiveMesh.createDodecahedron(engine, 1, { ...options, edgeSegments: 1 }) + ], + [ + "revolvedSurface", + () => PrimitiveMesh.createRevolvedSurface(engine, profile, { ...options }), + () => PrimitiveMesh.createRevolvedSurface(engine, profile, { ...options, segments: 12 }) + ], + [ + "tube", + () => PrimitiveMesh.createTube(engine, path, 0.2, { ...options }), + () => PrimitiveMesh.createTube(engine, path, 0.2, { ...options, pathSegments: 64, radialSegments: 8 }) + ], + [ + "depth extrusion", + () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { ...options }), + () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { ...options, depthSegments: 1 }) + ], + [ + "path extrusion", + () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, { ...options }), + () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, { ...options, pathSegments: 1 }) + ], + [ + "torus knot", + () => PrimitiveMesh.createTorusKnot(engine, 1, 0.2, 2, 3, { ...options }), + () => PrimitiveMesh.createTorusKnot(engine, 1, 0.2, 2, 3, { ...options, pathSegments: 64, radialSegments: 8 }) + ], + [ + "rounded cuboid", + () => PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0.2, { ...options }), + () => PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0.2, { ...options, roundingSegments: 2 }) + ] + ]; + + it.each(cases)("uses the same defaults for %s", (_name, createWithDefaults, createWithExplicitDefaults) => { + const withDefaults = createWithDefaults(); + const withExplicitDefaults = createWithExplicitDefaults(); + try { + expect(withDefaults.getPositions()).toEqual(withExplicitDefaults.getPositions()); + expect(withDefaults.getNormals()).toEqual(withExplicitDefaults.getNormals()); + expect(withDefaults.getUVs()).toEqual(withExplicitDefaults.getUVs()); + expect(withDefaults.getIndices()).toEqual(withExplicitDefaults.getIndices()); + expect(withDefaults.subMeshes.map(({ start, count }) => [start, count])).toEqual( + withExplicitDefaults.subMeshes.map(({ start, count }) => [start, count]) + ); + } finally { + withDefaults.destroy(); + withExplicitDefaults.destroy(); + } + }); + + it.each([0.5, 1])("derives a valid ring from outer radius %s", (radius) => { + const mesh = PrimitiveMesh.createRing(engine, radius, radius / 2, { ...options }); + const defaultMesh = PrimitiveMesh.createRing(engine, radius, radius / 2); + try { + const positions = mesh.getPositions()!; + const indices = mesh.getIndices()!; + expect(defaultMesh.bounds.max.x).toBeCloseTo(radius); + expect(Math.min(...positions.map(({ x, y }) => Math.hypot(x, y)))).toBeCloseTo(radius / 2); + expect(Math.max(...positions.map(({ x, y }) => Math.hypot(x, y)))).toBeCloseTo(radius); + for (let i = 0; i < indices.length; i += 3) { + const a = positions[indices[i]]; + const b = positions[indices[i + 1]]; + const c = positions[indices[i + 2]]; + expect((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)).toBeGreaterThan(0); + } + } finally { + mesh.destroy(); + defaultMesh.destroy(); + } + }); +}); + +describe("procedural mesh geometry", () => { + it("uses explicit dimensions and default subdivision settings", () => { + const cube = PrimitiveMesh.createCuboid(engine, 2, 2, 2); + const plane = PrimitiveMesh.createPlane(engine, 3, 3); + const sphere = PrimitiveMesh.createSphere(engine, 1); + const detailedSphere = PrimitiveMesh.createSphere(engine, 1, { subdivisionLevel: 4 }); + try { + expect(cube.bounds.min).toMatchObject({ x: -1, y: -1, z: -1 }); + expect(cube.bounds.max).toMatchObject({ x: 1, y: 1, z: 1 }); + expect(plane.bounds.max).toMatchObject({ x: 1.5, y: 0, z: 1.5 }); + expect(sphere.vertexCount).toBe(417); + expect(detailedSphere.vertexCount).toBe(1585); + } finally { + cube.destroy(); + plane.destroy(); + sphere.destroy(); + detailedSphere.destroy(); + } + }); + + it("distinguishes cylinders from frustums and selects end caps independently", () => { + const cylinder = PrimitiveMesh.createCylinder(engine, 1, 3); + const frustum = PrimitiveMesh.createTruncatedCone(engine, 0.5, 1.5, 4); + const topOnly = PrimitiveMesh.createCylinder(engine, 1, 3, { + caps: PrimitiveMeshCapMode.Top, + keepMeshData: true, + radialSegments: 8, + heightSegments: 1 + }); + try { + expect(cylinder.bounds.max).toMatchObject({ x: 1, y: 1.5, z: 1 }); + expect(frustum.bounds.max).toMatchObject({ x: 1.5, y: 2, z: 1.5 }); + expect(topOnly.getIndices()!.length).toBe(72); + expect(topOnly.getNormals()!.some((normal) => normal.y === 1)).toBe(true); + expect(topOnly.getNormals()!.some((normal) => normal.y === -1)).toBe(false); + } finally { + cylinder.destroy(); + frustum.destroy(); + topOnly.destroy(); + } + }); + + const cylinderOptions = { keepMeshData: true, radialSegments: 4, heightSegments: 2 }; + it.each([ + { name: "cylinder", topRadius: 2, create: () => PrimitiveMesh.createCylinder(engine, 2, 3, cylinderOptions) }, + { + name: "truncated cone", + topRadius: 0.5, + create: () => PrimitiveMesh.createTruncatedCone(engine, 0.5, 2, 3, cylinderOptions) + }, + { name: "cone", topRadius: 0, create: () => PrimitiveMesh.createCone(engine, 2, 3, cylinderOptions) } + ])("preserves the side seam and cap UV orientation of a $name", ({ create, topRadius }) => { + const mesh = create(); + try { + const positions = mesh.getPositions()!; + const normals = mesh.getNormals()!; + const uvs = mesh.getUVs()!; + expect(positions[0].x).toBeCloseTo(0); + expect(positions[0].z).toBeCloseTo(-2); + expect(uvs[0]).toMatchObject({ x: 0, y: 1 }); + expect(positions[1].x).toBeCloseTo(-2); + expect(uvs[1]).toMatchObject({ x: 0.25, y: 1 }); + expect(positions[4].z).toBeCloseTo(-2); + expect(uvs[4]).toMatchObject({ x: 1, y: 1 }); + expect(uvs[10]).toMatchObject({ x: 0, y: 0 }); + expect(uvs.every(({ x, y }) => Number.isFinite(x) && Number.isFinite(y))).toBe(true); + for (const [radius, height] of [ + [2, -1.5], + [topRadius, 1.5] + ]) { + if (radius === 0) { + continue; + } + for (const [x, z, u, v] of [ + [radius, 0, 1, 0.5], + [-radius, 0, 0, 0.5], + [0, radius, 0.5, 0], + [0, -radius, 0.5, 1], + [0, 0, 0.5, 0.5] + ]) { + const index = positions.findIndex( + (position, i) => + normals[i].y === Math.sign(height) && + Math.abs(position.x - x) < 1e-6 && + Math.abs(position.y - height) < 1e-6 && + Math.abs(position.z - z) < 1e-6 + ); + expect(index).toBeGreaterThanOrEqual(0); + expect(uvs[index].x).toBeCloseTo(u); + expect(uvs[index].y).toBeCloseTo(v); + } + } + } finally { + mesh.destroy(); + } + }); + + it("measures cylinder sections from the side seam at -Z", () => { + const mesh = PrimitiveMesh.createCylinder(engine, 2, 3, { + ...cylinderOptions, + angleRange: new Vector2(90, 180) + }); + try { + const positions = mesh.getPositions()!; + const uvs = mesh.getUVs()!; + expect(positions[0].x).toBeCloseTo(-2); + expect(positions[0].z).toBeCloseTo(0); + expect(positions[4].x).toBeCloseTo(0); + expect(positions[4].z).toBeCloseTo(2); + expect(uvs[0]).toMatchObject({ x: 0, y: 1 }); + expect(uvs[4]).toMatchObject({ x: 1, y: 1 }); + } finally { + mesh.destroy(); + } + }); + + it.each([false, true])("preserves cylinder cap order with separate material slots: %s", (separateMaterialSlots) => { + const mesh = PrimitiveMesh.createCylinder(engine, 2, 3, { ...cylinderOptions, separateMaterialSlots }); + try { + const indices = mesh.getIndices()!; + const normals = mesh.getNormals()!; + const capNormals: number[] = []; + for (let i = 48; i < indices.length; i += 3) { + capNormals.push(normals[indices[i]].y); + } + expect(capNormals).toEqual(separateMaterialSlots ? [1, 1, 1, 1, -1, -1, -1, -1] : [-1, 1, -1, 1, -1, 1, -1, 1]); + } finally { + mesh.destroy(); + } + }); + + it("uses one polygon algorithm for contours and polygons with holes", () => { + const fromContours = PrimitiveMesh.createPolygon( + engine, + { points: polygon.points, holes: polygon.holes }, + { keepMeshData: true } + ); + const fromShape = PrimitiveMesh.createPolygon(engine, polygon, { keepMeshData: true }); + const withoutHoles = PrimitiveMesh.createPolygon(engine, polygon.points, { keepMeshData: true }); + try { + expect(Array.from(fromContours.getIndices()!)).toEqual(Array.from(fromShape.getIndices()!)); + expect(withoutHoles.getIndices()!.length).toBe(6); + } finally { + fromContours.destroy(); + fromShape.destroy(); + withoutHoles.destroy(); + } + }); + + it("honors offset angular ranges for torus sections", () => { + const mesh = PrimitiveMesh.createTorus(engine, 1, 0.25, { + keepMeshData: true, + ringAngleRange: new Vector2(90, 180), + ringSegments: 8, + radialSegments: 6 + }); + try { + const first = mesh.getPositions()![0]; + expect(first.x).toBeCloseTo(0); + expect(first.y).toBeCloseTo(1.25); + } finally { + mesh.destroy(); + } + }); + + it.each([ + { axisTurns: 2, crossSectionTurns: 3, expected: new Vector3(1, Math.sqrt(3), 1) }, + { axisTurns: 2, crossSectionTurns: -3, expected: new Vector3(1, Math.sqrt(3), -1) }, + { axisTurns: -2, crossSectionTurns: 3, expected: new Vector3(1, -Math.sqrt(3), 1) }, + { axisTurns: -2, crossSectionTurns: -3, expected: new Vector3(1, -Math.sqrt(3), -1) }, + { axisTurns: 0, crossSectionTurns: 1, expected: new Vector3(2 + Math.sqrt(3) / 2, 0, 0.5) }, + { axisTurns: 1, crossSectionTurns: 0, expected: new Vector3((3 * Math.sqrt(3)) / 2, 1.5, 0) } + ])( + "preserves torus knot windings axisTurns=$axisTurns, crossSectionTurns=$crossSectionTurns during creation and restoration", + ({ axisTurns, crossSectionTurns, expected }) => { + const radialSegments = 8; + const mesh = PrimitiveMesh.createTorusKnot(engine, 2, 0.2, axisTurns, crossSectionTurns, { + keepMeshData: true, + pathSegments: 48, + radialSegments + }); + try { + const positions = mesh.getPositions()!; + const center = new Vector3(); + for (let i = 0; i < radialSegments; i++) { + center.add(positions[4 * (radialSegments + 1) + i]); + } + center.scale(1 / radialSegments); + expect(Vector3.distance(center, expected)).toBeLessThan(1e-6); + + const buffer = mesh.vertexBufferBindings[0]!.buffer; + const original = buffer.data!.slice(); + MeshTestUtils.clearBuffer(buffer); + (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); + expect(MeshTestUtils.readBuffer(buffer)).toEqual(original); + } finally { + mesh.destroy(); + } + } + ); + + it.each([ + { radialSegments: 3, capSegments: 1, heightSegments: 1 }, + { radialSegments: 8, capSegments: 4, heightSegments: 1 }, + { radialSegments: 13, capSegments: 7, heightSegments: 3 } + ])( + "centers capsule pole UVs with $radialSegments radial segments", + ({ radialSegments, capSegments, heightSegments }) => { + const mesh = PrimitiveMesh.createCapsule(engine, 1, 2, { + keepMeshData: true, + radialSegments, + capSegments, + heightSegments + }); + try { + const positions = mesh.getPositions()!; + const uvs = mesh.getUVs()!; + const indices = mesh.getIndices()!; + const poleTriangles = [0, 0]; + for (let i = 0; i < indices.length; i += 3) { + const triangle = [indices[i], indices[i + 1], indices[i + 2]]; + const pole = triangle.find((index) => Math.abs(positions[index].y) === 2); + if (pole !== undefined) { + const edge = triangle.filter((index) => index !== pole); + expect(uvs[pole].x).toBeCloseTo((uvs[edge[0]].x + uvs[edge[1]].x) / 2, 6); + expect(uvs[pole].x).toBeGreaterThan(0); + expect(uvs[pole].x).toBeLessThan(1); + const top = positions[pole].y > 0; + expect(uvs[pole].y).toBe(top ? 0 : 1); + poleTriangles[top ? 1 : 0]++; + } + } + expect(poleTriangles).toEqual([radialSegments, radialSegments]); + + const buffer = mesh.vertexBufferBindings[0]!.buffer; + const original = buffer.data!.slice(); + MeshTestUtils.clearBuffer(buffer); + (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); + expect(MeshTestUtils.readBuffer(buffer)).toEqual(original); + } finally { + mesh.destroy(); + } + } + ); + + it.each([ + { + segments: 1, + crossSection: [ + [0, 1], + [1, 0] + ] + }, + { + segments: 2, + crossSection: [ + [0, 1], + [Math.SQRT1_2, Math.SQRT1_2], + [1, 0] + ] + } + ])("preserves $segments segment(s) in a partial revolved surface", ({ segments, crossSection }) => { + const mesh = PrimitiveMesh.createRevolvedSurface(engine, [new Vector2(1, -1), new Vector2(1, 1)], { + keepMeshData: true, + angleRange: new Vector2(0, 90), + segments + }); + try { + expect(mesh.vertexCount).toBe(crossSection.length * 2); + expect(mesh.getIndices()!).toHaveLength(segments * 6); + const positions = mesh.getPositions()!; + for (let i = 0; i < crossSection.length; i++) { + const [x, z] = crossSection[i]; + for (let j = 0; j < 2; j++) { + const position = positions[i * 2 + j]; + expect(position.x).toBeCloseTo(x, 6); + expect(position.y).toBe(j === 0 ? -1 : 1); + expect(position.z).toBeCloseTo(z, 6); + } + } + + const buffer = mesh.vertexBufferBindings[0]!.buffer; + const original = buffer.data!.slice(); + MeshTestUtils.clearBuffer(buffer); + (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); + expect(MeshTestUtils.readBuffer(buffer)).toEqual(original); + } finally { + mesh.destroy(); + } + }); + + it.each([1, 4, 8])("maps rounded cuboid UVs by surface length with %s corner segments", (segments) => { + const sizes = { x: 2, y: 3, z: 4 }; + const radius = 0.25; + const mesh = PrimitiveMesh.createRoundedCuboid(engine, sizes.x, sizes.y, sizes.z, radius, { + keepMeshData: true, + separateMaterialSlots: true, + roundingSegments: segments + }); + const faces = [ + { axis: "y", sign: 1, u: "x", v: "z", flipU: false, flipV: false }, + { axis: "y", sign: -1, u: "x", v: "z", flipU: false, flipV: true }, + { axis: "x", sign: -1, u: "z", v: "y", flipU: false, flipV: true }, + { axis: "x", sign: 1, u: "z", v: "y", flipU: true, flipV: true }, + { axis: "z", sign: 1, u: "x", v: "y", flipU: false, flipV: true }, + { axis: "z", sign: -1, u: "x", v: "y", flipU: true, flipV: true } + ] as const; + try { + const positions = mesh.getPositions()!; + const normals = mesh.getNormals()!; + const uvs = mesh.getUVs()!; + const indices = mesh.getIndices()!; + expect(mesh.subMeshes).toHaveLength(6); + mesh.subMeshes.forEach(({ start, count }, faceIndex) => { + const face = faces[faceIndex]; + const flatVertices = [...new Set(indices.subarray(start, start + count))].filter( + (index) => normals[index][face.axis] === face.sign + ); + expect(flatVertices).toHaveLength(4); + const uEdge = (Math.PI * radius) / 4 / (sizes[face.u] - 2 * radius + (Math.PI * radius) / 2); + const vEdge = (Math.PI * radius) / 4 / (sizes[face.v] - 2 * radius + (Math.PI * radius) / 2); + for (const index of flatVertices) { + const position = positions[index]; + expect(position[face.axis]).toBeCloseTo((face.sign * sizes[face.axis]) / 2, 6); + expect(uvs[index].x).toBeCloseTo(position[face.u] < 0 !== face.flipU ? uEdge : 1 - uEdge, 6); + expect(uvs[index].y).toBeCloseTo(position[face.v] < 0 !== face.flipV ? vEdge : 1 - vEdge, 6); + } + }); + + const buffer = mesh.vertexBufferBindings[0]!.buffer; + const original = buffer.data!.slice(); + MeshTestUtils.clearBuffer(buffer); + (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); + expect(MeshTestUtils.readBuffer(buffer)).toEqual(original); + } finally { + mesh.destroy(); + } + }); + + it("handles rounded cuboid radius and segment limits without changing the cuboid fallback", () => { + const options = { keepMeshData: true, separateMaterialSlots: true }; + const meshes = [ + PrimitiveMesh.createCuboid(engine, 2, 3, 4, { + ...options, + widthSegments: 1, + heightSegments: 1, + depthSegments: 1 + }), + PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0, { ...options, roundingSegments: 4 }), + PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, -1, { ...options, roundingSegments: 4 }), + PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 1, { ...options, roundingSegments: 3 }), + PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 8, { ...options, roundingSegments: 3 }), + PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0.2, { ...options, roundingSegments: 0 }), + PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0.2, { ...options, roundingSegments: 1 }) + ]; + try { + for (const [a, b] of [ + [0, 1], + [0, 2], + [3, 4], + [5, 6] + ]) { + expect(meshes[a].vertexBufferBindings[0]!.buffer.data).toEqual(meshes[b].vertexBufferBindings[0]!.buffer.data); + expect(meshes[a].getIndices()).toEqual(meshes[b].getIndices()); + } + } finally { + meshes.forEach((mesh) => mesh.destroy()); + } + }); + + it.each([ + { width: 2, height: 2, depth: 2, radius: 1 }, + { width: 2, height: 3, depth: 4, radius: 1 }, + { width: 2, height: 3, depth: 4, radius: 0.0001 } + ])("keeps rounded cuboid attributes valid at radius $radius for $width x $height x $depth", (shape) => { + const { width, height, depth, radius } = shape; + const mesh = PrimitiveMesh.createRoundedCuboid(engine, width, height, depth, radius, { + keepMeshData: true, + roundingSegments: 4 + }); + try { + const positions = mesh.getPositions()!; + const normals = mesh.getNormals()!; + const uvs = mesh.getUVs()!; + const inner = new Vector3(width / 2 - radius, height / 2 - radius, depth / 2 - radius); + for (let i = 0; i < positions.length; i++) { + const p = positions[i]; + const nearest = new Vector3( + Math.max(-inner.x, Math.min(inner.x, p.x)), + Math.max(-inner.y, Math.min(inner.y, p.y)), + Math.max(-inner.z, Math.min(inner.z, p.z)) + ); + expect(Vector3.distance(p, nearest)).toBeCloseTo(radius, 6); + expect(normals[i].length()).toBeCloseTo(1, 6); + expect(uvs[i].x).toBeGreaterThanOrEqual(-1e-6); + expect(uvs[i].x).toBeLessThanOrEqual(1 + 1e-6); + expect(uvs[i].y).toBeGreaterThanOrEqual(-1e-6); + expect(uvs[i].y).toBeLessThanOrEqual(1 + 1e-6); + } + expect(mesh.bounds.min.toJSON()).toEqual({ x: -width / 2, y: -height / 2, z: -depth / 2 }); + expect(mesh.bounds.max.toJSON()).toEqual({ x: width / 2, y: height / 2, z: depth / 2 }); + } finally { + mesh.destroy(); + } + }); + + it.each([false, true])("controls all generated vertex data through keepMeshData=%s", (keepMeshData) => { + const mesh = PrimitiveMesh.createSphere(engine, 0.5, { keepMeshData, subdivisionLevel: 1 }); + try { + for (const binding of mesh.vertexBufferBindings) { + expect(binding!.buffer.readable).toBe(keepMeshData); + } + if (keepMeshData) { + expect(mesh.getPositions()).toHaveLength(mesh.vertexCount); + expect(mesh.getNormals()).toHaveLength(mesh.vertexCount); + expect(mesh.getTangents()).toHaveLength(mesh.vertexCount); + expect(mesh.getUVs()).toHaveLength(mesh.vertexCount); + expect(mesh.getIndices()!.length).toBeGreaterThan(0); + } else { + expect(() => mesh.getPositions()).toThrow(); + expect(() => mesh.getNormals()).toThrow(); + expect(() => mesh.getTangents()).toThrow(); + expect(() => mesh.getUVs()).toThrow(); + expect(() => mesh.getIndices()).toThrow(); + } + } finally { + mesh.destroy(); + } + }); + + it.each(creators)("generates finite attributes and valid winding for %s", (_name, create) => { + const mesh = create(); + try { + const positions = mesh.getPositions()!; + const normals = mesh.getNormals()!; + const uvs = mesh.getUVs()!; + const tangents = mesh.getTangents()!; + const indices = mesh.getIndices()!; + expect(indices.length).toBeGreaterThan(0); + for (const index of indices) { + expect(index).toBeLessThan(positions.length); + const p = positions[index]; + const n = normals[index]; + const t = tangents[index]; + expect( + [p.x, p.y, p.z, n.x, n.y, n.z, uvs[index].x, uvs[index].y, t.x, t.y, t.z, t.w].every(Number.isFinite) + ).toBe(true); + expect(n.length()).toBeCloseTo(1, 5); + expect(p.x).toBeGreaterThanOrEqual(mesh.bounds.min.x - 1e-6); + expect(p.y).toBeGreaterThanOrEqual(mesh.bounds.min.y - 1e-6); + expect(p.z).toBeGreaterThanOrEqual(mesh.bounds.min.z - 1e-6); + expect(p.x).toBeLessThanOrEqual(mesh.bounds.max.x + 1e-6); + expect(p.y).toBeLessThanOrEqual(mesh.bounds.max.y + 1e-6); + expect(p.z).toBeLessThanOrEqual(mesh.bounds.max.z + 1e-6); + } + const ab = new Vector3(); + const ac = new Vector3(); + const normal = new Vector3(); + for (let i = 0; i < indices.length; i += 3) { + const a = positions[indices[i]]; + Vector3.subtract(positions[indices[i + 1]], a, ab); + Vector3.subtract(positions[indices[i + 2]], a, ac); + Vector3.cross(ab, ac, normal); + expect(Vector3.dot(normal, normals[indices[i]])).toBeGreaterThanOrEqual(-1e-6); + } + } finally { + mesh.destroy(); + } + }); + + it("keeps sphere tangents perpendicular at non-unit radii", () => { + const mesh = PrimitiveMesh.createSphere(engine, 2, { keepMeshData: true, subdivisionLevel: 3 }); + try { + expect(mesh.vertexCount).toBe(417); + expect(mesh.getIndices()!.length / 3).toBe(768); + const normals = mesh.getNormals()!; + const tangents = mesh.getTangents()!; + for (const index of mesh.getIndices()!) { + const n = normals[index]; + const t = tangents[index]; + expect(n.x * t.x + n.y * t.y + n.z * t.z).toBeCloseTo(0, 5); + } + } finally { + mesh.destroy(); + } + }); + + it("supports a northern hemisphere", () => { + const mesh = PrimitiveMesh.createSphere(engine, 0.5, { + keepMeshData: true, + verticalAngleRange: new Vector2(0, 90), + subdivisionLevel: 2 + }); + try { + expect(mesh.getPositions()!.every((p) => p.y >= -1e-7)).toBe(true); + } finally { + mesh.destroy(); + } + }); + + it.each([ + { horizontal: [0, 360], vertical: [0, 90] }, + { horizontal: [90, 270], vertical: [0, 180] }, + { horizontal: [350, 370], vertical: [30, 150] }, + { horizontal: [20, 290], vertical: [30, 150] }, + { horizontal: [0, 360], vertical: [80, 85] }, + { horizontal: [0, 90], vertical: [0, 10] } + ])("clips a sphere to $horizontal and $vertical without cracks", ({ horizontal, vertical }) => { + const radius = 2; + const mesh = PrimitiveMesh.createSphere(engine, radius, { + keepMeshData: true, + horizontalAngleRange: new Vector2(horizontal[0], horizontal[1]), + verticalAngleRange: new Vector2(vertical[0], vertical[1]), + subdivisionLevel: 3 + }); + try { + const positions = mesh.getPositions()!; + const normals = mesh.getNormals()!; + const uvs = mesh.getUVs()!; + const indices = mesh.getIndices()!; + const edges = new Map(); + const sidePlanes = horizontal.map((angle) => { + const radians = (angle * Math.PI) / 180; + return new Vector3(Math.sin(radians), 0, Math.cos(radians)); + }); + const latitudeHeights = vertical.map((angle) => radius * Math.cos((angle * Math.PI) / 180)); + expect(indices.length).toBeGreaterThan(0); + for (const position of positions) { + expect(position.length()).toBeCloseTo(radius, 6); + const latitude = (Math.acos(Math.max(-1, Math.min(1, position.y / radius))) * 180) / Math.PI; + expect(latitude).toBeGreaterThanOrEqual(vertical[0] - 1e-5); + expect(latitude).toBeLessThanOrEqual(vertical[1] + 1e-5); + if (Math.hypot(position.x, position.z) > 1e-7) { + let longitude = (Math.atan2(position.z, -position.x) * 180) / Math.PI; + while (longitude < horizontal[0] - 1e-5) { + longitude += 360; + } + expect(longitude).toBeLessThanOrEqual(horizontal[1] + 1e-5); + } + } + for (let i = 0; i < indices.length; i += 3) { + const triangle = [indices[i], indices[i + 1], indices[i + 2]]; + const a = positions[triangle[0]]; + const ab = positions[triangle[1]].clone().subtract(a); + const ac = positions[triangle[2]].clone().subtract(a); + Vector3.cross(ab, ac, ab); + expect(Vector3.dot(ab, normals[triangle[0]])).toBeGreaterThan(1e-10); + expect(triangle.every((index) => Number.isFinite(uvs[index].x) && Number.isFinite(uvs[index].y))).toBe(true); + for (let edge = 0; edge < 3; edge++) { + const a = positions[triangle[edge]]; + const b = positions[triangle[(edge + 1) % 3]]; + const key = [a, b] + .map((point) => [point.x, point.y, point.z].map((value) => value.toFixed(6)).join(",")) + .sort() + .join("/"); + const existing = edges.get(key); + if (existing) { + existing.count++; + } else { + edges.set(key, { a, b, count: 1 }); + } + } + } + for (const { a, b, count } of edges.values()) { + expect(count).toBeLessThanOrEqual(2); + if (count === 1) { + const onLatitude = latitudeHeights.some( + (height) => Math.abs(a.y - height) < 1e-5 && Math.abs(b.y - height) < 1e-5 + ); + const onLongitude = + horizontal[1] - horizontal[0] < 360 && + sidePlanes.some( + (normal) => Math.abs(Vector3.dot(a, normal)) < 1e-5 && Math.abs(Vector3.dot(b, normal)) < 1e-5 + ); + expect(onLatitude || onLongitude).toBe(true); + } + } + } finally { + mesh.destroy(); + } + }); + + it("rotates complete spheres without changing topology", () => { + const original = PrimitiveMesh.createSphere(engine, 1, { keepMeshData: true, subdivisionLevel: 2 }); + const rotated = PrimitiveMesh.createSphere(engine, 1, { + keepMeshData: true, + horizontalAngleRange: new Vector2(90, 450), + subdivisionLevel: 2 + }); + try { + expect(rotated.getIndices()).toEqual(original.getIndices()); + expect(rotated.getUVs()).toEqual(original.getUVs()); + const positions = original.getPositions()!; + rotated.getPositions()!.forEach((position, i) => { + expect(position.x).toBeCloseTo(positions[i].z, 6); + expect(position.y).toBeCloseTo(positions[i].y, 6); + expect(position.z).toBeCloseTo(-positions[i].x, 6); + }); + } finally { + original.destroy(); + rotated.destroy(); + } + }); + + it("captures sphere ranges for device restoration", () => { + const horizontalAngleRange = new Vector2(20, 290); + const verticalAngleRange = new Vector2(30, 150); + const mesh = PrimitiveMesh.createSphere(engine, 1, { + horizontalAngleRange, + verticalAngleRange, + subdivisionLevel: 3 + }); + try { + const buffer = mesh.vertexBufferBindings[0]!.buffer; + const original = MeshTestUtils.readBuffer(buffer); + horizontalAngleRange.y = 360; + verticalAngleRange.x = 0; + MeshTestUtils.clearBuffer(buffer); + (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); + expect(MeshTestUtils.readBuffer(buffer)).toEqual(original); + } finally { + mesh.destroy(); + } + }); + + it("omits cylinder caps and makes material groups opt-in", () => { + const open = PrimitiveMesh.createCylinder(engine, 0.5, 2, { + keepMeshData: true, + caps: PrimitiveMeshCapMode.None, + radialSegments: 8, + heightSegments: 1 + }); + const grouped = PrimitiveMesh.createCylinder(engine, 0.5, 2, { + separateMaterialSlots: true, + radialSegments: 8, + heightSegments: 1 + }); + const cube = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { + separateMaterialSlots: true, + widthSegments: 1, + heightSegments: 1, + depthSegments: 1 + }); + try { + expect(open.getIndices()!.length).toBe(48); + expect(open.subMeshes.length).toBe(1); + expect(grouped.subMeshes.length).toBe(3); + expect(cube.subMeshes.length).toBe(6); + } finally { + open.destroy(); + grouped.destroy(); + cube.destroy(); + } + }); + + it("orders cuboid material slots by face direction", () => { + const mesh = PrimitiveMesh.createCuboid(engine, 1, 2, 3, { + keepMeshData: true, + separateMaterialSlots: true, + widthSegments: 1, + heightSegments: 1, + depthSegments: 1 + }); + try { + const indices = mesh.getIndices()!; + const normals = mesh.getNormals()!; + expect(mesh.subMeshes.map(({ start }) => normals[indices[start]].toJSON())).toEqual([ + { x: 0, y: 1, z: 0 }, + { x: 0, y: -1, z: 0 }, + { x: -1, y: 0, z: 0 }, + { x: 1, y: 0, z: 0 }, + { x: 0, y: 0, z: 1 }, + { x: 0, y: 0, z: -1 } + ]); + } finally { + mesh.destroy(); + } + }); + + it.each([ + { + name: "cylinder with both caps", + create: () => + PrimitiveMesh.createCylinder(engine, 1, 2, { + keepMeshData: true, + separateMaterialSlots: true, + radialSegments: 8, + heightSegments: 1 + }), + parts: ["side", "top", "bottom"] + }, + { + name: "cylinder with only its top cap", + create: () => + PrimitiveMesh.createCylinder(engine, 1, 2, { + keepMeshData: true, + separateMaterialSlots: true, + caps: PrimitiveMeshCapMode.Top, + radialSegments: 8, + heightSegments: 1 + }), + parts: ["side", "top"] + }, + { + name: "cylinder with only its bottom cap", + create: () => + PrimitiveMesh.createCylinder(engine, 1, 2, { + keepMeshData: true, + separateMaterialSlots: true, + caps: PrimitiveMeshCapMode.Bottom, + radialSegments: 8, + heightSegments: 1 + }), + parts: ["side", "bottom"] + }, + { + name: "cylinder without caps", + create: () => + PrimitiveMesh.createCylinder(engine, 1, 2, { + keepMeshData: true, + separateMaterialSlots: true, + caps: PrimitiveMeshCapMode.None, + radialSegments: 8, + heightSegments: 1 + }), + parts: ["side"] + }, + { + name: "truncated cone with a zero top radius", + create: () => + PrimitiveMesh.createTruncatedCone(engine, 0, 1, 2, { + keepMeshData: true, + separateMaterialSlots: true, + radialSegments: 8, + heightSegments: 1 + }), + parts: ["side", "bottom"] + }, + { + name: "truncated cone with a zero bottom radius", + create: () => + PrimitiveMesh.createTruncatedCone(engine, 1, 0, 2, { + keepMeshData: true, + separateMaterialSlots: true, + radialSegments: 8, + heightSegments: 1 + }), + parts: ["side", "top"] + }, + { + name: "cone with its bottom cap", + create: () => + PrimitiveMesh.createCone(engine, 1, 2, { + keepMeshData: true, + separateMaterialSlots: true, + radialSegments: 8, + heightSegments: 1 + }), + parts: ["side", "bottom"] + }, + { + name: "cone without its bottom cap", + create: () => + PrimitiveMesh.createCone(engine, 1, 2, { + keepMeshData: true, + separateMaterialSlots: true, + cap: false, + radialSegments: 8, + heightSegments: 1 + }), + parts: ["side"] + } + ])("uses consecutive material slots for $name", ({ create, parts }) => { + const mesh = create(); + try { + const indices = mesh.getIndices()!; + const normals = mesh.getNormals()!; + expect( + mesh.subMeshes.map(({ start }) => { + const normalY = normals[indices[start]].y; + return normalY === 1 ? "top" : normalY === -1 ? "bottom" : "side"; + }) + ).toEqual(parts); + } finally { + mesh.destroy(); + } + }); + + it("assigns one material slot to each polygon including its holes", () => { + const shapes = [polygon, { points: polygon.points.map(({ x, y }) => new Vector2(x + 6, y)) }]; + const mesh = PrimitiveMesh.createPolygon(engine, shapes, { keepMeshData: true, separateMaterialSlots: true }); + try { + const indices = mesh.getIndices()!; + const positions = mesh.getPositions()!; + expect(mesh.subMeshes).toHaveLength(2); + mesh.subMeshes.forEach(({ start, count }, shapeIndex) => { + const groupIndices = indices.subarray(start, start + count); + expect(Array.from(groupIndices).every((index) => (positions[index].x > 3 ? 1 : 0) === shapeIndex)).toBe(true); + }); + } finally { + mesh.destroy(); + } + }); + + it("orders each extruded shape's cap and wall material slots together", () => { + const shapes = [polygon, { points: polygon.points.map(({ x, y }) => new Vector2(x + 6, y)) }]; + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, shapes, 2, { + keepMeshData: true, + separateMaterialSlots: true, + depthSegments: 1 + }); + try { + const indices = mesh.getIndices()!; + const positions = mesh.getPositions()!; + const normals = mesh.getNormals()!; + expect(mesh.subMeshes).toHaveLength(4); + mesh.subMeshes.forEach(({ start, count }, slot) => { + const groupIndices = Array.from(indices.subarray(start, start + count)); + expect(groupIndices.every((index) => (positions[index].x > 3 ? 1 : 0) === Math.floor(slot / 2))).toBe(true); + const normalZ = new Set(groupIndices.map((index) => normals[index].z)); + expect(normalZ).toEqual(slot % 2 === 0 ? new Set([-1, 1]) : new Set([0])); + }); + } finally { + mesh.destroy(); + } + }); + + it.each([0.2, -0.2])("offsets extrusion walls and bevels by %s and restores their geometry", (contourOffset) => { + const options = { + keepMeshData: true, + separateMaterialSlots: true, + bevelWidth: 0.1, + bevelDepth: 0.2, + contourOffset + }; + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { ...options, depthSegments: 2 }); + try { + const outer = 2 + contourOffset; + const hole = 1 - contourOffset; + expect(mesh.bounds.min.x).toBeCloseTo(-outer); + expect(mesh.bounds.min.y).toBeCloseTo(-outer); + expect(mesh.bounds.min.z).toBe(0); + expect(mesh.bounds.max.x).toBeCloseTo(outer); + expect(mesh.bounds.max.y).toBeCloseTo(outer); + expect(mesh.bounds.max.z).toBe(2); + expect(mesh.subMeshes).toHaveLength(2); + const positions = mesh.getPositions()!; + for (const point of [ + new Vector3(outer, outer, 0.2), + new Vector3(hole, hole, 0.2), + new Vector3(outer - 0.1, outer - 0.1, 0), + new Vector3(hole + 0.1, hole + 0.1, 0), + new Vector3(outer - 0.1, outer - 0.1, 2), + new Vector3(hole + 0.1, hole + 0.1, 2) + ]) { + expect(positions.some((position) => Vector3.distance(position, point) < 1e-6)).toBe(true); + } + + const buffer = mesh.vertexBufferBindings[0]!.buffer; + const original = buffer.data!.slice(); + const indices = Array.from(mesh.getIndices()!); + options.contourOffset = 100; + MeshTestUtils.clearBuffer(buffer); + (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); + expect(MeshTestUtils.readBuffer(buffer)).toEqual(original); + expect(Array.from(mesh.getIndices()!)).toEqual(indices); + expect(mesh.subMeshes).toHaveLength(2); + } finally { + mesh.destroy(); + } + }); + + it.each([0.2, -0.2])("offsets extrusion contours by %s without adding bevels", (contourOffset) => { + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { + keepMeshData: true, + contourOffset, + depthSegments: 1 + }); + try { + const positions = mesh.getPositions()!; + expect(positions.every(({ z }) => z === 0 || z === 2)).toBe(true); + const indices = mesh.getIndices()!; + let topArea = 0; + for (let i = 0; i < indices.length; i += 3) { + const a = positions[indices[i]]; + const b = positions[indices[i + 1]]; + const c = positions[indices[i + 2]]; + if (a.z === 2 && b.z === 2 && c.z === 2) { + topArea += ((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)) / 2; + } + } + const outer = 2 + contourOffset; + const hole = 1 - contourOffset; + expect(topArea).toBeCloseTo(4 * (outer * outer - hole * hole), 5); + } finally { + mesh.destroy(); + } + }); + + it("triangulates holes without filling their interiors", () => { + const mesh = PrimitiveMesh.createPolygon(engine, polygon, { keepMeshData: true }); + try { + const positions = mesh.getPositions()!; + const indices = mesh.getIndices()!; + let area = 0; + for (let i = 0; i < indices.length; i += 3) { + const a = positions[indices[i]], + b = positions[indices[i + 1]], + c = positions[indices[i + 2]]; + area += ((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)) / 2; + const x = (a.x + b.x + c.x) / 3; + const y = (a.y + b.y + c.y) / 3; + expect(Math.abs(x) < 1 && Math.abs(y) < 1).toBe(false); + } + expect(area).toBeCloseTo(12, 6); + } finally { + mesh.destroy(); + } + }); + + const triangulationCases = [ + { + name: "concave outlines", + points: [ + new Vector2(0, 0), + new Vector2(4, 0), + new Vector2(4, 1), + new Vector2(1, 1), + new Vector2(1, 4), + new Vector2(0, 4) + ], + holes: [], + area: 7 + }, + { + name: "multiple holes", + points: [new Vector2(0, 0), new Vector2(10, 0), new Vector2(10, 6), new Vector2(0, 6)], + holes: [ + [new Vector2(1, 1), new Vector2(3, 1), new Vector2(3, 4), new Vector2(1, 4)], + [new Vector2(6, 2), new Vector2(9, 2), new Vector2(9, 5), new Vector2(6, 5)] + ], + area: 45 + }, + { + name: "collinear and repeated boundary vertices", + points: [ + new Vector2(0, 0), + new Vector2(2, 0), + new Vector2(2, 0), + new Vector2(4, 0), + new Vector2(4, 2), + new Vector2(2, 2), + new Vector2(0, 2), + new Vector2(0, 0) + ], + holes: [], + area: 8 + }, + { + name: "large concave rings with a hole", + points: Array.from({ length: 128 }, (_, i) => { + const angle = (i * Math.PI) / 64; + const radius = i % 2 === 0 ? 4 : 3; + return new Vector2(radius * Math.cos(angle), radius * Math.sin(angle)); + }), + holes: [ + Array.from({ length: 32 }, (_, i) => { + const angle = (i * Math.PI) / 16; + return new Vector2(Math.cos(angle), Math.sin(angle)); + }) + ], + area: 768 * Math.sin(Math.PI / 64) - 16 * Math.sin(Math.PI / 16) + } + ]; + + it.each(triangulationCases)("triangulates $name in either winding order", ({ points, holes, area }) => { + for (const reversed of [false, true]) { + const shape = { + points: reversed ? points.slice().reverse() : points, + holes: holes.map((hole) => (reversed ? hole : hole.slice().reverse())) + }; + const mesh = PrimitiveMesh.createPolygon(engine, shape, { keepMeshData: true }); + try { + const positions = mesh.getPositions()!; + const indices = mesh.getIndices()!; + let triangleArea = 0; + for (let i = 0; i < indices.length; i += 3) { + const a = positions[indices[i]]; + const b = positions[indices[i + 1]]; + const c = positions[indices[i + 2]]; + const signedArea = ((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)) / 2; + expect(signedArea).toBeGreaterThan(0); + triangleArea += signedArea; + + const x = (a.x + b.x + c.x) / 3; + const y = (a.y + b.y + c.y) / 3; + const contours = [shape.points, ...shape.holes]; + for (let contourIndex = 0; contourIndex < contours.length; contourIndex++) { + const contour = contours[contourIndex]; + let inside = false; + for (let j = 0, k = contour.length - 1; j < contour.length; k = j++) { + const p = contour[j]; + const q = contour[k]; + if (p.y > y !== q.y > y && x < ((q.x - p.x) * (y - p.y)) / (q.y - p.y) + p.x) { + inside = !inside; + } + } + expect(inside).toBe(contourIndex === 0); + } + } + expect(triangleArea).toBeCloseTo(area, 5); + } finally { + mesh.destroy(); + } + } + }); + + it("preserves multiple holes in extrusion caps and restored buffers", () => { + const { points, holes, area } = triangulationCases[1]; + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, { points, holes }, 3, { + keepMeshData: true, + depthSegments: 1 + }); + try { + const positions = mesh.getPositions()!; + const indices = Array.from(mesh.getIndices()!); + let topArea = 0; + let bottomArea = 0; + for (let i = 0; i < indices.length; i += 3) { + const a = positions[indices[i]]; + const b = positions[indices[i + 1]]; + const c = positions[indices[i + 2]]; + const signedArea = ((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)) / 2; + if (a.z === 0 && b.z === 0 && c.z === 0) { + bottomArea -= signedArea; + } else if (a.z === 3 && b.z === 3 && c.z === 3) { + topArea += signedArea; + } + } + expect(topArea).toBeCloseTo(area, 6); + expect(bottomArea).toBeCloseTo(area, 6); + const buffer = mesh.vertexBufferBindings[0]!.buffer; + const original = new Uint8Array(buffer.data!.buffer).slice(); + MeshTestUtils.clearBuffer(buffer); + (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); + expect(Array.from(mesh.getIndices()!)).toEqual(indices); + expect(MeshTestUtils.readBuffer(buffer)).toEqual(original); + } finally { + mesh.destroy(); + } + }); + + it.each([ + { type: "tube", tubeRadius: 0.5, keepMeshData: false }, + { type: "tube", tubeRadius: 0.5, keepMeshData: true }, + { type: "extrudedPolygon", extrudedPolygonDepth: 1, keepMeshData: false }, + { type: "extrudedPolygon", extrudedPolygonDepth: 1, keepMeshData: true } + ])("copies $type path points for device restoration with keepMeshData=$keepMeshData", ({ type, keepMeshData }) => { + const points = path.map((point) => point.clone()); + const mesh = + type === "tube" + ? PrimitiveMesh.createTube(engine, points, 0.5, { keepMeshData, pathSegments: 12, radialSegments: 8 }) + : PrimitiveMesh.createExtrudedPolygon(engine, polygon, points, { keepMeshData, pathSegments: 12 }); + try { + const buffers = mesh.vertexBufferBindings.map((binding) => binding!.buffer); + buffers.push(mesh._primitive.indexBufferBinding!._buffer); + const before = buffers.map((buffer) => MeshTestUtils.readBuffer(buffer)); + points[1].set(100, 200, 300); + points.push(new Vector3(400, 500, 600)); + buffers.forEach((buffer) => MeshTestUtils.clearBuffer(buffer)); + (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); + buffers.forEach((buffer, index) => { + expect(MeshTestUtils.readBuffer(buffer)).toEqual(before[index]); + }); + } finally { + mesh.destroy(); + } + }); + + it("restores primitive buffers after the default cache release", () => { + const mesh = PrimitiveMesh.createSphere(engine, 0.5); + try { + const restorer = (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId]; + const buffer = mesh.vertexBufferBindings[0]!.buffer; + const original = MeshTestUtils.readBuffer(buffer); + MeshTestUtils.clearBuffer(buffer); + expect(() => restorer.restoreContent()).not.toThrow(); + expect(() => restorer.restoreContent()).not.toThrow(); + expect(MeshTestUtils.readBuffer(buffer)).toEqual(original); + expect(buffer.readable).toBe(false); + } finally { + mesh.destroy(); + } + }); + + it("restores spheres independently after interleaved creation", () => { + const meshes = [ + PrimitiveMesh.createSphere(engine, 0.5, { keepMeshData: true, subdivisionLevel: 2 }), + PrimitiveMesh.createSphere(engine, 2, { keepMeshData: true, subdivisionLevel: 4 }) + ]; + const originals = meshes.map((mesh) => ({ + vertices: mesh.vertexBufferBindings[0]!.buffer.data!.slice(), + indices: Array.from(mesh.getIndices()!) + })); + try { + for (const index of [0, 1, 0]) { + const mesh = meshes[index]; + const buffer = mesh.vertexBufferBindings[0]!.buffer; + MeshTestUtils.clearBuffer(buffer); + (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); + expect(MeshTestUtils.readBuffer(buffer)).toEqual(originals[index].vertices); + expect(Array.from(mesh.getIndices()!)).toEqual(originals[index].indices); + } + } finally { + for (const mesh of meshes) { + mesh.destroy(); + } + } + }); + + it("uses 32-bit indices for subdivided meshes beyond 65535 vertices", () => { + const mesh = PrimitiveMesh.createPlane(engine, 1, 1, { + keepMeshData: true, + widthSegments: 256, + depthSegments: 256 + }); + try { + expect(mesh.vertexCount).toBe(66049); + expect(mesh.getIndices()).toBeInstanceOf(Uint32Array); + } finally { + mesh.destroy(); + } + }); + it.each([1, 2])("keeps the radius of a closed tube with %s longitudinal segments", (segments) => { + const path = [new Vector3(-2, 0, -2), new Vector3(2, 0, -2), new Vector3(2, 0, 2), new Vector3(-2, 0, 2)]; + const mesh = PrimitiveMesh.createTube(engine, path, 0.5, { + keepMeshData: true, + closedPath: true, + pathSegments: segments, + radialSegments: 8 + }); + try { + expect(mesh.vertexCount).toBe((segments + 1) * 9); + const positions = mesh.getPositions()!; + const normals = mesh.getNormals()!; + for (let row = 0; row <= segments; row++) { + const center = segments === 2 && row === 1 ? path[2] : path[0]; + for (let i = 0; i <= 8; i++) { + const vertex = row * 9 + i; + expect(Vector3.distance(positions[vertex], center)).toBeCloseTo(0.5, 6); + expect(normals[vertex].length()).toBeCloseTo(1, 6); + } + } + } finally { + mesh.destroy(); + } + }); + + it.each([1, 2])("keeps torus-knot cross-sections with %s longitudinal segments", (segments) => { + const mesh = PrimitiveMesh.createTorusKnot(engine, 1, 0.2, 2, 3, { + keepMeshData: true, + pathSegments: segments, + radialSegments: 8 + }); + try { + const positions = mesh.getPositions()!; + const normals = mesh.getNormals()!; + for (let row = 0; row <= segments; row++) { + const center = new Vector3(segments === 2 && row === 1 ? 0.5 : 1.5, 0, 0); + for (let i = 0; i <= 8; i++) { + const vertex = row * 9 + i; + expect(Vector3.distance(positions[vertex], center)).toBeCloseTo(0.2, 6); + expect(normals[vertex].length()).toBeCloseTo(1, 6); + } + } + } finally { + mesh.destroy(); + } + }); + + it("rejects a torus knot without either winding", () => { + expect(() => PrimitiveMesh.createTorusKnot(engine, 1, 0.2, 0, 0)).toThrow("at least one nonzero winding"); + }); + + it("closes tube frames without a position or normal seam", () => { + const radialSegments = 8; + const points = Array.from({ length: 40 }, (_, i) => { + const angle = (i / 40) * Math.PI * 2; + return new Vector3(Math.cos(angle), Math.sin(angle), Math.sin(angle * 2) / 3); + }); + const mesh = PrimitiveMesh.createTube(engine, points, 0.5, { + keepMeshData: true, + closedPath: true, + pathSegments: 40, + radialSegments + }); + try { + const positions = mesh.getPositions()!; + const normals = mesh.getNormals()!; + for (let i = 0; i <= radialSegments; i++) { + const end = positions.length - radialSegments - 1 + i; + expect(Vector3.distance(positions[i], positions[end])).toBeLessThan(1e-6); + expect(Vector3.distance(normals[i], normals[end])).toBeLessThan(1e-6); + } + } finally { + mesh.destroy(); + } + }); + + it.each([0, 0.4])("closes extrusion cross-sections without caps on a path of height %s", (height) => { + const points = Array.from({ length: 16 }, (_, i) => { + const angle = (i / 16) * Math.PI * 2; + return new Vector3(3 * Math.cos(angle), 3 * Math.sin(angle), height * Math.sin(angle * 2)); + }); + const originalPoints = points.map((point) => point.toJSON()); + const profile = [new Vector2(0.2, 0), new Vector2(-0.1, 0.1), new Vector2(-0.1, -0.1)]; + const options = { keepMeshData: true, closedPath: true }; + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, profile, points, { ...options, pathSegments: 32 }); + const repeated = PrimitiveMesh.createExtrudedPolygon(engine, profile, [...points, points[0].clone()], { + ...options, + pathSegments: 32 + }); + try { + const positions = mesh.getPositions()!; + const indices = mesh.getIndices()!; + expect(indices).toHaveLength(32 * profile.length * 6); + expect(points.map((point) => point.toJSON())).toEqual(originalPoints); + expect(mesh.vertexBufferBindings[0]!.buffer.data).toEqual(repeated.vertexBufferBindings[0]!.buffer.data); + + const keys = positions.map((point) => + [point.x, point.y, point.z].map((value) => Math.round(value * 1e5)).join(",") + ); + const edges = new Map(); + for (let i = 0; i < indices.length; i += 3) { + for (let j = 0; j < 3; j++) { + const edge = [keys[indices[i + j]], keys[indices[i + ((j + 1) % 3)]]].sort().join("|"); + edges.set(edge, (edges.get(edge) ?? 0) + 1); + } + } + expect(new Set(edges.values())).toEqual(new Set([2])); + + const buffer = mesh.vertexBufferBindings[0]!.buffer; + const original = buffer.data!.slice(); + const originalIndices = Array.from(indices); + points[0].set(100, 200, 300); + options.closedPath = false; + MeshTestUtils.clearBuffer(buffer); + (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); + expect(MeshTestUtils.readBuffer(buffer)).toEqual(original); + expect(Array.from(mesh.getIndices()!)).toEqual(originalIndices); + } finally { + mesh.destroy(); + repeated.destroy(); + } + }); + + it("uses one wall material slot per closed extrusion shape including its holes", () => { + const shapes = [ + { + points: polygon.points.map((point) => point.clone().scale(0.1)), + holes: polygon.holes.map((hole) => hole.map((point) => point.clone().scale(0.1))) + }, + { points: polygon.points.map(({ x, y }) => new Vector2(x * 0.1 + 0.6, y * 0.1)) } + ]; + const points = [new Vector3(-4, 0, -4), new Vector3(4, 0, -4), new Vector3(4, 0, 4), new Vector3(-4, 0, 4)]; + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, shapes, points, { + keepMeshData: true, + separateMaterialSlots: true, + closedPath: true, + pathSegments: 16 + }); + try { + const counts = [16 * 8 * 6, 16 * 4 * 6]; + expect(mesh.subMeshes.map(({ start, count }) => ({ start, count }))).toEqual([ + { start: 0, count: counts[0] }, + { start: counts[0], count: counts[1] } + ]); + expect(mesh.getIndices()!).toHaveLength(counts[0] + counts[1]); + } finally { + mesh.destroy(); + } + }); + + it("ignores settings from the inactive extrusion mode", () => { + const linearOptions = { keepMeshData: true, depthSegments: 2, bevelWidth: 0.1, separateMaterialSlots: true }; + const pathOptions = { keepMeshData: true, pathSegments: 5, separateMaterialSlots: true }; + const mixedLinearOptions = { ...linearOptions, pathSegments: 7, closedPath: true }; + const mixedPathOptions = { + ...pathOptions, + depthSegments: 7, + bevelWidth: 0.25, + bevelDepth: 0.4, + contourOffset: 0.5, + bevelSegments: 8 + }; + const pairs = [ + [ + PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, linearOptions), + PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, mixedLinearOptions) + ], + [ + PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, pathOptions), + PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, mixedPathOptions) + ] + ]; + try { + for (const [expected, actual] of pairs) { + expect(actual.getIndices()).toEqual(expected.getIndices()); + expect(actual.subMeshes).toEqual(expected.subMeshes); + for (let i = 0; i < expected.vertexBufferBindings.length; i++) { + expect(MeshTestUtils.readBuffer(actual.vertexBufferBindings[i]!.buffer)).toEqual( + MeshTestUtils.readBuffer(expected.vertexBufferBindings[i]!.buffer) + ); + } + } + } finally { + for (const pair of pairs) { + for (const mesh of pair) { + mesh.destroy(); + } + } + } + }); + + it("uses at least three path segments to close an extrusion path", () => { + const profile = [new Vector2(0.2, 0), new Vector2(-0.1, 0.1), new Vector2(-0.1, -0.1)]; + const points = [new Vector3(-4, 0, -4), new Vector3(4, 0, -4), new Vector3(4, 0, 4), new Vector3(-4, 0, 4)]; + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, profile, points, { keepMeshData: true, closedPath: true }); + try { + const positions = mesh.getPositions()!; + const indices = mesh.getIndices()!; + expect(indices).toHaveLength(3 * profile.length * 6); + const ab = new Vector3(); + const ac = new Vector3(); + const normal = new Vector3(); + for (let i = 0; i < indices.length; i += 3) { + Vector3.subtract(positions[indices[i + 1]], positions[indices[i]], ab); + Vector3.subtract(positions[indices[i + 2]], positions[indices[i]], ac); + Vector3.cross(ab, ac, normal); + expect(normal.length()).toBeGreaterThan(1e-6); + } + } finally { + mesh.destroy(); + } + }); + + it("samples tube paths at equal distances along their line segments", () => { + const radialSegments = 8; + const mesh = PrimitiveMesh.createTube(engine, [new Vector3(), new Vector3(1, 0, 0), new Vector3(1, 3, 0)], 0.5, { + keepMeshData: true, + pathSegments: 4, + radialSegments + }); + try { + const positions = mesh.getPositions()!; + const centers = [ + new Vector3(), + new Vector3(1, 0, 0), + new Vector3(1, 1, 0), + new Vector3(1, 2, 0), + new Vector3(1, 3, 0) + ]; + for (let i = 0; i < centers.length; i++) { + const center = new Vector3(); + for (let j = 0; j < radialSegments; j++) { + center.add(positions[i * (radialSegments + 1) + j]); + } + center.scale(1 / radialSegments); + expect(Vector3.distance(center, centers[i])).toBeLessThan(1e-6); + } + } finally { + mesh.destroy(); + } + }); + + it.each(["createTetrahedron", "createOctahedron", "createIcosahedron", "createDodecahedron"] as const)( + "keeps %s UVs within the shortest longitudinal interval", + (create) => { + for (const segments of [1, 2, 3]) { + const mesh = PrimitiveMesh[create](engine, 1, { edgeSegments: segments, keepMeshData: true }); + try { + const uvs = mesh.getUVs()!; + const indices = mesh.getIndices()!; + for (let i = 0; i < indices.length; i += 3) { + const values = [uvs[indices[i]].x, uvs[indices[i + 1]].x, uvs[indices[i + 2]].x]; + expect(Math.max(...values) - Math.min(...values)).toBeLessThanOrEqual(0.500001); + } + } finally { + mesh.destroy(); + } + } + } + ); + + it("ignores replaced vertex buffers while preserving pending position edits", () => { + const mesh = new ModelMesh(engine); + const previous = new Buffer( + engine, + BufferBindFlag.VertexBuffer, + new Float32Array([0, 0, 0]), + BufferUsage.Static, + true + ); + const current = new Buffer( + engine, + BufferBindFlag.VertexBuffer, + new Float32Array([1, 0, 0]), + BufferUsage.Static, + true + ); + try { + mesh.setVertexElements([new VertexElement(VertexAttribute.Position, 0, VertexElementFormat.Vector3, 0)]); + mesh.setVertexBufferBinding(previous, 12, 0); + mesh.setVertexBufferBinding(current, 12, 0); + expect((previous._dataUpdateManager as any)._listeners).toHaveLength(0); + expect((current._dataUpdateManager as any)._listeners).toHaveLength(1); + mesh.setPositions([new Vector3(2, 0, 0)]); + previous.setData(new Float32Array([3, 0, 0])); + expect(mesh.getPositions()![0].x).toBe(2); + mesh.uploadData(false); + expect(new Float32Array(MeshTestUtils.readBuffer(current).buffer)[0]).toBe(2); + } finally { + mesh.destroy(); + previous.destroy(); + current.destroy(); + } + }); + + it.each([false, true])( + "restores generated primitive buffers and groups with keepMeshData: %s", + async (keepMeshData) => { + const restoredEngine = await WebGLEngine.create({ canvas: document.createElement("canvas") }); + const released = PrimitiveMesh.createSphere(restoredEngine, 1, { subdivisionLevel: 1 }); + const mesh = PrimitiveMesh.createCuboid(restoredEngine, 1, 2, 3, { + keepMeshData, + separateMaterialSlots: true, + widthSegments: 1, + heightSegments: 1, + depthSegments: 1 + }); + try { + const bindings = mesh.vertexBufferBindings.map((binding) => binding!.buffer); + bindings.push(mesh._primitive.indexBufferBinding!._buffer); + const buffers = bindings.map((buffer) => MeshTestUtils.readBuffer(buffer)); + const releasedBindings = released.vertexBufferBindings.map((binding) => binding!.buffer); + releasedBindings.push(released._primitive.indexBufferBinding!._buffer); + const releasedBuffers = releasedBindings.map((buffer) => MeshTestUtils.readBuffer(buffer)); + const groups = mesh.subMeshes.slice(); + const min = mesh.bounds.min.toJSON(); + const max = mesh.bounds.max.toJSON(); + + const lost = new Promise((resolve) => restoredEngine.once(EngineEventType.DeviceLost, () => resolve())); + restoredEngine.forceLoseDevice(); + await lost; + await new Promise((resolve) => setTimeout(resolve, 0)); + const restored = new Promise((resolve) => + restoredEngine.once(EngineEventType.DeviceRestored, () => resolve()) + ); + restoredEngine.forceRestoreDevice(); + await restored; + + expect(mesh.subMeshes).toHaveLength(6); + expect(mesh.subMeshes.every((subMesh, index) => subMesh === groups[index])).toBe(true); + expect(mesh.bounds.min.toJSON()).toEqual(min); + expect(mesh.bounds.max.toJSON()).toEqual(max); + bindings.forEach((buffer, index) => { + expect(MeshTestUtils.readBuffer(buffer)).toEqual(buffers[index]); + }); + releasedBindings.forEach((buffer, index) => { + expect(MeshTestUtils.readBuffer(buffer)).toEqual(releasedBuffers[index]); + }); + expect(mesh.vertexBufferBindings.every((binding) => binding!.buffer.readable === keepMeshData)).toBe(true); + } finally { + restoredEngine.destroy(); + } + } + ); + + it.each([1, 1e-8])("normalizes tangents for a plane of size %s", (size) => { + const mesh = PrimitiveMesh.createPlane(engine, size, size, { + keepMeshData: true, + widthSegments: 1, + depthSegments: 1 + }); + try { + for (const tangent of mesh.getTangents()!) { + expect(Math.hypot(tangent.x, tangent.y, tangent.z)).toBeCloseTo(1, 6); + expect(tangent.x).toBeCloseTo(1, 6); + expect(tangent.y).toBeCloseTo(0, 6); + expect(tangent.z).toBeCloseTo(0, 6); + } + } finally { + mesh.destroy(); + } + }); + + it("keeps tangent calculations finite for collapsed UV triangles", () => { + const mesh = new ModelMesh(engine); + try { + mesh.setPositions([new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(0, 1, 0)]); + mesh.setNormals([new Vector3(0, 0, 2), new Vector3(0, 0, 2), new Vector3(0, 0, 2)]); + mesh.setUVs([new Vector2(), new Vector2(), new Vector2()]); + mesh.setIndices(new Uint16Array([0, 1, 2])); + mesh.calculateTangents(); + expect(mesh.getTangents()!.every((t) => [t.x, t.y, t.z, t.w].every(Number.isFinite))).toBe(true); + } finally { + mesh.destroy(); + } + }); + + it.each([false, true])("preserves tangent data when adding a vertex channel after reading: %s", (readTangents) => { + const mesh = PrimitiveMesh.createSphere(engine, 0.5, { keepMeshData: true, subdivisionLevel: 2 }); + try { + const original = MeshTestUtils.readBuffer(mesh.vertexBufferBindings[1]!.buffer); + if (readTangents) { + mesh.getTangents(); + } + mesh.setUVs( + mesh.getUVs()!.map((uv) => uv.clone()), + 1 + ); + mesh.uploadData(false); + const element = mesh.getVertexElement(VertexAttribute.Tangent)!; + const binding = mesh.vertexBufferBindings[element.bindingIndex]!; + const buffer = MeshTestUtils.readBuffer(binding.buffer); + const tangents = new Uint8Array(mesh.vertexCount * 16); + for (let i = 0; i < mesh.vertexCount; i++) { + const offset = i * binding.stride + element.offset; + tangents.set(buffer.subarray(offset, offset + 16), i * 16); + } + expect(tangents).toEqual(original); + expect(mesh.vertexBufferBindings).toHaveLength(2); + } finally { + mesh.destroy(); + } + }); + + it("uses standard tangent access and mutation for primitives", () => { + const mesh = PrimitiveMesh.createPlane(engine, 1, 1, { keepMeshData: true }); + try { + expect(mesh.getTangents()!.every((tangent) => tangent instanceof Vector4)).toBe(true); + const tangents = Array.from({ length: mesh.vertexCount }, (_, i) => new Vector4(0, 0, 1, i % 2 ? 1 : -1)); + mesh.setTangents(tangents); + mesh.uploadData(false); + expect(mesh.getTangents()).toBe(tangents); + const element = mesh.getVertexElement(VertexAttribute.Tangent)!; + const binding = mesh.vertexBufferBindings[element.bindingIndex]!; + const data = new Float32Array(MeshTestUtils.readBuffer(binding.buffer).buffer); + expect(data).toEqual(new Float32Array(tangents.flatMap(({ x, y, z, w }) => [x, y, z, w]))); + } finally { + mesh.destroy(); + } + }); + + it("releases temporary vertex data after default primitive creation", () => { + const mesh = PrimitiveMesh.createPlane(engine, 1, 1); + try { + expect(mesh.vertexBufferBindings.every((binding) => !binding!.buffer.readable)).toBe(true); + expect(() => mesh.getPositions()).toThrow(); + expect(() => mesh.getTangents()).toThrow(); + } finally { + mesh.destroy(); + } + }); + + it("releases primitive tangent data through the ModelMesh buffer lifecycle", () => { + const mesh = PrimitiveMesh.createPlane(engine, 1, 1, { keepMeshData: true }); + try { + const tangentBuffer = mesh.vertexBufferBindings[1]!.buffer; + expect(tangentBuffer.readable).toBe(true); + mesh.uploadData(true); + expect(tangentBuffer.readable).toBe(false); + expect(() => mesh.getTangents()).toThrow(); + } finally { + mesh.destroy(); + } + }); + + it("calculates tangents for non-indexed triangles with non-unit normals", () => { + const mesh = new ModelMesh(engine); + try { + mesh.setPositions([new Vector3(), new Vector3(1, 0, 0), new Vector3(0, 1, 0)]); + mesh.setNormals([new Vector3(0, 0, 2), new Vector3(0, 0, 2), new Vector3(0, 0, 2)]); + mesh.setUVs([new Vector2(), new Vector2(1, 0), new Vector2(0, 1)]); + mesh.calculateTangents(); + expect(mesh.getTangents()!.map((tangent) => tangent.toJSON())).toEqual([ + { x: 1, y: 0, z: 0, w: 1 }, + { x: 1, y: 0, z: 0, w: 1 }, + { x: 1, y: 0, z: 0, w: 1 } + ]); + } finally { + mesh.destroy(); + } + }); + + it.each([false, true])("ignores an incomplete final tangent triangle with indices: %s", (indexed) => { + const mesh = new ModelMesh(engine); + try { + mesh.setPositions([new Vector3(), new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(1, 1, 0)]); + mesh.setNormals(Array.from({ length: 4 }, () => new Vector3(0, 0, 1))); + mesh.setUVs([new Vector2(), new Vector2(1, 0), new Vector2(0, 1), new Vector2(1, 1)]); + if (indexed) { + mesh.setIndices(new Uint16Array([0, 1, 2, 3])); + } + mesh.calculateTangents(); + expect(mesh.getTangents()!.map((tangent) => tangent.toJSON())).toEqual([ + { x: 1, y: 0, z: 0, w: 1 }, + { x: 1, y: 0, z: 0, w: 1 }, + { x: 1, y: 0, z: 0, w: 1 }, + { x: 0, y: 0, z: 0, w: -1 } + ]); + } finally { + mesh.destroy(); + } + }); + + it("triangulates contours above the function argument limit", () => { + const count = 150000; + const points = Array.from({ length: count }, (_, i) => { + const angle = (i * Math.PI * 2) / count; + return new Vector2(Math.cos(angle), Math.sin(angle)); + }); + const mesh = PrimitiveMesh.createPolygon(engine, points, { keepMeshData: true }); + try { + expect(mesh.vertexCount).toBe(count); + expect(mesh.getIndices()).toBeInstanceOf(Uint32Array); + expect(mesh.getIndices()!.length).toBe((count - 2) * 3); + } finally { + mesh.destroy(); + } + }); + + it("promotes growing extrusion indices beyond the 16-bit vertex range", () => { + const contour = Array.from({ length: 256 }, (_, i) => { + const angle = (i * Math.PI * 2) / 256; + return new Vector2(Math.cos(angle), Math.sin(angle)); + }); + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, contour, 1, { keepMeshData: true, depthSegments: 43 }); + try { + const indices = mesh.getIndices()!; + expect(mesh.vertexCount).toBeGreaterThan(65535); + expect(indices).toBeInstanceOf(Uint32Array); + expect(indices[indices.length - 1]).toBe(mesh.vertexCount - 1); + } finally { + mesh.destroy(); + } + }); + + it("handles repeated contour endpoints when beveling", () => { + const mesh = PrimitiveMesh.createExtrudedPolygon( + engine, + { + points: [ + new Vector2(0, 0), + new Vector2(2, 0), + new Vector2(2, 0), + new Vector2(2, 2), + new Vector2(0, 2), + new Vector2(0, 0) + ] + }, + 1, + { keepMeshData: true, bevelWidth: 0.1, depthSegments: 1 } + ); + try { + expect(mesh.getPositions()!.every((p) => [p.x, p.y, p.z].every(Number.isFinite))).toBe(true); + } finally { + mesh.destroy(); + } + }); +}); + +class MeshTestUtils { + static clearBuffer(buffer: Buffer): void { + buffer._platformBuffer.setData( + buffer.byteLength, + new Uint8Array(buffer.byteLength), + 0, + 0, + undefined, + SetDataOptions.None + ); + } + + static readBuffer(buffer: Buffer): Uint8Array { + const data = new Uint8Array(buffer.byteLength); + buffer.getData(data); + return data; + } +} diff --git a/tests/src/core/particle/ParticleRenderer.test.ts b/tests/src/core/particle/ParticleRenderer.test.ts index 640eb82036..703a408d31 100644 --- a/tests/src/core/particle/ParticleRenderer.test.ts +++ b/tests/src/core/particle/ParticleRenderer.test.ts @@ -320,7 +320,7 @@ describe("ParticleRenderer", () => { it("releases mesh geometry bindings when the mesh is removed", () => { const entity = scene.createRootEntity("MeshBindingCleanup"); const renderer = entity.addComponent(ParticleRenderer); - const mesh = PrimitiveMesh.createCuboid(engine); + const mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); renderer.renderMode = ParticleRenderMode.Mesh; renderer.mesh = mesh; expect(renderer.generator._primitive.vertexBufferBindings.length).to.be.greaterThan(0); @@ -367,7 +367,7 @@ describe("ParticleRenderer", () => { it("clone with mesh render mode", () => { const entity = scene.createRootEntity("CloneSource"); const renderer = entity.addComponent(ParticleRenderer); - const mesh = PrimitiveMesh.createCuboid(engine); + const mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); renderer.renderMode = ParticleRenderMode.Mesh; renderer.mesh = mesh; expect(mesh.refCount).to.eq(1); @@ -393,7 +393,7 @@ describe("ParticleRenderer", () => { // Mesh mode + noise triggers buffer reorganization mid-clone, before mesh is applied const entity = scene.createRootEntity("CloneMacroSource"); const renderer = entity.addComponent(ParticleRenderer); - const mesh = PrimitiveMesh.createCuboid(engine); + const mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); renderer.renderMode = ParticleRenderMode.Mesh; renderer.mesh = mesh; renderer.generator.noise.enabled = true; @@ -444,7 +444,7 @@ describe("ParticleRenderer", () => { generator._resizeInstanceBuffer(256); expect(generator._primitive.vertexBufferBindings).to.have.length(0); - const mesh = PrimitiveMesh.createCuboid(engine); + const mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); renderer.mesh = mesh; expect(generator._primitive.vertexBufferBindings).to.include(generator._instanceVertexBufferBinding); diff --git a/tests/src/core/particle/SizeOverLifetime.test.ts b/tests/src/core/particle/SizeOverLifetime.test.ts index e0e204f2e7..dd36c8ef0e 100644 --- a/tests/src/core/particle/SizeOverLifetime.test.ts +++ b/tests/src/core/particle/SizeOverLifetime.test.ts @@ -193,7 +193,7 @@ describe("SizeOverLifetime", () => { it("mesh render mode with separateAxes TwoCurves enables macros, uploads all axis curves and writes the random slot", () => { const renderer = createParticleRenderer(engine, "SOL_MeshSeparate"); renderer.renderMode = ParticleRenderMode.Mesh; - renderer.mesh = PrimitiveMesh.createCuboid(engine); + renderer.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); const generator = renderer.generator; const sol = generator.sizeOverLifetime; diff --git a/tests/src/core/particle/SubEmitter.test.ts b/tests/src/core/particle/SubEmitter.test.ts index 0c8487b29d..30a3aa2997 100644 --- a/tests/src/core/particle/SubEmitter.test.ts +++ b/tests/src/core/particle/SubEmitter.test.ts @@ -3307,7 +3307,7 @@ describe("SubEmitter rendering regressions", () => { const generator = child.generator; generator.main.startSize.constant = 0.8; child.renderMode = ParticleRenderMode.Mesh; - const mesh = PrimitiveMesh.createCuboid(engine); + const mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); child.mesh = mesh; if (vertexColor) { mesh.setColors(Array.from({ length: mesh.vertexCount }, () => new Color(1, 1, 1, 1))); diff --git a/tests/src/core/particle/SubEmitterRendering.test.ts b/tests/src/core/particle/SubEmitterRendering.test.ts index d0d6aa3d73..3a75960f01 100644 --- a/tests/src/core/particle/SubEmitterRendering.test.ts +++ b/tests/src/core/particle/SubEmitterRendering.test.ts @@ -97,7 +97,7 @@ describe("Sub-emitter rendering", () => { const child = createRenderer("Child"); (parent.getMaterial() as ParticleMaterial).baseColor.set(0, 0, 0, 1); child.renderMode = ParticleRenderMode.Mesh; - child.mesh = PrimitiveMesh.createCuboid(engine); + child.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); child.generator.main.startSize.constant = 0.8; const texture = new Texture2D(engine, 1, 1, undefined, false); texture.setPixelBuffer(new Uint8Array([255, 255, 255, 255])); diff --git a/tests/src/core/physics/ColliderLayer.test.ts b/tests/src/core/physics/ColliderLayer.test.ts index 1df326a0e5..e9dd2e1b2b 100644 --- a/tests/src/core/physics/ColliderLayer.test.ts +++ b/tests/src/core/physics/ColliderLayer.test.ts @@ -101,7 +101,12 @@ describe("Collider layer initialization", () => { source.addShape(shape); expect(attach.mock.calls.length).toBe(1); - const mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1, false); + const mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { + keepMeshData: true, + widthSegments: 1, + heightSegments: 1, + depthSegments: 1 + }); shape.mesh = mesh; const center = new Vector3(3, 1000.5, 0); expect(physics.overlapSphereAll(center, 0.1, Layer.Everything)).toEqual([]); diff --git a/tests/src/core/physics/MeshColliderLayer.test.ts b/tests/src/core/physics/MeshColliderLayer.test.ts index 153be012d1..2196fce054 100644 --- a/tests/src/core/physics/MeshColliderLayer.test.ts +++ b/tests/src/core/physics/MeshColliderLayer.test.ts @@ -25,7 +25,12 @@ describe("Mesh collider collision layers", () => { beforeAll(async () => { engine = await WebGLEngine.create({ canvas: document.createElement("canvas"), physics: createPhysics() }); physics = engine.sceneManager.activeScene.physics; - mesh = PrimitiveMesh.createCuboid(engine, 10, 1, 10, false); + mesh = PrimitiveMesh.createCuboid(engine, 10, 1, 10, { + keepMeshData: true, + widthSegments: 1, + heightSegments: 1, + depthSegments: 1 + }); }); afterAll(() => engine.destroy()); diff --git a/tests/src/loader/PrimitiveMeshLoader.test.ts b/tests/src/loader/PrimitiveMeshLoader.test.ts new file mode 100644 index 0000000000..8a6a254f79 --- /dev/null +++ b/tests/src/loader/PrimitiveMeshLoader.test.ts @@ -0,0 +1,720 @@ +import { + AssetPromise, + AssetType, + ModelMesh, + PrimitiveMesh, + PrimitiveMeshAsset, + PrimitiveMeshCapMode, + Vector2, + Vector3, + WebGLEngine +} from "@galacean/engine"; +import "@galacean/engine-loader"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; + +let engine: WebGLEngine; +beforeAll(async () => { + engine = await WebGLEngine.create({ canvas: document.createElement("canvas") }); +}); +afterAll(() => engine.destroy()); + +const profile = [ + { x: 0.25, y: -1 }, + { x: 1, y: 0 }, + { x: 0.5, y: 1 } +]; +const profileVectors = profile.map(({ x, y }) => new Vector2(x, y)); +const path = [ + { x: 0, y: 0, z: 0 }, + { x: 0, y: 0, z: 2 }, + { x: 1, y: 1, z: 3 } +]; +const pathVectors = path.map(({ x, y, z }) => new Vector3(x, y, z)); +const shapes = [ + { + points: [ + { x: -2, y: -2 }, + { x: 2, y: -2 }, + { x: 2, y: 2 }, + { x: -2, y: 2 } + ], + holes: [ + [ + { x: -1, y: -1 }, + { x: -1, y: 1 }, + { x: 1, y: 1 }, + { x: 1, y: -1 } + ] + ] + }, + { + points: [ + { x: 3, y: 0 }, + { x: 4, y: 0 }, + { x: 3, y: 1 } + ] + } +]; +const shapeVectors = shapes.map(({ points, holes }) => ({ + points: points.map(({ x, y }) => new Vector2(x, y)), + holes: holes?.map((hole) => hole.map(({ x, y }) => new Vector2(x, y))) +})); +const options = { keepMeshData: true }; +const groupedOptions = { keepMeshData: true, separateMaterialSlots: true }; +const mixedLinearOptions = { ...groupedOptions, depthSegments: 2, closedPath: true }; +const mixedPathOptions = { + ...groupedOptions, + pathSegments: 6, + bevelWidth: 0.25, + bevelDepth: 0.4, + contourOffset: 0.5, + bevelSegments: 8 +}; + +describe("PrimitiveMeshLoader", () => { + const defaults = { + sphere: { data: { type: "sphere", sphereRadius: 0.5 }, create: () => PrimitiveMesh.createSphere(engine, 0.5) }, + cuboid: { + data: { type: "cuboid", cuboidWidth: 1, cuboidHeight: 1, cuboidDepth: 1 }, + create: () => PrimitiveMesh.createCuboid(engine, 1, 1, 1) + }, + plane: { + data: { type: "plane", planeWidth: 1, planeDepth: 1 }, + create: () => PrimitiveMesh.createPlane(engine, 1, 1) + }, + cylinder: { + data: { type: "cylinder", cylinderRadius: 0.5, cylinderHeight: 2 }, + create: () => PrimitiveMesh.createCylinder(engine, 0.5, 2) + }, + truncatedCone: { + data: { + type: "truncatedCone", + truncatedConeTopRadius: 0.25, + truncatedConeBottomRadius: 0.5, + truncatedConeHeight: 2 + }, + create: () => PrimitiveMesh.createTruncatedCone(engine, 0.25, 0.5, 2) + }, + cone: { + data: { type: "cone", coneRadius: 0.5, coneHeight: 2 }, + create: () => PrimitiveMesh.createCone(engine, 0.5, 2) + }, + capsule: { + data: { type: "capsule", capsuleRadius: 0.5, capsuleCylinderHeight: 2 }, + create: () => PrimitiveMesh.createCapsule(engine, 0.5, 2) + }, + torus: { + data: { type: "torus", torusRadius: 0.5, torusTubeRadius: 0.1 }, + create: () => PrimitiveMesh.createTorus(engine, 0.5, 0.1) + }, + circle: { data: { type: "circle", circleRadius: 0.5 }, create: () => PrimitiveMesh.createCircle(engine, 0.5) }, + ring: { + data: { type: "ring", ringOuterRadius: 0.5, ringInnerRadius: 0.25 }, + create: () => PrimitiveMesh.createRing(engine, 0.5, 0.25) + }, + tetrahedron: { + data: { type: "tetrahedron", tetrahedronRadius: 0.5 }, + create: () => PrimitiveMesh.createTetrahedron(engine, 0.5) + }, + octahedron: { + data: { type: "octahedron", octahedronRadius: 0.5 }, + create: () => PrimitiveMesh.createOctahedron(engine, 0.5) + }, + icosahedron: { + data: { type: "icosahedron", icosahedronRadius: 0.5 }, + create: () => PrimitiveMesh.createIcosahedron(engine, 0.5) + }, + dodecahedron: { + data: { type: "dodecahedron", dodecahedronRadius: 0.5 }, + create: () => PrimitiveMesh.createDodecahedron(engine, 0.5) + }, + revolvedSurface: { + data: { type: "revolvedSurface", revolvedSurfaceProfile: profile }, + create: () => PrimitiveMesh.createRevolvedSurface(engine, profileVectors) + }, + tube: { + data: { type: "tube", tubeRadius: 0.5, tubePath: path }, + create: () => PrimitiveMesh.createTube(engine, pathVectors, 0.5) + }, + polygon: { + data: { type: "polygon", polygonShapes: shapes }, + create: () => PrimitiveMesh.createPolygon(engine, shapeVectors) + }, + extrudedPolygon: { + data: { type: "extrudedPolygon", extrudedPolygonDepth: 1, extrudedPolygonShapes: shapes }, + create: () => PrimitiveMesh.createExtrudedPolygon(engine, shapeVectors, 1) + }, + torusKnot: { + data: { + type: "torusKnot", + torusKnotRadius: 0.5, + torusKnotTubeRadius: 0.1, + torusKnotAxisTurns: 2, + torusKnotCrossSectionTurns: 3 + }, + create: () => PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2, 3) + }, + roundedCuboid: { + data: { + type: "roundedCuboid", + roundedCuboidWidth: 1, + roundedCuboidHeight: 1, + roundedCuboidDepth: 1, + roundedCuboidCornerRadius: 0.1 + }, + create: () => PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.1) + } + } satisfies Record ModelMesh }>; + + const configured: { name: string; data: PrimitiveMeshAsset; create: () => ModelMesh }[] = [ + { + name: "sphere ranges and subdivision level", + data: { + type: "sphere", + sphereRadius: 2, + sphereOptions: { + ...options, + horizontalAngleRange: { x: 20, y: 260 }, + verticalAngleRange: { x: 30, y: 150 }, + subdivisionLevel: 3 + } + }, + create: () => + PrimitiveMesh.createSphere(engine, 2, { + ...options, + horizontalAngleRange: new Vector2(20, 260), + verticalAngleRange: new Vector2(30, 150), + subdivisionLevel: 3 + }) + }, + { + name: "sphere", + data: { type: "sphere", sphereRadius: 1.5, sphereOptions: { ...options, subdivisionLevel: 2 } }, + create: () => PrimitiveMesh.createSphere(engine, 1.5, { ...options, subdivisionLevel: 2 }) + }, + { + name: "sphere angular ranges", + data: { + type: "sphere", + sphereRadius: 2, + sphereOptions: { + ...options, + horizontalAngleRange: { x: 350, y: 370 }, + verticalAngleRange: { x: 30, y: 150 }, + subdivisionLevel: 3 + } + }, + create: () => + PrimitiveMesh.createSphere(engine, 2, { + ...options, + horizontalAngleRange: new Vector2(350, 370), + verticalAngleRange: new Vector2(30, 150), + subdivisionLevel: 3 + }) + }, + { + name: "cuboid dimensions and segment counts", + data: { + type: "cuboid", + cuboidWidth: 2, + cuboidHeight: 3, + cuboidDepth: 4, + cuboidOptions: { ...groupedOptions, widthSegments: 2, heightSegments: 3, depthSegments: 4 } + }, + create: () => + PrimitiveMesh.createCuboid(engine, 2, 3, 4, { + ...groupedOptions, + widthSegments: 2, + heightSegments: 3, + depthSegments: 4 + }) + }, + { + name: "plane dimensions and segment counts", + data: { + type: "plane", + planeWidth: 3, + planeDepth: 5, + planeOptions: { ...options, widthSegments: 2, depthSegments: 4 } + }, + create: () => PrimitiveMesh.createPlane(engine, 3, 5, { ...options, widthSegments: 2, depthSegments: 4 }) + }, + { + name: "cylinder caps and range", + data: { + type: "cylinder", + cylinderRadius: 0.75, + cylinderHeight: 3, + cylinderOptions: { + ...groupedOptions, + caps: PrimitiveMeshCapMode.Bottom, + angleRange: { x: 20, y: 270 }, + radialSegments: 12, + heightSegments: 2 + } + }, + create: () => + PrimitiveMesh.createCylinder(engine, 0.75, 3, { + ...groupedOptions, + caps: PrimitiveMeshCapMode.Bottom, + angleRange: new Vector2(20, 270), + radialSegments: 12, + heightSegments: 2 + }) + }, + { + name: "truncated cone end radii", + data: { + type: "truncatedCone", + truncatedConeTopRadius: 0.25, + truncatedConeBottomRadius: 1, + truncatedConeHeight: 3, + truncatedConeOptions: { + ...groupedOptions, + caps: PrimitiveMeshCapMode.Top, + angleRange: { x: 30, y: 250 }, + radialSegments: 12, + heightSegments: 2 + } + }, + create: () => + PrimitiveMesh.createTruncatedCone(engine, 0.25, 1, 3, { + ...groupedOptions, + caps: PrimitiveMeshCapMode.Top, + angleRange: new Vector2(30, 250), + radialSegments: 12, + heightSegments: 2 + }) + }, + { + name: "cone cap and range", + data: { + type: "cone", + coneRadius: 0.75, + coneHeight: 3, + coneOptions: { + ...groupedOptions, + cap: false, + angleRange: { x: 20, y: 270 }, + radialSegments: 12, + heightSegments: 2 + } + }, + create: () => + PrimitiveMesh.createCone(engine, 0.75, 3, { + ...groupedOptions, + cap: false, + angleRange: new Vector2(20, 270), + radialSegments: 12, + heightSegments: 2 + }) + }, + { + name: "capsule independent segment counts", + data: { + type: "capsule", + capsuleRadius: 0.75, + capsuleCylinderHeight: 3, + capsuleOptions: { ...options, radialSegments: 12, capSegments: 5, heightSegments: 2 } + }, + create: () => + PrimitiveMesh.createCapsule(engine, 0.75, 3, { + ...options, + radialSegments: 12, + capSegments: 5, + heightSegments: 2 + }) + }, + { + name: "torus major and tube ranges", + data: { + type: "torus", + torusRadius: 2, + torusTubeRadius: 0.25, + torusOptions: { + ...options, + tubeAngleRange: { x: 45, y: 300 }, + ringAngleRange: { x: 20, y: 200 }, + ringSegments: 12, + radialSegments: 8 + } + }, + create: () => + PrimitiveMesh.createTorus(engine, 2, 0.25, { + ...options, + tubeAngleRange: new Vector2(45, 300), + ringAngleRange: new Vector2(20, 200), + ringSegments: 12, + radialSegments: 8 + }) + }, + { + name: "circle sector", + data: { + type: "circle", + circleRadius: 2, + circleOptions: { ...options, angleRange: { x: 30, y: 240 }, segments: 12 } + }, + create: () => + PrimitiveMesh.createCircle(engine, 2, { ...options, angleRange: new Vector2(30, 240), segments: 12 }) + }, + { + name: "ring sector", + data: { + type: "ring", + ringOuterRadius: 2, + ringInnerRadius: 0.5, + ringOptions: { ...options, angleRange: { x: 40, y: 240 }, ringSegments: 12, widthSegments: 3 } + }, + create: () => + PrimitiveMesh.createRing(engine, 2, 0.5, { + ...options, + angleRange: new Vector2(40, 240), + ringSegments: 12, + widthSegments: 3 + }) + }, + { + name: "ring radius defaults", + data: { type: "ring", ringOuterRadius: 2, ringInnerRadius: 1, ringOptions: { ...options } }, + create: () => PrimitiveMesh.createRing(engine, 2, 1, { ...options }) + }, + { + name: "tetrahedron subdivision", + data: { type: "tetrahedron", tetrahedronRadius: 2, tetrahedronOptions: { ...options, edgeSegments: 3 } }, + create: () => PrimitiveMesh.createTetrahedron(engine, 2, { ...options, edgeSegments: 3 }) + }, + { + name: "octahedron subdivision", + data: { type: "octahedron", octahedronRadius: 1.5, octahedronOptions: { ...options, edgeSegments: 2 } }, + create: () => PrimitiveMesh.createOctahedron(engine, 1.5, { ...options, edgeSegments: 2 }) + }, + { + name: "icosahedron subdivision", + data: { type: "icosahedron", icosahedronRadius: 2, icosahedronOptions: { ...options, edgeSegments: 3 } }, + create: () => PrimitiveMesh.createIcosahedron(engine, 2, { ...options, edgeSegments: 3 }) + }, + { + name: "dodecahedron subdivision", + data: { type: "dodecahedron", dodecahedronRadius: 1.5, dodecahedronOptions: { ...options, edgeSegments: 2 } }, + create: () => PrimitiveMesh.createDodecahedron(engine, 1.5, { ...options, edgeSegments: 2 }) + }, + { + name: "revolved surface profile and range", + data: { + type: "revolvedSurface", + revolvedSurfaceProfile: profile, + revolvedSurfaceOptions: { ...options, angleRange: { x: 30, y: 270 }, segments: 16 } + }, + create: () => + PrimitiveMesh.createRevolvedSurface(engine, profileVectors, { + ...options, + angleRange: new Vector2(30, 270), + segments: 16 + }) + }, + { + name: "closed tube path", + data: { + type: "tube", + tubeRadius: 0.2, + tubePath: path, + tubeOptions: { ...options, closedPath: true, pathSegments: 16, radialSegments: 6 } + }, + create: () => + PrimitiveMesh.createTube(engine, pathVectors, 0.2, { + ...options, + closedPath: true, + pathSegments: 16, + radialSegments: 6 + }) + }, + { + name: "multiple polygons with holes", + data: { type: "polygon", polygonShapes: shapes, polygonOptions: groupedOptions }, + create: () => PrimitiveMesh.createPolygon(engine, shapeVectors, { ...groupedOptions }) + }, + { + name: "beveled extrusion", + data: { + type: "extrudedPolygon", + extrudedPolygonDepth: 2, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { + ...groupedOptions, + bevelWidth: 0.1, + bevelDepth: 0.2, + contourOffset: 0.2, + bevelSegments: 2, + depthSegments: 3 + } + }, + create: () => + PrimitiveMesh.createExtrudedPolygon(engine, shapeVectors, 2, { + ...groupedOptions, + bevelWidth: 0.1, + bevelDepth: 0.2, + contourOffset: 0.2, + bevelSegments: 2, + depthSegments: 3 + }) + }, + { + name: "inset extrusion without bevels", + data: { + type: "extrudedPolygon", + extrudedPolygonDepth: 2, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { ...options, contourOffset: -0.1 } + }, + create: () => + PrimitiveMesh.createExtrudedPolygon(engine, shapeVectors, 2, { + ...options, + contourOffset: -0.1, + depthSegments: 1 + }) + }, + { + name: "extrusion along a path", + data: { + type: "extrudedPolygon", + extrudedPolygonPath: path, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { ...groupedOptions, pathSegments: 6 } + }, + create: () => + PrimitiveMesh.createExtrudedPolygon(engine, shapeVectors, pathVectors, { ...groupedOptions, pathSegments: 6 }) + }, + { + name: "closed extrusion path", + data: { + type: "extrudedPolygon", + extrudedPolygonPath: path, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { ...groupedOptions, closedPath: true, pathSegments: 12 } + }, + create: () => + PrimitiveMesh.createExtrudedPolygon(engine, shapeVectors, pathVectors, { + ...groupedOptions, + closedPath: true, + pathSegments: 12 + }) + }, + { + name: "linear extrusion ignores path-only settings", + data: { + type: "extrudedPolygon", + extrudedPolygonDepth: 2, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: mixedLinearOptions + }, + create: () => + PrimitiveMesh.createExtrudedPolygon(engine, shapeVectors, 2, { ...groupedOptions, depthSegments: 2 }) + }, + { + name: "path extrusion ignores linear-only settings", + data: { + type: "extrudedPolygon", + extrudedPolygonPath: path, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: mixedPathOptions + }, + create: () => + PrimitiveMesh.createExtrudedPolygon(engine, shapeVectors, pathVectors, { ...groupedOptions, pathSegments: 6 }) + }, + { + name: "torus knot winding", + data: { + type: "torusKnot", + torusKnotRadius: 2, + torusKnotTubeRadius: 0.2, + torusKnotAxisTurns: 3, + torusKnotCrossSectionTurns: 4, + torusKnotOptions: { ...options, pathSegments: 48, radialSegments: 6 } + }, + create: () => + PrimitiveMesh.createTorusKnot(engine, 2, 0.2, 3, 4, { ...options, pathSegments: 48, radialSegments: 6 }) + }, + { + name: "negative torus knot windings", + data: { + type: "torusKnot", + torusKnotRadius: 2, + torusKnotTubeRadius: 0.2, + torusKnotAxisTurns: -2, + torusKnotCrossSectionTurns: -3, + torusKnotOptions: { ...options, pathSegments: 48, radialSegments: 8 } + }, + create: () => + PrimitiveMesh.createTorusKnot(engine, 2, 0.2, -2, -3, { ...options, pathSegments: 48, radialSegments: 8 }) + }, + { + name: "rounded cuboid", + data: { + type: "roundedCuboid", + roundedCuboidWidth: 2, + roundedCuboidHeight: 3, + roundedCuboidDepth: 4, + roundedCuboidCornerRadius: 0.2, + roundedCuboidOptions: { ...groupedOptions, roundingSegments: 3 } + }, + create: () => PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0.2, { ...groupedOptions, roundingSegments: 3 }) + }, + { + name: "cuboid inherited defaults", + data: { type: "cuboid", cuboidWidth: 2, cuboidHeight: 2, cuboidDepth: 2, cuboidOptions: { widthSegments: 3 } }, + create: () => PrimitiveMesh.createCuboid(engine, 2, 2, 2, { widthSegments: 3 }) + }, + { + name: "plane inherited defaults", + data: { type: "plane", planeWidth: 2, planeDepth: 2, planeOptions: { widthSegments: 4 } }, + create: () => PrimitiveMesh.createPlane(engine, 2, 2, { widthSegments: 4 }) + }, + { + name: "capsule inherited cap segments", + data: { type: "capsule", capsuleRadius: 0.5, capsuleCylinderHeight: 2, capsuleOptions: { radialSegments: 10 } }, + create: () => PrimitiveMesh.createCapsule(engine, 0.5, 2, { radialSegments: 10 }) + } + ]; + + const cases = [ + ...Object.entries(defaults).map(([name, value]) => ({ name: `default ${name}`, ...value })), + ...configured + ]; + + it.each(cases)("loads $name from JSON with the same result as the creation API", async ({ name, data, create }) => { + const serialized = JSON.stringify(data); + const parsed = JSON.parse(serialized); + const request = vi.spyOn(engine.resourceManager, "_request").mockReturnValue(AssetPromise.resolve(parsed) as any); + const expected = create(); + let mesh: ModelMesh | undefined; + try { + mesh = await engine.resourceManager.load({ url: `${name}.mesh`, type: AssetType.PrimitiveMesh }); + expect(mesh.vertexCount).toBe(expected.vertexCount); + const buffer = mesh.vertexBufferBindings[0]!.buffer; + const expectedBuffer = expected.vertexBufferBindings[0]!.buffer; + const vertices = new Uint8Array(buffer.byteLength); + const expectedVertices = new Uint8Array(expectedBuffer.byteLength); + buffer.getData(vertices); + expectedBuffer.getData(expectedVertices); + expect(vertices).toEqual(expectedVertices); + expect(buffer.readable).toBe(expectedBuffer.readable); + expect(mesh.bounds.min.toJSON()).toEqual(expected.bounds.min.toJSON()); + expect(mesh.bounds.max.toJSON()).toEqual(expected.bounds.max.toJSON()); + expect(mesh.subMeshes.map(({ start, count, topology }) => ({ start, count, topology }))).toEqual( + expected.subMeshes.map(({ start, count, topology }) => ({ start, count, topology })) + ); + expect(mesh.accessible).toBe(expected.accessible); + if (mesh.accessible) { + expect(mesh.getIndices()).toEqual(expected.getIndices()); + } + expect(JSON.stringify(parsed)).toBe(serialized); + } finally { + request.mockRestore(); + mesh?.destroy(); + expected.destroy(); + } + }); + + it.each([{}, { subdivisionLevel: 1, keepMeshData: true }])( + "reuses serialized options without angle ranges: %j", + async (sphereOptions) => { + const data: PrimitiveMeshAsset = { type: "sphere", sphereRadius: 0.5, sphereOptions }; + const serialized = JSON.stringify(data); + const request = vi.spyOn(engine.resourceManager, "_request").mockReturnValue(AssetPromise.resolve(data) as any); + const create = vi.spyOn(PrimitiveMesh, "createSphere"); + let mesh: ModelMesh | undefined; + try { + mesh = await engine.resourceManager.load({ + url: "numeric-options.mesh", + type: AssetType.PrimitiveMesh + }); + expect(create.mock.calls[0][2]).toBe(sphereOptions); + expect(JSON.stringify(data)).toBe(serialized); + } finally { + create.mockRestore(); + request.mockRestore(); + mesh?.destroy(); + } + } + ); + + it("converts serialized ranges to Vector2 without modifying the asset", async () => { + const data: PrimitiveMeshAsset = { + type: "sphere", + sphereRadius: 0.5, + sphereOptions: { horizontalAngleRange: { x: 350, y: 370 }, verticalAngleRange: { x: 30, y: 150 } } + }; + const serialized = JSON.stringify(data); + const request = vi.spyOn(engine.resourceManager, "_request").mockReturnValue(AssetPromise.resolve(data) as any); + const create = vi.spyOn(PrimitiveMesh, "createSphere"); + let mesh: ModelMesh | undefined; + try { + mesh = await engine.resourceManager.load({ url: "vector-ranges.mesh", type: AssetType.PrimitiveMesh }); + const ranges = create.mock.calls[0][2]!; + expect(ranges).not.toBe(data.sphereOptions); + expect(ranges.horizontalAngleRange).toBeInstanceOf(Vector2); + expect(ranges.verticalAngleRange).toBeInstanceOf(Vector2); + expect(ranges.horizontalAngleRange!.toJSON()).toEqual({ x: 350, y: 370 }); + expect(ranges.verticalAngleRange!.toJSON()).toEqual({ x: 30, y: 150 }); + expect(JSON.stringify(data)).toBe(serialized); + } finally { + create.mockRestore(); + request.mockRestore(); + mesh?.destroy(); + } + }); + + it.each([ + { caps: PrimitiveMeshCapMode.Both, value: "both", top: true, bottom: true }, + { caps: PrimitiveMeshCapMode.Top, value: "top", top: true, bottom: false }, + { caps: PrimitiveMeshCapMode.Bottom, value: "bottom", top: false, bottom: true }, + { caps: PrimitiveMeshCapMode.None, value: "none", top: false, bottom: false } + ])( + "loads the $value cap mode from serialized cylinder and truncated cone assets", + async ({ caps, value, top, bottom }) => { + const request = vi.spyOn(engine.resourceManager, "_request"); + try { + for (const type of ["cylinder", "truncatedCone"] as const) { + const optionsKey = `${type}Options`; + const shape = + type === "cylinder" + ? { type, cylinderRadius: 0.5, cylinderHeight: 2 } + : { type, truncatedConeTopRadius: 0.25, truncatedConeBottomRadius: 0.5, truncatedConeHeight: 2 }; + const data = JSON.parse( + JSON.stringify({ ...shape, [optionsKey]: { caps, keepMeshData: true, separateMaterialSlots: true } }) + ); + expect(data[optionsKey].caps).toBe(value); + request.mockReturnValue(AssetPromise.resolve(data) as any); + const mesh = await engine.resourceManager.load({ + url: `${type}-${value}.mesh`, + type: AssetType.PrimitiveMesh + }); + try { + const normals = mesh.getNormals()!; + expect(normals.some((normal) => normal.y === 1)).toBe(top); + expect(normals.some((normal) => normal.y === -1)).toBe(bottom); + expect(mesh.subMeshes).toHaveLength(1 + Number(top) + Number(bottom)); + } finally { + mesh.destroy(); + } + } + } finally { + request.mockRestore(); + } + } + ); + + it("rejects an unknown primitive mesh type", async () => { + const request = vi + .spyOn(engine.resourceManager, "_request") + .mockReturnValue(AssetPromise.resolve({ type: "unknown" }) as any); + try { + await expect( + engine.resourceManager.load({ url: "unknown.mesh", type: AssetType.PrimitiveMesh }) + ).rejects.toThrow("Unknown primitive mesh type: unknown"); + } finally { + request.mockRestore(); + } + }); +});