From f9073d0e25e4484abb1b1f295f9edee687b181ec Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sat, 14 Nov 2026 19:43:55 +0800 Subject: [PATCH 01/24] feat(core): expand primitive mesh creation Add named options, angular sections, contour and path generators, regular polyhedra, rounded cuboids, and serializable assets for all 20 factories. Share tangent generation and preserve primitive buffer ownership on restore. Migrate examples, docs and tests, including six visual galleries. BREAKING CHANGE: PrimitiveMesh factories use named options. createSphere uses cube subdivision and replaces createSubdivisionSurfaceSphere. Angular ranges use Vector2; serialized ranges use coordinate objects. --- LICENSE | 42 + README.md | 2 +- docs/en/graphics/mesh/primitiveMesh.mdx | 192 +- docs/en/graphics/renderer/meshRenderer.mdx | 2 +- docs/zh/graphics/mesh/primitiveMesh.mdx | 198 +- docs/zh/graphics/renderer/meshRenderer.mdx | 2 +- e2e/case/.initPostProcessEnv.ts | 2 +- e2e/case/.primitiveMeshGallery.ts | 188 + e2e/case/camera-opaque-texture.ts | 2 +- e2e/case/camera-ssao.ts | 4 +- e2e/case/canvas-transparency.ts | 6 +- e2e/case/gpu-instancing-custom-data.ts | 2 +- e2e/case/material-LUT.ts | 2 +- e2e/case/material-white-furnace.ts | 2 +- e2e/case/multi-camera-no-clear.ts | 4 +- e2e/case/multi-scene-clear.ts | 4 +- e2e/case/multi-scene-no-clear.ts | 4 +- e2e/case/physx-collision-group.ts | 8 +- e2e/case/physx-collision.ts | 4 +- e2e/case/physx-customUrl.ts | 4 +- e2e/case/physx-deferred-contact.ts | 2 +- e2e/case/physx-mesh-collider.ts | 2 +- e2e/case/primitive-all.ts | 279 ++ e2e/case/primitive-capsule.ts | 2 +- e2e/case/primitive-contours.ts | 127 + e2e/case/primitive-materials.ts | 128 + e2e/case/primitive-sections.ts | 106 + e2e/case/primitive-sphere-sections.ts | 102 + e2e/case/primitive-sphere.ts | 2 +- e2e/case/primitive-topology.ts | 168 + e2e/case/shadow-basic.ts | 2 +- e2e/case/shadow-transparent.ts | 2 +- e2e/case/texture-R8G8.ts | 2 +- e2e/case/texture-hdr.ts | 2 +- e2e/case/texture-sRGB-KTX2.ts | 2 +- e2e/config.ts | 36 + .../Advance_multi-camera-no-clear.jpg | 4 +- .../Material_material-white-furnace.jpg | 4 +- .../originImage/Material_shader-mrt.jpg | 4 +- .../Material_shader-renderState.jpg | 4 +- .../Physics_physx-collision-group.jpg | 4 +- .../originImage/Physics_physx-collision.jpg | 4 +- .../originImage/Physics_physx-customUrl.jpg | 4 +- .../originImage/Primitive_primitive-all.jpg | 3 + .../Primitive_primitive-contours.jpg | 3 + .../Primitive_primitive-materials.jpg | 3 + .../Primitive_primitive-sections.jpg | 3 + .../Primitive_primitive-sphere-sections.jpg | 3 + .../Primitive_primitive-topology.jpg | 3 + e2e/primitive-mesh.md | 24 + examples/src/gltf-loader.ts | 2 +- examples/src/gpu-instancing-auto-batch.ts | 2 +- examples/src/gpu-instancing-custom-data.ts | 2 +- examples/src/shader-01-basic-shader.ts | 2 +- examples/src/shader-02-render-state.ts | 2 +- examples/src/shader-03-ui-script.ts | 2 +- examples/src/shader-04-multi-pass.ts | 2 +- packages/core/src/mesh/MeshTangentUtils.ts | 142 + packages/core/src/mesh/ModelMesh.ts | 184 +- packages/core/src/mesh/PrimitiveMesh.ts | 3161 ++++++++++------- .../core/src/mesh/PrimitiveMeshOptions.ts | 627 ++++ .../core/src/mesh/PrimitiveMeshRestorer.ts | 272 -- .../src/mesh/enums/PrimitiveMeshCapMode.ts | 21 + packages/core/src/mesh/index.ts | 24 + .../core/src/mesh/primitive/MeshPathUtils.ts | 151 + .../core/src/mesh/primitive/PolygonUtils.ts | 741 ++++ .../mesh/primitive/PrimitiveMeshBuilder.ts | 112 + .../mesh/primitive/PrimitiveMeshRestorer.ts | 67 + .../src/mesh/primitive/SubdivisionUtils.ts | 96 + packages/galacean/README.md | 2 +- .../references/mesh-geometry.md | 57 +- packages/loader/src/PrimitiveMeshAsset.ts | 125 + packages/loader/src/PrimitiveMeshLoader.ts | 193 +- packages/loader/src/index.ts | 1 + .../package-consumer/PrimitiveMeshApi.test.ts | 89 + .../fixtures/PrimitiveMeshApi.ts | 315 ++ .../fixtures/PrimitiveMeshAsset.ts | 136 + tests/src/core/DeviceLost.test.ts | 2 +- tests/src/core/Light.test.ts | 2 +- tests/src/core/MeshRenderer.test.ts | 4 +- tests/src/core/Shader.test.ts | 4 +- tests/src/core/mesh/BlendShape.test.ts | 2 +- tests/src/core/mesh/BlendShapeManager.test.ts | 20 +- tests/src/core/mesh/PrimitiveMesh.test.ts | 145 +- tests/src/core/mesh/ProceduralMesh.test.ts | 2072 +++++++++++ tests/src/core/physics/ColliderLayer.test.ts | 10 +- .../core/physics/MeshColliderLayer.test.ts | 10 +- tests/src/loader/PrimitiveMeshLoader.test.ts | 643 ++++ tests/src/spine/SpineAlpha.test.ts | 2 +- 89 files changed, 9182 insertions(+), 1972 deletions(-) create mode 100644 e2e/case/.primitiveMeshGallery.ts create mode 100644 e2e/case/primitive-all.ts create mode 100644 e2e/case/primitive-contours.ts create mode 100644 e2e/case/primitive-materials.ts create mode 100644 e2e/case/primitive-sections.ts create mode 100644 e2e/case/primitive-sphere-sections.ts create mode 100644 e2e/case/primitive-topology.ts create mode 100644 e2e/fixtures/originImage/Primitive_primitive-all.jpg create mode 100644 e2e/fixtures/originImage/Primitive_primitive-contours.jpg create mode 100644 e2e/fixtures/originImage/Primitive_primitive-materials.jpg create mode 100644 e2e/fixtures/originImage/Primitive_primitive-sections.jpg create mode 100644 e2e/fixtures/originImage/Primitive_primitive-sphere-sections.jpg create mode 100644 e2e/fixtures/originImage/Primitive_primitive-topology.jpg create mode 100644 e2e/primitive-mesh.md create mode 100644 packages/core/src/mesh/MeshTangentUtils.ts create mode 100644 packages/core/src/mesh/PrimitiveMeshOptions.ts delete mode 100644 packages/core/src/mesh/PrimitiveMeshRestorer.ts create mode 100644 packages/core/src/mesh/enums/PrimitiveMeshCapMode.ts create mode 100644 packages/core/src/mesh/primitive/MeshPathUtils.ts create mode 100644 packages/core/src/mesh/primitive/PolygonUtils.ts create mode 100644 packages/core/src/mesh/primitive/PrimitiveMeshBuilder.ts create mode 100644 packages/core/src/mesh/primitive/PrimitiveMeshRestorer.ts create mode 100644 packages/core/src/mesh/primitive/SubdivisionUtils.ts create mode 100644 packages/loader/src/PrimitiveMeshAsset.ts create mode 100644 tests/package-consumer/PrimitiveMeshApi.test.ts create mode 100644 tests/package-consumer/fixtures/PrimitiveMeshApi.ts create mode 100644 tests/package-consumer/fixtures/PrimitiveMeshAsset.ts create mode 100644 tests/src/core/mesh/ProceduralMesh.test.ts create mode 100644 tests/src/loader/PrimitiveMeshLoader.test.ts diff --git a/LICENSE b/LICENSE index 742b2b0fff..36987e9152 100644 --- a/LICENSE +++ b/LICENSE @@ -19,3 +19,45 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Third-party notices +=================== + +Regular-polyhedron vertex and face tables and rounded-cuboid UV mapping are derived from three.js +Copyright (c) 2010-2026 three.js authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Polygon triangulation adapted from Mapbox Earcut 3.0.2. +https://github.com/mapbox/earcut/tree/v3.0.2 + +ISC License +Copyright (c) 2024, Mapbox + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/README.md b/README.md index 0013443a68..62397da938 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ const meshEntity = rootEntity.createChild("Sphere"); const meshRenderer = meshEntity.addComponent(MeshRenderer); const material = new BlinnPhongMaterial(engine); meshRenderer.setMaterial(material); -meshRenderer.mesh = PrimitiveMesh.createSphere(engine, 1); +meshRenderer.mesh = PrimitiveMesh.createSphere(engine, { radius: 1 }); // Run engine engine.run(); diff --git a/docs/en/graphics/mesh/primitiveMesh.mdx b/docs/en/graphics/mesh/primitiveMesh.mdx index c7feaea26f..9af04d7a1f 100644 --- a/docs/en/graphics/mesh/primitiveMesh.mdx +++ b/docs/en/graphics/mesh/primitiveMesh.mdx @@ -12,15 +12,27 @@ 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 @@ -116,3 +128,177 @@ const material = new BlinnPhongMaterial(engine); material.emissiveColor.set(1, 1, 1, 1); renderer.setMaterial(material); ``` + +## Procedural geometry + +Each factory accepts one named options object. Every options type documents its fields, units and defaults. Omit the object to use all defaults, or specify only the fields you need. For example, `createSphere` accepts `SphereMeshOptions`: + +```ts +const unitSphere = PrimitiveMesh.createSphere(engine); +const sphere = PrimitiveMesh.createSphere(engine, { radius: 1 }); +const smoothSphere = PrimitiveMesh.createSphere(engine, { radius: 1, subdivisions: 4 }); +const cube = PrimitiveMesh.createCuboid(engine, { width: 2 }); +const box = PrimitiveMesh.createCuboid(engine, { width: 2, height: 3, depth: 4 }); +const ground = PrimitiveMesh.createPlane(engine, { width: 10 }); +const cylinder = PrimitiveMesh.createCylinder(engine, { radius: 0.5, height: 2 }); +const frustum = PrimitiveMesh.createTruncatedCone(engine, { topRadius: 0.25, bottomRadius: 0.5, height: 2 }); +const mirroredKnot = PrimitiveMesh.createTorusKnot(engine, { radius: 1, tubeRadius: 0.1, p: 2, q: -3 }); +``` + +Cuboid height and depth default to its width. Plane height defaults to its width. 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 outer radius first; the inner radius defaults to half the outer radius. + +For torus knots, `p` and `q` are signed integer revolution counts, independent of mesh subdivisions. Negative values reverse the corresponding winding direction; zero keeps that angle fixed. + +| 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 profile, path tube, polygon, extrusion, rounded cuboid | `createLathe`, `createTube`, `createPolygon`, `createExtrusion`, `createRoundedCuboid` | + +### Subdivisions, angles and caps + +Dimensions and subdivisions are named fields in the same options object. For tubes and tori, `tubularSegments` controls longitudinal subdivisions and `radialSegments` controls the cross-section. Capsule `capSegments` controls each pole-to-equator section independently; its height describes the cylindrical section. + +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, cones and lathes rotate around Y starting from +Z; a sphere's vertical angle starts at +Y. + +```ts +import { PrimitiveMeshCapMode, Vector2 } from "@galacean/engine"; + +const hemisphere = PrimitiveMesh.createSphere(engine, { verticalRange: new Vector2(0, 90), radius: 1 }); +const openCylinder = PrimitiveMesh.createCylinder(engine, { caps: PrimitiveMeshCapMode.None, radius: 0.5, height: 2 }); +const cupWall = PrimitiveMesh.createCylinder(engine, { caps: PrimitiveMeshCapMode.Bottom, radius: 0.5, height: 2 }); +const halfRing = PrimitiveMesh.createRing(engine, { angleRange: new Vector2(0, 180), outerRadius: 1, innerRadius: 0.5 }); +``` + +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 `horizontalRange` and `verticalRange`. 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 + +Contours and lathe profiles use `Vector2` arrays, and path points use `Vector3` 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. Closing points need not be repeated. + +```ts +import { Vector2, Vector3 } from "@galacean/engine"; + +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.createExtrusion(engine, { points: outline, holes: [hole] }, { depth: 0.5 }); +const beveled = PrimitiveMesh.createExtrusion(engine, outline, { + bevelSize: 0.05, + bevelOffset: 0.02, + depth: 0.5, + steps: 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, { radius: 0.1, tubularSegments: 64 }); +const swept = PrimitiveMesh.createExtrusion(engine, outline, { path: path, steps: 64 }); +const loop = [new Vector3(-4, 0, -4), new Vector3(4, 0, -4), new Vector3(4, 0, 4), new Vector3(-4, 0, 4)]; +const closed = PrimitiveMesh.createExtrusion(engine, outline, { closed: true, path: loop, steps: 32 }); +``` + +Extrusion uses `LinearExtrusionMeshOptions` for `depth` and bevels, or `PathExtrusionMeshOptions` with a required `path`. TypeScript rejects combinations of a path with depth or bevel settings. The default extrusion goes along +Z without bevels. A positive `bevelSize` enables beveling; `bevelThickness` defaults to the same value. Path extrusion does not generate bevels. Paths accept `Vector3` arrays and 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, `closed` 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 steps and have no end caps. Open extrusions have two end caps; tubes have no end caps in either mode. + +`bevelOffset` 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 `bevelSize` is `0`. Bevels are cut into this outline and included in `depth`, so they do not increase the total depth. + +### Mesh data and materials + +Mesh settings belong to the same options object as dimensions and subdivisions: + +```ts +const editable = PrimitiveMesh.createSphere(engine, { keepData: true, radius: 1, subdivisions: 3 }); +const sixMaterials = PrimitiveMesh.createCuboid(engine, { + separateMaterials: true, + width: 1, + height: 1, + depth: 1, + widthSegments: 1, + heightSegments: 1, + depthSegments: 1 +}); +``` + +`keepData` defaults to false. Set it to true to retain readable CPU vertex attributes. + +`separateMaterials` 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 | +| Extrusion | 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", + sphereOptions: { radius: 1, subdivisions: 3, keepData: true } +} satisfies PrimitiveMeshAsset; +``` + +Each `type` selects the matching `PrimitiveMesh.createX` method. `Options` follows that factory's named fields and defaults. 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 fields use the creation API's defaults, including defaults derived from another field. Angles remain in degrees. + +| Asset types | Required geometry fields | +| --- | --- | +| `sphere`, `cuboid`, `plane` | None | +| `cylinder`, `truncatedCone`, `cone`, `capsule` | None | +| `torus`, `circle`, `ring`, `torusKnot`, `roundedCuboid` | None | +| `tetrahedron`, `octahedron`, `icosahedron`, `dodecahedron` | None | +| `lathe` | `latheProfile` | +| `tube` | `tubePath` | +| `polygon` | `polygonShapes` | +| `extrusion` | `extrusionShapes`; optional `extrusionOptions.depth` or `extrusionOptions.path` | + +`sphere` creates a subdivided cube projected onto a sphere; `sphereOptions.subdivisions` controls its subdivision level. `cylinder` has one radius; `truncatedCone` has independent `truncatedConeOptions.topRadius` and `truncatedConeOptions.bottomRadius`. + +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": "extrusion", + "extrusionShapes": [ + { + "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 } + ] + ] + } + ], + "extrusionOptions": { "depth": 2, "bevelSize": 0.1, "bevelOffset": 0.2, "separateMaterials": true } +} +``` + +Path extrusion uses `extrusionOptions.path` in place of `extrusionOptions.depth` and does not accept bevel options. Set `extrusionOptions.closed` to `true` for a closed path without end caps. Save path points as `{ x, y, z }`. + +The type-prefixed fields, including `Options`, pass through the Editor's primitive asset bundler. Editor previews should select the same creation method and parameters as the saved asset. diff --git a/docs/en/graphics/renderer/meshRenderer.mdx b/docs/en/graphics/renderer/meshRenderer.mdx index af4226e3b1..1a4b24e2e6 100644 --- a/docs/en/graphics/renderer/meshRenderer.mdx +++ b/docs/en/graphics/renderer/meshRenderer.mdx @@ -23,7 +23,7 @@ Here's how to use it in code: ```typescript const cubeEntity = rootEntity.createChild("cube"); const cube = cubeEntity.addComponent(MeshRenderer); -cube.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); +cube.mesh = PrimitiveMesh.createCuboid(engine, { width: 2 }); cube.setMaterial(new BlinnPhongMaterial(engine)); ``` diff --git a/docs/zh/graphics/mesh/primitiveMesh.mdx b/docs/zh/graphics/mesh/primitiveMesh.mdx index 3f5fb7c428..85383e639f 100644 --- a/docs/zh/graphics/mesh/primitiveMesh.mdx +++ b/docs/zh/graphics/mesh/primitiveMesh.mdx @@ -12,15 +12,27 @@ 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 ## 脚本使用 @@ -116,3 +128,183 @@ const material = new BlinnPhongMaterial(engine); material.emissiveColor.set(1, 1, 1, 1); renderer.setMaterial(material); ``` + +## 程序化几何 + +每个工厂方法接收一个具名配置对象。配置类型逐字段说明含义、单位和默认值;省略对象或其中的字段即可使用默认值。例如,`createSphere` 接收 `SphereMeshOptions`: + +```ts +const unitSphere = PrimitiveMesh.createSphere(engine); +const sphere = PrimitiveMesh.createSphere(engine, { radius: 1 }); +const smoothSphere = PrimitiveMesh.createSphere(engine, { radius: 1, subdivisions: 4 }); + +const cube = PrimitiveMesh.createCuboid(engine, { width: 2 }); +const box = PrimitiveMesh.createCuboid(engine, { width: 2, height: 3, depth: 4 }); +const ground = PrimitiveMesh.createPlane(engine, { width: 10 }); + +const cylinder = PrimitiveMesh.createCylinder(engine, { radius: 0.5, height: 2 }); +const frustum = PrimitiveMesh.createTruncatedCone(engine, { topRadius: 0.25, bottomRadius: 0.5, height: 2 }); +const mirroredKnot = PrimitiveMesh.createTorusKnot(engine, { radius: 1, tubeRadius: 0.1, p: 2, q: -3 }); +``` + +`createCuboid` 的高度、深度默认等于宽度;`createPlane` 的高度默认等于宽度。平面和长方体的后续分段数默认沿用第一个方向的分段数。球体使用一个细分层级,默认为 3,限制在 1 到 6 之间。`createCylinder` 只有一个半径;上下半径不同的圆台使用 `createTruncatedCone`。`createRing` 的 `innerRadius` 默认等于 `outerRadius` 的一半。 + +尺寸、分段和网格设置都使用具名字段,可以只修改其中任意一项。 + +环面结的 `p`、`q` 是有符号整数缠绕次数,与网格分段数无关。负值反转对应方向的缠绕,`0` 表示该方向的角度保持不变。 + +| 能力 | 创建方法 | +| --- | --- | +| 平面、长方体、球 | `createPlane`、`createCuboid`、`createSphere` | +| 圆柱、圆台、圆锥、胶囊 | `createCylinder`、`createTruncatedCone`、`createCone`、`createCapsule` | +| 圆盘、圆环面、圆环体、环面结 | `createCircle`、`createRing`、`createTorus`、`createTorusKnot` | +| 四面体、八面体、二十面体、十二面体 | `createTetrahedron`、`createOctahedron`、`createIcosahedron`、`createDodecahedron` | +| 旋转体、路径管道、平面多边形、拉伸、圆角长方体 | `createLathe`、`createTube`、`createPolygon`、`createExtrusion`、`createRoundedCuboid` | + +### 分段、角度和端盖 + +`createTube` 与 `createTorus` 的 `tubularSegments` 控制管道方向的分段,`radialSegments` 控制截面的周向分段。胶囊的 `capSegments` 独立控制每个半球从极点到赤道的分段,`height` 仍指圆柱部分的高度。 + +角度范围统一放在配置对象中。所有角度均使用**度数**,范围使用 `Vector2`,`x` 表示起始角,`y` 表示结束角。跨越 360 度时使用连续角度,例如 `new Vector2(350, 370)`。圆柱、圆锥和旋转体围绕 Y 轴,0 度从 +Z 方向开始;球体的垂直角度从 +Y 极点开始。 + +```ts +import { PrimitiveMeshCapMode, Vector2 } from "@galacean/engine"; + +const hemisphere = PrimitiveMesh.createSphere(engine, { verticalRange: new Vector2(0, 90), radius: 1 }); +const openCylinder = PrimitiveMesh.createCylinder(engine, { caps: PrimitiveMeshCapMode.None, radius: 0.5, height: 2 }); +const cupWall = PrimitiveMesh.createCylinder(engine, { caps: PrimitiveMeshCapMode.Bottom, radius: 0.5, height: 2 }); +const halfRing = PrimitiveMesh.createRing(engine, { angleRange: new Vector2(0, 180), outerRadius: 1, innerRadius: 0.5 }); +``` + +圆柱和圆台的 `caps` 使用 `PrimitiveMeshCapMode`:`Both`(默认)、`Top`、`Bottom`、`None`。顶盖朝 +Y,底盖朝 -Y,角度裁切产生的侧面切口保持开放。圆锥用布尔值 `cap` 控制底盖。`createCircle`、`createRing` 和多边形位于 XY 平面、正面朝 +Z;地面用的 `createPlane` 位于 XZ 平面、正面朝 +Y。 + +`createSphere` 将细分后的立方体投影到球面,支持 `horizontalRange` 和 `verticalRange`。水平角度从 -X 朝 +Z 开始,垂直角度从 +Y 极点开始。裁切保留细分表面,切口不生成端盖;水平范围 `new Vector2(350, 370)` 可跨越接缝。细分层级控制表面及裁切边界的精细程度。 + +### 轮廓与路径 + +轮廓和旋转体截面使用 `Vector2` 数组,路径点使用 `Vector3` 数组。一个简单多边形直接传入点数组;有孔洞时使用 `{ points, holes }`,多个多边形使用这种对象的数组。首尾点不必重复。 + +```ts +import { Vector2, Vector3 } from "@galacean/engine"; + +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.createExtrusion(engine, { points: outline, holes: [hole] }, { depth: 0.5 }); +const beveled = PrimitiveMesh.createExtrusion(engine, outline, { + bevelSize: 0.05, + bevelOffset: 0.02, + depth: 0.5, + steps: 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, { radius: 0.1, tubularSegments: 64 }); +const swept = PrimitiveMesh.createExtrusion(engine, outline, { path: path, steps: 64 }); +const loop = [new Vector3(-4, 0, -4), new Vector3(4, 0, -4), new Vector3(4, 0, 4), new Vector3(-4, 0, 4)]; +const closed = PrimitiveMesh.createExtrusion(engine, outline, { closed: true, path: loop, steps: 32 }); +``` + +拉伸配置分为 `LinearExtrusionMeshOptions` 和 `PathExtrusionMeshOptions`:前者指定 `depth` 与倒角,后者必须指定 `path`。TypeScript 会拒绝同时传入路径与深度或倒角的组合。默认沿 +Z 直线拉伸且不倒角;`bevelSize > 0` 时开启倒角,`bevelThickness` 默认等于 `bevelSize`。沿路径拉伸不生成倒角。路径接收 `Vector3` 数组,并按折线长度均匀采样。使用曲线时,在外层采样成点数组后传入,如上例所示。 + +管道和路径挤出的 `closed` 默认关闭;开启后自动连接路径首尾并对齐截面,不必重复首点。闭合挤出至少使用三段,不生成端盖。开放挤出保留两端端盖;管道在两种模式下都不生成端盖。 + +`bevelOffset` 默认是 `0`,用于偏移侧壁轮廓:正值外扩实体并缩小孔洞,负值内缩实体并扩大孔洞。`bevelSize` 为 `0` 时偏移仍然生效。倒角从偏移后的轮廓向内削边,厚度包含在 `depth` 内,不会增加总厚度。 + +### 网格数据和材质 + +网格设置与尺寸、分段放在同一配置对象中: + +```ts +const editable = PrimitiveMesh.createSphere(engine, { keepData: true, radius: 1, subdivisions: 3 }); +const sixMaterials = PrimitiveMesh.createCuboid(engine, { + separateMaterials: true, + width: 1, + height: 1, + depth: 1, + widthSegments: 1, + heightSegments: 1, + depthSegments: 1 +}); +``` + +`keepData` 默认关闭,设为 `true` 时保留可读的 CPU 顶点属性。 + +`separateMaterials` 适用于长方体、圆柱、圆台、圆锥、多边形、挤出和圆角长方体。默认关闭,生成一个 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", + sphereOptions: { radius: 1, subdivisions: 3, keepData: true } +} satisfies PrimitiveMeshAsset; +``` + +每个 `type` 对应同名的 `PrimitiveMesh.createX` 方法,`Options` 使用该工厂的具名字段和默认值。角度范围保存为 `{ x: 起始角, y: 结束角 }`,由 Loader 构造 `Vector2`。例如 `circleOptions: { angleRange: { x: 30, y: 180 } }` 创建从 30 度到 180 度的扇形。省略字段时采用创建 API 的默认值,包括由其他字段决定的默认值;角度仍使用度数。 + +| 资产类型 | 必填几何字段 | +| --- | --- | +| `sphere`、`cuboid`、`plane` | 无 | +| `cylinder`、`truncatedCone`、`cone`、`capsule` | 无 | +| `torus`、`circle`、`ring`、`torusKnot`、`roundedCuboid` | 无 | +| `tetrahedron`、`octahedron`、`icosahedron`、`dodecahedron` | 无 | +| `lathe` | `latheProfile` | +| `tube` | `tubePath` | +| `polygon` | `polygonShapes` | +| `extrusion` | `extrusionShapes`;可指定 `extrusionOptions.depth` 或 `extrusionOptions.path` | + +`sphere` 创建立方体细分后投影得到的球体,`sphereOptions.subdivisions` 控制细分层级。`cylinder` 使用一个半径;`truncatedCone` 分别使用 `truncatedConeOptions.topRadius` 和 `truncatedConeOptions.bottomRadius`。 + +轮廓和旋转截面保存为 `{ x, y }` 点数组,路径保存为 `{ x, y, z }` 点数组,由 Loader 构造对应向量。多边形与拉伸统一使用形状数组,每个形状包含 `points` 和可选的 `holes`: + +```json +{ + "type": "extrusion", + "extrusionShapes": [ + { + "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 } + ] + ] + } + ], + "extrusionOptions": { "depth": 2, "bevelSize": 0.1, "bevelOffset": 0.2, "separateMaterials": true } +} +``` + +沿路径拉伸使用 `extrusionOptions.path` 替代 `extrusionOptions.depth`,不接受倒角选项。`extrusionOptions.closed` 设为 `true` 时闭合路径且不生成端盖。路径点保存为 `{ x, y, z }`。 + +以上类型前缀字段及 `Options` 都能经过 Editor 现有的基础网格打包过滤。Editor 预览应使用与保存资产相同的创建方法和参数。 diff --git a/docs/zh/graphics/renderer/meshRenderer.mdx b/docs/zh/graphics/renderer/meshRenderer.mdx index d93b39ad01..dde0fc497a 100644 --- a/docs/zh/graphics/renderer/meshRenderer.mdx +++ b/docs/zh/graphics/renderer/meshRenderer.mdx @@ -23,7 +23,7 @@ label: Graphics/Renderer ```typescript const cubeEntity = rootEntity.createChild("cube"); const cube = cubeEntity.addComponent(MeshRenderer); -cube.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); +cube.mesh = PrimitiveMesh.createCuboid(engine, { width: 2 }); cube.setMaterial(new BlinnPhongMaterial(engine)); ``` diff --git a/e2e/case/.initPostProcessEnv.ts b/e2e/case/.initPostProcessEnv.ts index bbcba54183..8a260c660e 100644 --- a/e2e/case/.initPostProcessEnv.ts +++ b/e2e/case/.initPostProcessEnv.ts @@ -47,7 +47,7 @@ export async function initPostProcessEnv( scene.background.mode = BackgroundMode.Sky; sky.material = skyMaterial; - sky.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); + sky.mesh = PrimitiveMesh.createCuboid(engine, { width: 1, height: 1, depth: 1 }); skyMaterial.texture = ambientLight.specularTexture; return ambientLight; }), 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-opaque-texture.ts b/e2e/case/camera-opaque-texture.ts index 646ae31809..29bcaeca7e 100644 --- a/e2e/case/camera-opaque-texture.ts +++ b/e2e/case/camera-opaque-texture.ts @@ -153,7 +153,7 @@ function showOpaquePlane(engine: Engine, camera: Entity): void { entity.transform.setPosition(0, 0, -1); entity.transform.rotate(new Vector3(90, 0, 0)); const renderer = entity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createPlane(engine, 0.5, 0.5); + renderer.mesh = PrimitiveMesh.createPlane(engine, { width: 0.5 }); // Create material const material = new BaseMaterial(engine, Shader.find("RenderOpaqueTexture")); diff --git a/e2e/case/camera-ssao.ts b/e2e/case/camera-ssao.ts index d38998ef58..cb25ac6061 100644 --- a/e2e/case/camera-ssao.ts +++ b/e2e/case/camera-ssao.ts @@ -52,7 +52,7 @@ WebGLEngine.create({ const skyMaterial = new SkyBoxMaterial(engine); background.mode = BackgroundMode.Sky; sky.material = skyMaterial; - sky.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); + sky.mesh = PrimitiveMesh.createCuboid(engine); // Sphere const sphereMaterial = new PBRMaterial(engine); @@ -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); meshRenderer.setMaterial(sphereMaterial); // Box diff --git a/e2e/case/canvas-transparency.ts b/e2e/case/canvas-transparency.ts index f140cb0334..a0c998ea60 100644 --- a/e2e/case/canvas-transparency.ts +++ b/e2e/case/canvas-transparency.ts @@ -82,7 +82,7 @@ WebGLEngine.create({ canvas: "canvas", graphicDeviceOptions: { alpha: false } }) canvasPlaneEntity.transform.setPosition(0, 0, 0); canvasPlaneEntity.transform.rotate(new Vector3(90, 0, 0)); const renderer = canvasPlaneEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createPlane(engine, 2, 2); + renderer.mesh = PrimitiveMesh.createPlane(engine, { width: 2 }); renderer.setMaterial(canvasMaterial); updateForE2E(engine); @@ -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); 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); const sphereMaterial = new UnlitMaterial(engine); sphereRenderer.setMaterial(sphereMaterial); diff --git a/e2e/case/gpu-instancing-custom-data.ts b/e2e/case/gpu-instancing-custom-data.ts index 290f478ca9..48982d3861 100644 --- a/e2e/case/gpu-instancing-custom-data.ts +++ b/e2e/case/gpu-instancing-custom-data.ts @@ -79,7 +79,7 @@ WebGLEngine.create({ canvas: "canvas", shaderCompiler }).then((engine) => { lightEntity.addComponent(DirectLight).color = new Color(1, 1, 1, 1); // Shared mesh and material - const mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); + const mesh = PrimitiveMesh.createCuboid(engine); const material = new Material(engine, Shader.find("CustomInstanceShader")); const customColorProperty = ShaderProperty.getByName("renderer_CustomColor"); diff --git a/e2e/case/material-LUT.ts b/e2e/case/material-LUT.ts index 149c0fd5c1..09ca9fddd0 100644 --- a/e2e/case/material-LUT.ts +++ b/e2e/case/material-LUT.ts @@ -56,7 +56,7 @@ WebGLEngine.create({ canvas: "canvas", shaderCompiler }) const entity = rootEntity.createChild("Entity"); entity.transform.setRotation(90, 0, 0); const renderer = entity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createPlane(engine, 1, 1); + renderer.mesh = PrimitiveMesh.createPlane(engine); const shader = Shader.create(shaderSource); const material = new Material(engine, shader); diff --git a/e2e/case/material-white-furnace.ts b/e2e/case/material-white-furnace.ts index 00baa80276..ff19f0fc42 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, { radius: 0.5, subdivisions: 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..44c7dc9b07 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, { radius: 2, subdivisions: 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, { radius: 2, subdivisions: 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/multi-scene-clear.ts b/e2e/case/multi-scene-clear.ts index 78cc90f01b..12f124fbe0 100644 --- a/e2e/case/multi-scene-clear.ts +++ b/e2e/case/multi-scene-clear.ts @@ -41,7 +41,7 @@ function initFirstScene(engine: Engine): Camera { const cubeEntity = rootEntity.createChild("cube"); cubeEntity.transform.setPosition(-2, 0, 3); const renderer = cubeEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); + renderer.mesh = PrimitiveMesh.createCuboid(engine, { width: 2 }); const material = new BlinnPhongMaterial(engine); material.baseColor = new Color(1, 0, 0, 1); renderer.setMaterial(material); @@ -73,7 +73,7 @@ function initSecondScene(engine: Engine): Camera { const cubeEntity = rootEntity.createChild("cube"); cubeEntity.transform.setPosition(2, 0, 3); const renderer = cubeEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); + renderer.mesh = PrimitiveMesh.createCuboid(engine, { width: 2 }); 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/multi-scene-no-clear.ts b/e2e/case/multi-scene-no-clear.ts index 976e67e8ae..22c7eac833 100644 --- a/e2e/case/multi-scene-no-clear.ts +++ b/e2e/case/multi-scene-no-clear.ts @@ -48,7 +48,7 @@ function initFirstScene(engine: Engine): Camera { const cubeEntity = rootEntity.createChild("cube"); cubeEntity.transform.setPosition(-2, 0, 3); const renderer = cubeEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); + renderer.mesh = PrimitiveMesh.createCuboid(engine, { width: 2 }); const material = new BlinnPhongMaterial(engine); material.baseColor = new Color(1, 0, 0, 1); renderer.setMaterial(material); @@ -80,7 +80,7 @@ function initSecondScene(engine: Engine): Camera { const cubeEntity = rootEntity.createChild("cube"); cubeEntity.transform.setPosition(2, 0, 3); const renderer = cubeEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); + renderer.mesh = PrimitiveMesh.createCuboid(engine, { width: 2 }); 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/physx-collision-group.ts b/e2e/case/physx-collision-group.ts index 94263f6d80..aeff378941 100644 --- a/e2e/case/physx-collision-group.ts +++ b/e2e/case/physx-collision-group.ts @@ -55,7 +55,7 @@ function createPhysicsSphere( sphereMtl.baseColor.set(color.x, color.y, color.z, 1.0); sphereMtl.metallic = 0.0; sphereMtl.roughness = 0.5; - sphereRenderer.mesh = PrimitiveMesh.createSphere(rootEntity.engine, radius); + sphereRenderer.mesh = PrimitiveMesh.createSphere(rootEntity.engine, { radius }); sphereRenderer.setMaterial(sphereMtl); // Add physics @@ -107,7 +107,11 @@ WebGLEngine.create({ canvas: "canvas", physics: new PhysXPhysics() }).then((engi const cubeSize = new Vector3(10, 0.2, 10); const groundRenderer = groundEntity.addComponent(MeshRenderer); - groundRenderer.mesh = PrimitiveMesh.createCuboid(engine, cubeSize.x, cubeSize.y, cubeSize.z); + groundRenderer.mesh = PrimitiveMesh.createCuboid(engine, { + width: cubeSize.x, + height: cubeSize.y, + depth: cubeSize.z + }); groundRenderer.setMaterial(groundMtl); // Physics for the ground cube diff --git a/e2e/case/physx-collision.ts b/e2e/case/physx-collision.ts index a7e2989974..3f1cd3cfc1 100644 --- a/e2e/case/physx-collision.ts +++ b/e2e/case/physx-collision.ts @@ -36,7 +36,7 @@ function addBox(rootEntity: Entity, cubeSize: number, x: number, y: number, z: n boxMtl.baseColor.set(0.6, 0.3, 0.3, 1.0); boxMtl.roughness = 0.5; boxMtl.metallic = 0.0; - boxRenderer.mesh = PrimitiveMesh.createCuboid(rootEntity.engine, cubeSize, cubeSize, cubeSize); + boxRenderer.mesh = PrimitiveMesh.createCuboid(rootEntity.engine, { width: cubeSize }); boxRenderer.setMaterial(boxMtl); if (index === 0) { boxMtl.baseColor.set(1, 0, 0, 1.0); @@ -87,7 +87,7 @@ WebGLEngine.create({ canvas: "canvas", physics: new PhysXPhysics() }).then((engi sphereMtl.baseColor.set(Math.random(), Math.random(), Math.random(), 1.0); sphereMtl.metallic = 0.0; sphereMtl.roughness = 0.5; - sphereRenderer.mesh = PrimitiveMesh.createSphere(engine, radius); + sphereRenderer.mesh = PrimitiveMesh.createSphere(engine, { radius }); sphereRenderer.setMaterial(sphereMtl); const physicsSphere = new SphereColliderShape(); diff --git a/e2e/case/physx-customUrl.ts b/e2e/case/physx-customUrl.ts index ddc1d1a752..aa5bc8edc7 100644 --- a/e2e/case/physx-customUrl.ts +++ b/e2e/case/physx-customUrl.ts @@ -35,7 +35,7 @@ function addBox(rootEntity: Entity, cubeSize: number, x: number, y: number, z: n boxMtl.baseColor.set(0.6, 0.3, 0.3, 1.0); boxMtl.roughness = 0.5; boxMtl.metallic = 0.0; - boxRenderer.mesh = PrimitiveMesh.createCuboid(rootEntity.engine, cubeSize, cubeSize, cubeSize); + boxRenderer.mesh = PrimitiveMesh.createCuboid(rootEntity.engine, { width: cubeSize }); boxRenderer.setMaterial(boxMtl); if (index === 0) { boxMtl.baseColor.set(1, 0, 0, 1.0); @@ -92,7 +92,7 @@ WebGLEngine.create({ sphereMtl.baseColor.set(Math.random(), Math.random(), Math.random(), 1.0); sphereMtl.metallic = 0.0; sphereMtl.roughness = 0.5; - sphereRenderer.mesh = PrimitiveMesh.createSphere(engine, radius); + sphereRenderer.mesh = PrimitiveMesh.createSphere(engine, { radius }); sphereRenderer.setMaterial(sphereMtl); const physicsSphere = new SphereColliderShape(); diff --git a/e2e/case/physx-deferred-contact.ts b/e2e/case/physx-deferred-contact.ts index a3e903a3d5..d28d3e9797 100644 --- a/e2e/case/physx-deferred-contact.ts +++ b/e2e/case/physx-deferred-contact.ts @@ -39,7 +39,7 @@ WebGLEngine.create({ canvas: "canvas", physics: new PhysXPhysics() }).then((engi mtl.metallic = 0.0; mtl.roughness = 0.5; const renderer = entity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); + renderer.mesh = PrimitiveMesh.createCuboid(engine, { width: 2 }); renderer.setMaterial(mtl); const shape = new BoxColliderShape(); diff --git a/e2e/case/physx-mesh-collider.ts b/e2e/case/physx-mesh-collider.ts index f3d5f63701..6836b4fbe2 100644 --- a/e2e/case/physx-mesh-collider.ts +++ b/e2e/case/physx-mesh-collider.ts @@ -38,7 +38,7 @@ function createFallingBox( // Visual const renderer = entity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createCuboid(engine, size.x, size.y, size.z); + renderer.mesh = PrimitiveMesh.createCuboid(engine, { width: size.x, height: size.y, depth: size.z }); const material = new PBRMaterial(engine); material.baseColor.copyFrom(color); material.roughness = 0.6; diff --git a/e2e/case/primitive-all.ts b/e2e/case/primitive-all.ts new file mode 100644 index 0000000000..dd92519235 --- /dev/null +++ b/e2e/case/primitive-all.ts @@ -0,0 +1,279 @@ +/** + * @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, { + separateMaterials: true, + width: 1, + height: 1, + depth: 1, + widthSegments: 2, + heightSegments: 2, + depthSegments: 2 + }) + }, + plane: { + label: "Plane", + mesh: PrimitiveMesh.createPlane(engine, { width: 2, height: 2, horizontalSegments: 4, verticalSegments: 4 }), + rotation: new Vector3(90, 0, 0) + }, + sphere: { label: "Sphere", mesh: PrimitiveMesh.createSphere(engine, { radius: 1, subdivisions: 3 }) }, + cylinder: { + label: "Cylinder", + mesh: PrimitiveMesh.createCylinder(engine, { + separateMaterials: true, + radius: 0.65, + height: 1.5, + radialSegments: 24, + heightSegments: 2 + }) + }, + cone: { + label: "Cone", + mesh: PrimitiveMesh.createCone(engine, { + separateMaterials: true, + radius: 0.8, + height: 1.8, + radialSegments: 24, + heightSegments: 2 + }) + }, + truncatedCone: { + label: "Truncated Cone", + mesh: PrimitiveMesh.createTruncatedCone(engine, { + separateMaterials: true, + topRadius: 0.35, + bottomRadius: 0.8, + height: 1.6, + radialSegments: 24, + heightSegments: 2 + }) + }, + capsule: { + label: "Capsule", + mesh: PrimitiveMesh.createCapsule(engine, { + radius: 0.5, + height: 1, + radialSegments: 24, + capSegments: 8, + heightSegments: 2 + }) + }, + torus: { + label: "Torus", + mesh: PrimitiveMesh.createTorus(engine, { + radius: 0.75, + tubeRadius: 0.25, + tubularSegments: 32, + radialSegments: 12 + }) + }, + torusKnot: { + label: "Torus Knot", + mesh: PrimitiveMesh.createTorusKnot(engine, { + radius: 0.65, + tubeRadius: 0.17, + p: 2, + q: 3, + tubularSegments: 96, + radialSegments: 10 + }) + }, + circle: { + label: "Circle", + mesh: PrimitiveMesh.createCircle(engine, { radius: 1, segments: 32 }), + rotation: new Vector3() + }, + ring: { + label: "Ring", + mesh: PrimitiveMesh.createRing(engine, { + outerRadius: 1, + innerRadius: 0.5, + radialSegments: 32, + widthSegments: 2 + }), + rotation: new Vector3() + }, + tetrahedron: { label: "Tetrahedron", mesh: PrimitiveMesh.createTetrahedron(engine, { radius: 1 }) }, + octahedron: { label: "Octahedron", mesh: PrimitiveMesh.createOctahedron(engine, { radius: 1 }) }, + icosahedron: { label: "Icosahedron", mesh: PrimitiveMesh.createIcosahedron(engine, { radius: 1 }) }, + dodecahedron: { label: "Dodecahedron", mesh: PrimitiveMesh.createDodecahedron(engine, { radius: 1 }) }, + lathe: { label: "Lathe", mesh: PrimitiveMesh.createLathe(engine, profile, { segments: 24 }) }, + tube: { + label: "Tube", + mesh: PrimitiveMesh.createTube(engine, path, { radius: 0.2, tubularSegments: 48, radialSegments: 10 }) + }, + polygon: { label: "Polygon", mesh: PrimitiveMesh.createPolygon(engine, polygon), rotation: new Vector3() }, + extrusion: { + label: "Extrusion", + mesh: PrimitiveMesh.createExtrusion(engine, polygon, { + bevelSize: 0.1, + bevelThickness: 0.1, + bevelSegments: 3, + separateMaterials: true, + depth: 0.6, + steps: 2 + }) + }, + roundedCuboid: { + label: "Rounded Cuboid", + mesh: PrimitiveMesh.createRoundedCuboid(engine, { + separateMaterials: true, + width: 2, + height: 1.6, + depth: 1.4, + cornerRadius: 0.3, + segments: 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..25f998b1e2 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, { radius: 0.5, height: 1, radialSegments: 24 }); 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..7e162c0260 --- /dev/null +++ b/e2e/case/primitive-contours.ts @@ -0,0 +1,127 @@ +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.createExtrusion(engine, polygon, { depth: 0.6 }) + }, + { + label: "Independent bevel depth", + detail: "size: 0.16 / thickness: 0.06", + mesh: PrimitiveMesh.createExtrusion(engine, polygon, { + depth: 0.6, + bevelSize: 0.16, + bevelThickness: 0.06, + bevelSegments: 4 + }) + }, + { + label: "Expanded contour", + detail: "offset: +0.15 / no bevel", + mesh: PrimitiveMesh.createExtrusion(engine, polygon, { depth: 0.6, bevelOffset: 0.15 }) + }, + { + label: "Contracted contour", + detail: "bevelOffset: -0.15", + mesh: PrimitiveMesh.createExtrusion(engine, polygon, { depth: 0.6, bevelOffset: -0.15, bevelSize: 0.08 }) + }, + { + label: "Open tube", + detail: "point array / open ends", + mesh: PrimitiveMesh.createTube(engine, path, { radius: 0.15, tubularSegments: 48, radialSegments: 12 }) + }, + { + label: "Closed tube", + detail: "closed: true / seamless join", + mesh: PrimitiveMesh.createTube(engine, loop, { + radius: 0.15, + tubularSegments: 64, + radialSegments: 12, + closed: true + }) + }, + { + label: "Open profile sweep", + detail: "path + steps: 48", + mesh: PrimitiveMesh.createExtrusion(engine, smallProfile, { path, steps: 48 }) + }, + { + label: "Closed profile sweep", + detail: "closed: true / no caps", + mesh: PrimitiveMesh.createExtrusion(engine, smallProfile, { path: loop, steps: 64, closed: true }) + }, + { + label: "Hollow profile sweep", + detail: "path + inner contour", + mesh: PrimitiveMesh.createExtrusion(engine, smallHoleProfile, { path, steps: 48 }) + } + ], + 4 + ); + } +} + +PrimitiveContours.create(); diff --git a/e2e/case/primitive-materials.ts b/e2e/case/primitive-materials.ts new file mode 100644 index 0000000000..cc03d6ff0d --- /dev/null +++ b/e2e/case/primitive-materials.ts @@ -0,0 +1,128 @@ +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", sphereOptions: { radius: 1, subdivisions: 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, { radius: 1, subdivisions: 2, keepData: 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: "separateMaterials: false", + mesh: PrimitiveMesh.createCuboid(engine), + slots: 1 + }, + { + label: "Cuboid / face materials", + detail: "+Y -Y -X +X +Z -Z", + mesh: PrimitiveMesh.createCuboid(engine, { separateMaterials: true }), + slots: 6 + }, + { + label: "Cylinder / part materials", + detail: "side / top / bottom", + mesh: PrimitiveMesh.createCylinder(engine, { height: 1.4, separateMaterials: true }), + slots: 3 + }, + { + label: "Cone / part materials", + detail: "side / bottom", + mesh: PrimitiveMesh.createCone(engine, { height: 1.4, separateMaterials: true }), + slots: 2, + rotation: new Vector3(-25, -28, 0) + }, + { + label: "Polygon / shape materials", + detail: "one slot per polygon", + mesh: PrimitiveMesh.createPolygon(engine, polygons, { separateMaterials: true }), + slots: 2, + rotation: new Vector3() + }, + { + label: "Extrusion / cap and wall", + detail: "caps / walls + bevels", + mesh: PrimitiveMesh.createExtrusion(engine, square, { depth: 0.6, bevelSize: 0.12, separateMaterials: true }), + slots: 2 + }, + { + label: "Closed / two profiles", + detail: "one wall slot per profile", + mesh: PrimitiveMesh.createExtrusion(engine, profiles, { + path: loop, + steps: 64, + closed: true, + separateMaterials: true + }), + slots: 2 + }, + { + label: "Rounded / face materials", + detail: "six material slots", + mesh: PrimitiveMesh.createRoundedCuboid(engine, { cornerRadius: 0.2, segments: 4, separateMaterials: true }), + slots: 6 + }, + { + label: "Factory / retained data", + detail: "keepData: true / readable", + mesh: retained, + slots: 1, + appearance: "checker" + }, + { + label: "JSON asset / released data", + detail: "keepData: false / same shape", + mesh: loaded, + slots: 1, + appearance: "checker" + }, + { + label: "Mirrored torus knot", + detail: "p: 2 / q: -3", + mesh: PrimitiveMesh.createTorusKnot(engine, { q: -3, tubularSegments: 96 }), + slots: 1, + appearance: "checker" + }, + { + label: "Clamped corner radius", + detail: "radius: 2 clamped to 0.5", + mesh: PrimitiveMesh.createRoundedCuboid(engine, { cornerRadius: 2, segments: 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-sections.ts b/e2e/case/primitive-sections.ts new file mode 100644 index 0000000000..b0a1df2300 --- /dev/null +++ b/e2e/case/primitive-sections.ts @@ -0,0 +1,106 @@ +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, { angleRange: new Vector2(30, 300) }), + rotation: front + }, + { + label: "Ring sector", + detail: "angleRange: [30, 300]", + mesh: PrimitiveMesh.createRing(engine, { angleRange: new Vector2(30, 300) }), + rotation: front + }, + { + label: "Torus arc", + detail: "angleRange: [30, 300]", + mesh: PrimitiveMesh.createTorus(engine, { angleRange: new Vector2(30, 300) }) + }, + { + label: "Torus cross-section", + detail: "tubeRange: [0, 180]", + mesh: PrimitiveMesh.createTorus(engine, { tubeRadius: 0.2, tubeRange: new Vector2(0, 180) }) + }, + { + label: "Both torus ranges", + detail: "arc 270 / tube 270 degrees", + mesh: PrimitiveMesh.createTorus(engine, { + tubeRadius: 0.2, + angleRange: new Vector2(30, 300), + tubeRange: new Vector2(45, 315) + }) + }, + { label: "Cylinder: both", detail: "caps: both", mesh: PrimitiveMesh.createCylinder(engine, { height: 1.4 }) }, + { + label: "Cylinder: top", + detail: "caps: top", + mesh: PrimitiveMesh.createCylinder(engine, { height: 1.4, caps: PrimitiveMeshCapMode.Top }) + }, + { + label: "Cylinder: bottom", + detail: "caps: bottom", + mesh: PrimitiveMesh.createCylinder(engine, { height: 1.4, caps: PrimitiveMeshCapMode.Bottom }), + rotation: new Vector3(-25, -28, 0) + }, + { + label: "Cylinder: open", + detail: "caps: none", + mesh: PrimitiveMesh.createCylinder(engine, { height: 1.4, caps: PrimitiveMeshCapMode.None }) + }, + { + label: "Cylinder sector", + detail: "angleRange: [30, 270]", + mesh: PrimitiveMesh.createCylinder(engine, { height: 1.4, angleRange: new Vector2(30, 270) }) + }, + { + label: "Truncated cone sector", + detail: "top 0.25 / bottom 0.6", + mesh: PrimitiveMesh.createTruncatedCone(engine, { + bottomRadius: 0.6, + height: 1.4, + angleRange: new Vector2(30, 270) + }) + }, + { + label: "Cone with cap", + detail: "cap: true", + mesh: PrimitiveMesh.createCone(engine, { height: 1.4 }), + rotation: new Vector3(-25, -28, 0) + }, + { + label: "Cone without cap", + detail: "cap: false", + mesh: PrimitiveMesh.createCone(engine, { height: 1.4, cap: false }), + rotation: new Vector3(-25, -28, 0) + }, + { + label: "Full lathe", + detail: "angleRange: [0, 360]", + mesh: PrimitiveMesh.createLathe(engine, profile, { segments: 32 }) + }, + { + label: "Partial lathe", + detail: "angleRange: [30, 270]", + mesh: PrimitiveMesh.createLathe(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..fc14807dc0 --- /dev/null +++ b/e2e/case/primitive-sphere-sections.ts @@ -0,0 +1,102 @@ +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; + horizontalRange?: Vector2; + verticalRange?: Vector2; + rotation?: Vector3; + }[] = [ + { name: "Full sphere" }, + { name: "Hemisphere", verticalRange: new Vector2(0, 90) }, + { name: "Half longitude", horizontalRange: new Vector2(90, 270) }, + { name: "Octant", horizontalRange: new Vector2(90, 180), verticalRange: new Vector2(0, 90) }, + { name: "Latitude band", verticalRange: new Vector2(50, 130) }, + { + name: "Across 360 degrees", + horizontalRange: new Vector2(330, 390), + verticalRange: new Vector2(20, 160), + rotation: new Vector3(20, 90, 0) + } + ]; + const font = Font.createFromOS(engine, "AlibabaSans"); + cases.forEach(({ name, horizontalRange, verticalRange, 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, { + horizontalRange, + verticalRange, + radius: 1, + subdivisions: 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..87b5d2f0b0 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); 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..04fa00468d --- /dev/null +++ b/e2e/case/primitive-topology.ts @@ -0,0 +1,168 @@ +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 = { keepData: true }; + const examples: PrimitiveMeshExample[] = [ + { + label: "Sphere / level 1", + detail: "subdivisions: 1", + mesh: PrimitiveMesh.createSphere(engine, { ...keep, subdivisions: 1 }) + }, + { + label: "Sphere / level 3", + detail: "subdivisions: 3", + mesh: PrimitiveMesh.createSphere(engine, { ...keep, subdivisions: 3 }) + }, + { + label: "Cylinder / 6 sides", + detail: "radialSegments: 6", + mesh: PrimitiveMesh.createCylinder(engine, { ...keep, radialSegments: 6 }) + }, + { + label: "Cylinder / 24 sides", + detail: "radial: 24 / height: 4", + mesh: PrimitiveMesh.createCylinder(engine, { ...keep, radialSegments: 24, heightSegments: 4 }) + }, + { + label: "Cone / 6 sides", + detail: "radial: 6 / height: 3", + mesh: PrimitiveMesh.createCone(engine, { ...keep, radialSegments: 6, heightSegments: 3 }) + }, + { + label: "Cuboid subdivisions", + detail: "width: 4 / height: 2 / depth: 3", + mesh: PrimitiveMesh.createCuboid(engine, { ...keep, widthSegments: 4, heightSegments: 2, depthSegments: 3 }) + }, + { + label: "Plane / 1 by 6", + detail: "horizontal: 1 / vertical: 6", + mesh: PrimitiveMesh.createPlane(engine, { ...keep, horizontalSegments: 1, verticalSegments: 6 }), + rotation: new Vector3(65, -20, 0) + }, + { + label: "Plane / 6 by 1", + detail: "horizontal: 6 / vertical: 1", + mesh: PrimitiveMesh.createPlane(engine, { ...keep, horizontalSegments: 6, verticalSegments: 1 }), + rotation: new Vector3(65, -20, 0) + }, + { + label: "Capsule / coarse caps", + detail: "radial: 8 / caps: 2 / height: 1", + mesh: PrimitiveMesh.createCapsule(engine, { ...keep, height: 1, radialSegments: 8, capSegments: 2 }) + }, + { + label: "Capsule / fine caps", + detail: "radial: 16 / caps: 8 / height: 4", + mesh: PrimitiveMesh.createCapsule(engine, { + ...keep, + height: 1, + radialSegments: 16, + capSegments: 8, + heightSegments: 4 + }) + }, + { + label: "Tetrahedron subdivision", + detail: "segments: 3", + mesh: PrimitiveMesh.createTetrahedron(engine, { ...keep, segments: 3 }) + }, + { + label: "Octahedron subdivision", + detail: "segments: 3", + mesh: PrimitiveMesh.createOctahedron(engine, { ...keep, segments: 3 }) + }, + { + label: "Icosahedron subdivision", + detail: "segments: 3", + mesh: PrimitiveMesh.createIcosahedron(engine, { ...keep, segments: 3 }) + }, + { + label: "Dodecahedron subdivision", + detail: "segments: 3", + mesh: PrimitiveMesh.createDodecahedron(engine, { ...keep, segments: 3 }) + }, + { + label: "Sphere / level 2", + detail: "subdivisions: 2", + mesh: PrimitiveMesh.createSphere(engine, { ...keep, subdivisions: 2 }) + }, + { + label: "Rounded cuboid / zero", + detail: "cornerRadius: 0", + mesh: PrimitiveMesh.createRoundedCuboid(engine, { ...keep, cornerRadius: 0 }) + }, + { + label: "Rounded cuboid / coarse", + detail: "radius: 0.2 / segments: 1", + mesh: PrimitiveMesh.createRoundedCuboid(engine, { ...keep, cornerRadius: 0.2, segments: 1 }) + }, + { + label: "Rounded cuboid / fine", + detail: "radius: 0.2 / segments: 4", + mesh: PrimitiveMesh.createRoundedCuboid(engine, { ...keep, cornerRadius: 0.2, segments: 4 }) + }, + { + label: "Torus knot / 2, 3", + detail: "p: 2 / q: 3", + mesh: PrimitiveMesh.createTorusKnot(engine, { ...keep, p: 2, q: 3, tubularSegments: 96 }) + }, + { + label: "Torus knot / 3, 2", + detail: "p: 3 / q: 2", + mesh: PrimitiveMesh.createTorusKnot(engine, { ...keep, p: 3, q: 2, tubularSegments: 96 }) + }, + { + label: "Circle / 8 segments", + detail: "segments: 8", + mesh: PrimitiveMesh.createCircle(engine, { ...keep, segments: 8 }), + rotation: new Vector3() + }, + { + label: "Ring / width subdivisions", + detail: "radial: 12 / width: 4", + mesh: PrimitiveMesh.createRing(engine, { ...keep, radialSegments: 12, widthSegments: 4 }), + rotation: new Vector3() + }, + { + label: "Lathe / 8 segments", + detail: "segments: 8", + mesh: PrimitiveMesh.createLathe(engine, [new Vector2(0.4, -1), new Vector2(0.8, 0), new Vector2(0.4, 1)], { + ...keep, + segments: 8 + }) + }, + { + label: "Tube / path subdivisions", + detail: "tubular: 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)], + { ...keep, radius: 0.2, tubularSegments: 12, radialSegments: 6 } + ) + }, + { + label: "Extrusion / bevel layers", + detail: "steps: 3 / bevelSegments: 3", + mesh: PrimitiveMesh.createExtrusion( + engine, + [new Vector2(-1, -1), new Vector2(1, -1), new Vector2(1, 1), new Vector2(-1, 1)], + { ...keep, depth: 0.6, steps: 3, bevelSize: 0.15, bevelSegments: 3 } + ) + } + ]; + gallery.show( + "Subdivision and triangle topology", + examples.map((example) => ({ ...example, wireframe: true })), + 5 + ); + } +} + +PrimitiveTopology.create(); diff --git a/e2e/case/shadow-basic.ts b/e2e/case/shadow-basic.ts index cea64a22bc..0fda95c255 100644 --- a/e2e/case/shadow-basic.ts +++ b/e2e/case/shadow-basic.ts @@ -36,7 +36,7 @@ WebGLEngine.create({ canvas: "canvas" }).then((engine) => { const planeEntity = rootEntity.createChild("plane_node"); const renderer = planeEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createPlane(engine, 10, 10); + renderer.mesh = PrimitiveMesh.createPlane(engine, { width: 10 }); const planeMaterial = new PBRMaterial(engine); renderer.setMaterial(planeMaterial); diff --git a/e2e/case/shadow-transparent.ts b/e2e/case/shadow-transparent.ts index 8b03ecb580..6e5c0549bc 100644 --- a/e2e/case/shadow-transparent.ts +++ b/e2e/case/shadow-transparent.ts @@ -42,7 +42,7 @@ WebGLEngine.create({ const planeEntity = rootEntity.createChild("plane_node"); const renderer = planeEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createPlane(engine, 10, 10); + renderer.mesh = PrimitiveMesh.createPlane(engine, { width: 10 }); const planeMaterial = new PBRMaterial(engine); renderer.setMaterial(planeMaterial); diff --git a/e2e/case/texture-R8G8.ts b/e2e/case/texture-R8G8.ts index 0bcce16c57..edbf50c4c3 100644 --- a/e2e/case/texture-R8G8.ts +++ b/e2e/case/texture-R8G8.ts @@ -32,7 +32,7 @@ WebGLEngine.create({ canvas: "canvas" }).then((engine) => { planeEntity.transform.setRotation(5, 0, 0); const planeRenderer = planeEntity.addComponent(MeshRenderer); - planeRenderer.mesh = PrimitiveMesh.createPlane(engine, 2, 2); + planeRenderer.mesh = PrimitiveMesh.createPlane(engine, { width: 2 }); planeRenderer.setMaterial(material); const width = 1024; diff --git a/e2e/case/texture-hdr.ts b/e2e/case/texture-hdr.ts index 2c9531a82b..1ff1ae2f36 100644 --- a/e2e/case/texture-hdr.ts +++ b/e2e/case/texture-hdr.ts @@ -37,7 +37,7 @@ WebGLEngine.create({ canvas: "canvas" }).then((engine) => { scene.background.mode = BackgroundMode.Sky; sky.material = skyMaterial; - sky.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); + sky.mesh = PrimitiveMesh.createCuboid(engine); skyMaterial.texture = textureCube; updateForE2E(engine); diff --git a/e2e/case/texture-sRGB-KTX2.ts b/e2e/case/texture-sRGB-KTX2.ts index 99803b82aa..d0599cc395 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); meshRenderer.setMaterial(material); updateForE2E(engine); diff --git a/e2e/config.ts b/e2e/config.ts index 077a5fc1bd..162d4dd6d4 100644 --- a/e2e/config.ts +++ b/e2e/config.ts @@ -229,6 +229,42 @@ export const E2E_CONFIG = { } }, Primitive: { + sections: { + category: "Primitive", + caseFileName: "primitive-sections", + threshold: 0, + diffPercentage: 0.02 + }, + contours: { + category: "Primitive", + caseFileName: "primitive-contours", + threshold: 0, + diffPercentage: 0.02 + }, + topology: { + category: "Primitive", + caseFileName: "primitive-topology", + threshold: 0, + diffPercentage: 0.02 + }, + materials: { + category: "Primitive", + caseFileName: "primitive-materials", + threshold: 0, + diffPercentage: 0.02 + }, + "sphere-sections": { + category: "Primitive", + caseFileName: "primitive-sphere-sections", + threshold: 0, + diffPercentage: 0.02 + }, + all: { + category: "Primitive", + caseFileName: "primitive-all", + threshold: 0, + diffPercentage: 0.02 + }, capsule: { category: "Primitive", caseFileName: "primitive-capsule", 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/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..db81641721 --- /dev/null +++ b/e2e/fixtures/originImage/Primitive_primitive-all.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b02da204a75e866639aa4fe5c99d68cb2bfcac9256abcd4a4dfd7fd2a42ca194 +size 443010 diff --git a/e2e/fixtures/originImage/Primitive_primitive-contours.jpg b/e2e/fixtures/originImage/Primitive_primitive-contours.jpg new file mode 100644 index 0000000000..47df90481b --- /dev/null +++ b/e2e/fixtures/originImage/Primitive_primitive-contours.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1032a48cfa2f180ccf7b48bb58c2254f6e2ef02f1012de69ed08f7c1b8dfd37c +size 694471 diff --git a/e2e/fixtures/originImage/Primitive_primitive-materials.jpg b/e2e/fixtures/originImage/Primitive_primitive-materials.jpg new file mode 100644 index 0000000000..11ef7cc0f5 --- /dev/null +++ b/e2e/fixtures/originImage/Primitive_primitive-materials.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0be18490ece2cc50727f2d363128b8299583cca935323d19d8350ebad5f55ece +size 525209 diff --git a/e2e/fixtures/originImage/Primitive_primitive-sections.jpg b/e2e/fixtures/originImage/Primitive_primitive-sections.jpg new file mode 100644 index 0000000000..3cd988edb3 --- /dev/null +++ b/e2e/fixtures/originImage/Primitive_primitive-sections.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ec71ec0bdc456cb7b1c842a8c637352ebb936682bb184e80212adf0e5c8fd33 +size 627848 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..5297b8cde2 --- /dev/null +++ b/e2e/fixtures/originImage/Primitive_primitive-topology.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0fa8b7ae7d6b2cd8c6ae1e80ffefc5e2623c7fb185dfd7312191688e0c80670c +size 820215 diff --git a/e2e/primitive-mesh.md b/e2e/primitive-mesh.md new file mode 100644 index 0000000000..a123737017 --- /dev/null +++ b/e2e/primitive-mesh.md @@ -0,0 +1,24 @@ +# 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 lathes | +| `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, `keepData`, 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 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/gltf-loader.ts b/examples/src/gltf-loader.ts index 40f4fac362..d0d5039025 100644 --- a/examples/src/gltf-loader.ts +++ b/examples/src/gltf-loader.ts @@ -201,7 +201,7 @@ class Oasis { this.lightEntity2.transform.setRotation(-30, 180, 0); this.scene.ambientLight.specularIntensity = this.state.envIntensity; this.scene.background.sky.material = this.skyMaterial; - this.scene.background.sky.mesh = PrimitiveMesh.createCuboid(this.engine, 1, 1, 1); + this.scene.background.sky.mesh = PrimitiveMesh.createCuboid(this.engine); this.engine.run(); } diff --git a/examples/src/gpu-instancing-auto-batch.ts b/examples/src/gpu-instancing-auto-batch.ts index ce27044161..f29b6eb070 100644 --- a/examples/src/gpu-instancing-auto-batch.ts +++ b/examples/src/gpu-instancing-auto-batch.ts @@ -157,7 +157,7 @@ WebGLEngine.create({ scene.ambientLight = ambientLight; // Cube resources - const cubeMesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); + const cubeMesh = PrimitiveMesh.createCuboid(engine); const cubeMaterial = new Material(engine, Shader.find("CustomInstanceShader")); const customColorProperty = ShaderProperty.getByName("renderer_CustomColor"); diff --git a/examples/src/gpu-instancing-custom-data.ts b/examples/src/gpu-instancing-custom-data.ts index 52b0ea89a3..94c9100170 100644 --- a/examples/src/gpu-instancing-custom-data.ts +++ b/examples/src/gpu-instancing-custom-data.ts @@ -128,7 +128,7 @@ WebGLEngine.create({ lightEntity.transform.setRotation(-45, -45, 0); lightEntity.addComponent(DirectLight).color = new Color(1, 1, 1, 1); - const mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); + const mesh = PrimitiveMesh.createCuboid(engine); const material = new Material(engine, Shader.find("CustomInstanceShader")); const customColorProperty = ShaderProperty.getByName("renderer_CustomColor"); diff --git a/examples/src/shader-01-basic-shader.ts b/examples/src/shader-01-basic-shader.ts index f92c1e9cea..66571ab2a0 100644 --- a/examples/src/shader-01-basic-shader.ts +++ b/examples/src/shader-01-basic-shader.ts @@ -80,7 +80,7 @@ function createQuad(engine: Engine): Entity { const renderer = entity.addComponent(MeshRenderer); // 使用内置的平面网格 - renderer.mesh = PrimitiveMesh.createPlane(engine, 2, 2); + renderer.mesh = PrimitiveMesh.createPlane(engine, { width: 2 }); entity.transform.setRotation(90, 0, 0); diff --git a/examples/src/shader-02-render-state.ts b/examples/src/shader-02-render-state.ts index 4a7538c064..0f2451863c 100644 --- a/examples/src/shader-02-render-state.ts +++ b/examples/src/shader-02-render-state.ts @@ -113,7 +113,7 @@ function createPlane(engine: Engine, name: string, position: Vector3): Entity { entity.transform.setRotation(90, 0, 0); const renderer = entity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createPlane(engine, 2, 2); + renderer.mesh = PrimitiveMesh.createPlane(engine, { width: 2 }); return entity; } diff --git a/examples/src/shader-03-ui-script.ts b/examples/src/shader-03-ui-script.ts index 321a3e4b75..ae581ec74f 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, { width: 3, height: 3, horizontalSegments: 20 }); // 增加细分以显示顶点动画 renderer.setMaterial(material); // 运行引擎 diff --git a/examples/src/shader-04-multi-pass.ts b/examples/src/shader-04-multi-pass.ts index 427982f394..b2b33d65ae 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, { radius: 0.8, subdivisions: 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..1d7997c837 --- /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 in double precision before converting to the GPU buffer format + const basis = new Float64Array(vertexCount * 6); + for (let i = 0; i < 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..58b0b132f5 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,12 @@ 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 tangent vectors from the mesh's positions, normals and UV coordinates. + * @remarks + * Position, normal and UV data must be readable. + * Without indices, each consecutive triplet of vertices forms a triangle. + * Triangles with degenerate UV coordinates do not contribute to the tangent basis. + * @see http://foundationsofgameenginedev.com/FGED2-sample.pdf */ calculateTangents(): void { const positions = this.getPositions()!; @@ -686,78 +684,15 @@ 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); - } + this.setTangents(MeshTangentUtils.calculateTangents(positions, normals, uvs, this._indices)); + } - // 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); + /** + * @internal + */ + _initializeTangents(tangents: Float32Array, releaseData: boolean): void { + this._updateAdvancedVertexElement(true, VertexAttribute.Tangent, VertexElementFlags.Tangent); + this._updateInternalVertexBuffer(releaseData, tangents); } /** @@ -766,23 +701,26 @@ 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 && updateInfo) { + 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(); + 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 +750,13 @@ export class ModelMesh extends Mesh { * @internal */ protected override _onDestroy(): void { + const bindings = this._primitive.vertexBufferBindings; + for (let i = 0; i < bindings.length; i++) { + const updateInfo = this._vertexBufferInfos[i]; + if (updateInfo) { + bindings[i]?.buffer._dataUpdateManager.removeListener(updateInfo.onBufferChanged); + } + } super._onDestroy(); this._releaseCache(true); } @@ -857,7 +802,7 @@ export class ModelMesh extends Mesh { this._advancedVertexDataVersions[elementIndex] = this._dataVersionCounter++; } - private _updateInternalVertexBuffer(releaseData: boolean): void { + private _updateInternalVertexBuffer(releaseData: boolean, initialData?: Float32Array): void { const bufferStride = this._internalVertexBufferStride; const vertexCount = this.vertexCount; const bufferCreatedInfo = this._internalVertexBufferCreatedInfo; @@ -868,7 +813,14 @@ export class ModelMesh extends Mesh { // Destroy old internal vertex buffer const createdInternalBufferIndex = bufferCreatedInfo.z; if (createdInternalBufferIndex !== -1) { - this._primitive.vertexBufferBindings[createdInternalBufferIndex]?.buffer.destroy(); + const buffer = this._primitive.vertexBufferBindings[createdInternalBufferIndex]?.buffer; + const tangentElement = this._primitive._vertexElementMap[VertexAttribute.Tangent]; + // Raw tangents are read lazily; preserve them before repacking the owned buffer + if (buffer?.readable && tangentElement?.bindingIndex === createdInternalBufferIndex) { + this.getTangents(); + this._advancedVertexDataVersions[VertexElementIndex.Tangent] = this._dataVersionCounter++; + } + buffer?.destroy(); this._setVertexBufferBinding(createdInternalBufferIndex, null); } @@ -876,10 +828,14 @@ export class ModelMesh extends Mesh { const isCreate = bufferStride * this.vertexCount > 0; if (isCreate) { // No matter the internal buffer is stride change or vertex count change, we need set to internal buffer again - this._advancedDataUpdateFlag |= this._internalVertexElementsFlags; + if (!initialData) { + this._advancedDataUpdateFlag |= this._internalVertexElementsFlags; + } const bufferUsage = releaseData ? BufferUsage.Static : BufferUsage.Dynamic; - const vertexBuffer = new Buffer(this._engine, BufferBindFlag.VertexBuffer, needByteLength, bufferUsage, true); + const vertexBuffer = initialData + ? new Buffer(this._engine, BufferBindFlag.VertexBuffer, initialData, bufferUsage, !releaseData) + : new Buffer(this._engine, BufferBindFlag.VertexBuffer, needByteLength, bufferUsage, true); this._setVertexBufferBinding(vertexBufferIndex, new VertexBufferBinding(vertexBuffer, bufferStride)); } bufferCreatedInfo.set(bufferStride, vertexCount, isCreate ? vertexBufferIndex : -1); @@ -946,15 +902,11 @@ export class ModelMesh extends Mesh { return vertices; } - private _updateAdvancedVertexElement( - vertices: VertexType[] | null, - attribute: VertexAttribute, - flag: VertexElementFlags - ): void { + private _updateAdvancedVertexElement(present: boolean, attribute: VertexAttribute, flag: VertexElementFlags): void { const primitive = this._primitive; const vertexElementMap = primitive._vertexElementMap; - if (vertices) { + if (present) { if (!vertexElementMap[attribute]) { const format = this._getAttributeFormat(attribute); const offset = this._internalVertexBufferStride; @@ -987,59 +939,59 @@ export class ModelMesh extends Mesh { const advancedElementUpdateFlag = this._advancedElementUpdateFlag; if (advancedElementUpdateFlag & VertexElementFlags.Position) { - this._updateAdvancedVertexElement(this._positions, VertexAttribute.Position, VertexElementFlags.Position); + this._updateAdvancedVertexElement(!!this._positions, VertexAttribute.Position, VertexElementFlags.Position); } if (advancedElementUpdateFlag & VertexElementFlags.Normal) { - this._updateAdvancedVertexElement(this._normals, VertexAttribute.Normal, VertexElementFlags.Normal); + this._updateAdvancedVertexElement(!!this._normals, VertexAttribute.Normal, VertexElementFlags.Normal); } if (advancedElementUpdateFlag & VertexElementFlags.Color) { - this._updateAdvancedVertexElement(this._colors, VertexAttribute.Color, VertexElementFlags.Color); + this._updateAdvancedVertexElement(!!this._colors, VertexAttribute.Color, VertexElementFlags.Color); } if (advancedElementUpdateFlag & VertexElementFlags.BoneWeight) { - this._updateAdvancedVertexElement(this._boneWeights, VertexAttribute.BoneWeight, VertexElementFlags.BoneWeight); + this._updateAdvancedVertexElement(!!this._boneWeights, VertexAttribute.BoneWeight, VertexElementFlags.BoneWeight); } if (advancedElementUpdateFlag & VertexElementFlags.BoneIndex) { - this._updateAdvancedVertexElement(this._boneIndices, VertexAttribute.BoneIndex, VertexElementFlags.BoneIndex); + this._updateAdvancedVertexElement(!!this._boneIndices, VertexAttribute.BoneIndex, VertexElementFlags.BoneIndex); } if (advancedElementUpdateFlag & VertexElementFlags.Tangent) { - this._updateAdvancedVertexElement(this._tangents, VertexAttribute.Tangent, VertexElementFlags.Tangent); + this._updateAdvancedVertexElement(!!this._tangents, VertexAttribute.Tangent, VertexElementFlags.Tangent); } if (advancedElementUpdateFlag & VertexElementFlags.UV) { - this._updateAdvancedVertexElement(this._uv, VertexAttribute.UV, VertexElementFlags.UV); + this._updateAdvancedVertexElement(!!this._uv, VertexAttribute.UV, VertexElementFlags.UV); } if (advancedElementUpdateFlag & VertexElementFlags.UV1) { - this._updateAdvancedVertexElement(this._uv1, VertexAttribute.UV1, VertexElementFlags.UV1); + this._updateAdvancedVertexElement(!!this._uv1, VertexAttribute.UV1, VertexElementFlags.UV1); } if (advancedElementUpdateFlag & VertexElementFlags.UV2) { - this._updateAdvancedVertexElement(this._uv2, VertexAttribute.UV2, VertexElementFlags.UV2); + this._updateAdvancedVertexElement(!!this._uv2, VertexAttribute.UV2, VertexElementFlags.UV2); } if (advancedElementUpdateFlag & VertexElementFlags.UV3) { - this._updateAdvancedVertexElement(this._uv3, VertexAttribute.UV3, VertexElementFlags.UV3); + this._updateAdvancedVertexElement(!!this._uv3, VertexAttribute.UV3, VertexElementFlags.UV3); } if (advancedElementUpdateFlag & VertexElementFlags.UV4) { - this._updateAdvancedVertexElement(this._uv4, VertexAttribute.UV4, VertexElementFlags.UV4); + this._updateAdvancedVertexElement(!!this._uv4, VertexAttribute.UV4, VertexElementFlags.UV4); } if (advancedElementUpdateFlag & VertexElementFlags.UV5) { - this._updateAdvancedVertexElement(this._uv5, VertexAttribute.UV5, VertexElementFlags.UV5); + this._updateAdvancedVertexElement(!!this._uv5, VertexAttribute.UV5, VertexElementFlags.UV5); } if (advancedElementUpdateFlag & VertexElementFlags.UV6) { - this._updateAdvancedVertexElement(this._uv6, VertexAttribute.UV6, VertexElementFlags.UV6); + this._updateAdvancedVertexElement(!!this._uv6, VertexAttribute.UV6, VertexElementFlags.UV6); } if (advancedElementUpdateFlag & VertexElementFlags.UV7) { - this._updateAdvancedVertexElement(this._uv7, VertexAttribute.UV7, VertexElementFlags.UV7); + this._updateAdvancedVertexElement(!!this._uv7, VertexAttribute.UV7, VertexElementFlags.UV7); } } @@ -1337,6 +1289,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..b943b0f632 100644 --- a/packages/core/src/mesh/PrimitiveMesh.ts +++ b/packages/core/src/mesh/PrimitiveMesh.ts @@ -1,28 +1,45 @@ -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 { MeshTangentUtils } from "./MeshTangentUtils"; +import type { + SphereMeshOptions, + CuboidMeshOptions, + PlaneMeshOptions, + CylinderMeshOptions, + TruncatedConeMeshOptions, + ConeMeshOptions, + CapsuleMeshOptions, + TorusMeshOptions, + CircleMeshOptions, + RingMeshOptions, + RegularPolyhedronMeshOptions, + LatheMeshOptions, + TubeMeshOptions, + PolygonMeshOptions, + ExtrusionMeshOptions, + 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. */ 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 +47,1745 @@ 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. + * @param engine - The engine that owns the mesh + * @param options - Shape and mesh creation settings + * @returns The generated mesh + */ + static createSphere(engine: Engine, options: SphereMeshOptions = {}): ModelMesh { + const { radius = 0.5, subdivisions = 3, horizontalRange, verticalRange } = options; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createSphereData, + [ + radius, + subdivisions, + horizontalRange?.x ?? 0, + horizontalRange?.y ?? 360, + verticalRange?.x ?? 0, + verticalRange?.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. + * @param engine - The engine that owns the mesh + * @param options - Shape and mesh creation settings + * @returns The generated mesh */ - static createSphere( - engine: Engine, - radius: number = 0.5, - segments: number = 18, - noLongerAccessible: boolean = true - ): ModelMesh { - const sphereMesh = new ModelMesh(engine); - PrimitiveMesh._setSphereData(sphereMesh, radius, segments, noLongerAccessible, false); + static createCuboid(engine: Engine, options: CuboidMeshOptions = {}): ModelMesh { + const { + width = 1, + height = width, + depth = width, + widthSegments = 1, + heightSegments = widthSegments, + depthSegments = widthSegments + } = options; + 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. + * @param engine - The engine that owns the mesh + * @param options - Shape and mesh creation settings + * @returns The generated mesh + */ + static createPlane(engine: Engine, options: PlaneMeshOptions = {}): ModelMesh { + const { width = 1, height = width, horizontalSegments = 1, verticalSegments = horizontalSegments } = options; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createPlaneData, + [width, height, horizontalSegments, verticalSegments], + 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. + * @param engine - The engine that owns the mesh + * @param options - Shape and mesh creation 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, options: CylinderMeshOptions = {}): ModelMesh { + const { + radius = 0.5, + height = 2, + radialSegments = 20, + heightSegments = 1, + caps = PrimitiveMeshCapMode.Both, + angleRange + } = options; + 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 ); - 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. + * @param engine - The engine that owns the mesh + * @param options - Shape and mesh creation settings + * @returns The generated mesh */ - static createCuboid( - engine: Engine, - width: number = 1, - height: number = 1, - depth: number = 1, - noLongerAccessible: boolean = true - ): ModelMesh { - const mesh = new ModelMesh(engine); - PrimitiveMesh._setCuboidData(mesh, width, height, depth, noLongerAccessible, false); + static createTruncatedCone(engine: Engine, options: TruncatedConeMeshOptions = {}): ModelMesh { + const { + topRadius = 0.25, + bottomRadius = 0.5, + height = 2, + radialSegments = 20, + heightSegments = 1, + caps = PrimitiveMeshCapMode.Both, + angleRange + } = options; + 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 + ); + } - 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. + * @param engine - The engine that owns the mesh + * @param options - Shape and mesh creation settings + * @returns The generated mesh + */ + static createCone(engine: Engine, options: ConeMeshOptions = {}): ModelMesh { + const { radius = 0.5, height = 2, radialSegments = 20, heightSegments = 1, cap = true, angleRange } = options; + 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. + * @param engine - The engine that owns the mesh + * @param options - Shape and mesh creation settings + * @returns The generated mesh */ - static createPlane( - engine: Engine, - width: number = 1, - height: number = 1, - horizontalSegments: number = 1, - verticalSegments: number = 1, - noLongerAccessible: boolean = true - ): 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) - ) + static createCapsule(engine: Engine, options: CapsuleMeshOptions = {}): ModelMesh { + const { radius = 0.5, height = 2, radialSegments = 6, capSegments = radialSegments, heightSegments = 1 } = options; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createCapsuleData, + [radius, height, 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. + * @param engine - The engine that owns the mesh + * @param options - Shape and mesh creation 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, options: TorusMeshOptions = {}): ModelMesh { + const { + radius = 0.5, + tubeRadius = 0.1, + tubularSegments = 30, + radialSegments = 30, + angleRange, + tubeRange + } = options; + const startAngle = angleRange?.x ?? 0; + const tubeStartAngle = tubeRange?.x ?? 0; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createTorusData, + [ + radius, + tubeRadius, + radialSegments, + tubularSegments, + (angleRange?.y ?? 360) - startAngle, + tubeStartAngle, + (tubeRange?.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. + * @param engine - The engine that owns the mesh + * @param options - Shape and mesh creation settings + * @returns The generated mesh + */ + static createCircle(engine: Engine, options: CircleMeshOptions = {}): ModelMesh { + const { radius = 0.5, segments = 32, angleRange } = options; + 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. + * @param engine - The engine that owns the mesh + * @param options - Shape and mesh creation settings + * @returns The generated mesh */ - static createTorus( - engine: Engine, - radius: number = 0.5, - tubeRadius: number = 0.1, - radialSegments: number = 30, - tubularSegments: number = 30, - arc: number = 360, - noLongerAccessible: boolean = true - ): ModelMesh { - const mesh = new ModelMesh(engine); - PrimitiveMesh._setTorusData( - mesh, - radius, - tubeRadius, - radialSegments, - tubularSegments, - arc, - noLongerAccessible, - false + static createRing(engine: Engine, options: RingMeshOptions = {}): ModelMesh { + const { + outerRadius = 0.5, + innerRadius = outerRadius / 2, + radialSegments = 32, + widthSegments = 1, + angleRange + } = options; + const startAngle = angleRange?.x ?? 0; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createRingData, + [innerRadius, outerRadius, radialSegments, widthSegments, 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) - ) + /** + * Create a regular tetrahedron or its spherical subdivision. + * @param engine - The engine that owns the mesh + * @param options - Shape and mesh creation settings + * @returns The generated mesh + */ + static createTetrahedron(engine: Engine, options: RegularPolyhedronMeshOptions = {}): ModelMesh { + const { radius = 0.5, segments = 1 } = options; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createRegularPolyhedronData, + ["tetrahedron", radius, segments], + options + ); + } + + /** + * Create a regular octahedron or its spherical subdivision. + * @param engine - The engine that owns the mesh + * @param options - Shape and mesh creation settings + * @returns The generated mesh + */ + static createOctahedron(engine: Engine, options: RegularPolyhedronMeshOptions = {}): ModelMesh { + const { radius = 0.5, segments = 1 } = options; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createRegularPolyhedronData, + ["octahedron", radius, segments], + options + ); + } + + /** + * Create a regular icosahedron or its spherical subdivision. + * @param engine - The engine that owns the mesh + * @param options - Shape and mesh creation settings + * @returns The generated mesh + */ + static createIcosahedron(engine: Engine, options: RegularPolyhedronMeshOptions = {}): ModelMesh { + const { radius = 0.5, segments = 1 } = options; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createRegularPolyhedronData, + ["icosahedron", radius, segments], + options + ); + } + + /** + * Create a regular dodecahedron or its spherical subdivision. + * @param engine - The engine that owns the mesh + * @param options - Shape and mesh creation settings + * @returns The generated mesh + */ + static createDodecahedron(engine: Engine, options: RegularPolyhedronMeshOptions = {}): ModelMesh { + const { radius = 0.5, segments = 1 } = options; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createRegularPolyhedronData, + ["dodecahedron", radius, segments], + 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 + * Revolve a radius-height profile around Y. + * @param engine - The engine that owns the mesh + * @param profile - The radius-height profile, with at least two points; X is radius and Y is height + * @param options - Shape and mesh creation settings + * @returns The generated mesh */ - static createCone( + static createLathe(engine: Engine, profile: readonly Vector2[], options: LatheMeshOptions = {}): ModelMesh { + const { segments = 12, angleRange } = options; + const startAngle = angleRange?.x ?? 0; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createLatheData, + [profile, segments, startAngle, (angleRange?.y ?? 360) - startAngle], + options + ); + } + + /** + * Sweep a circular cross-section along a path. + * @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 options - Shape and mesh creation settings + * @returns The generated mesh + */ + static createTube(engine: Engine, path: readonly Vector3[], options: TubeMeshOptions = {}): ModelMesh { + const { radius = 0.5, tubularSegments = 64, radialSegments = 8, closed = false } = options; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createTubeData, + [path, radius, tubularSegments, radialSegments, closed], + options + ); + } + + /** + * Triangulate one or more polygons in XY facing +Z. + * @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 - Shape and mesh creation settings + * @returns The generated mesh + */ + 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 polygons along +Z or a spatial path. + * @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 - Linear or path extrusion settings + * @returns The generated mesh */ - static createCapsule( + static createExtrusion( engine: Engine, - radius: number = 0.5, - height: number = 2, - radialSegments: number = 6, - heightSegments: number = 1, - noLongerAccessible: boolean = true + shapes: readonly Vector2[] | PolygonShape | readonly PolygonShape[], + options: ExtrusionMeshOptions = {} ): 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 { + depth = 1, + path, + steps = 1, + closed = false, + bevelSize = 0, + bevelThickness = bevelSize, + bevelOffset = 0, + bevelSegments = 3 + } = options; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createExtrusionData, + [ + PrimitiveMesh._polygons(shapes), + depth, + steps, + path, + closed, + bevelThickness, + bevelSize, + bevelOffset, + bevelSegments + ], + options ); - return mesh; } /** - * @internal + * Create a closed torus knot. + * @param engine - The engine that owns the mesh + * @param options - Shape and mesh creation settings + * @returns The generated mesh */ - static _setSubdivisionSurfaceSphereData( - sphereMesh: ModelMesh, + static createTorusKnot(engine: Engine, options: TorusKnotMeshOptions = {}): ModelMesh { + const { radius = 0.5, tubeRadius = 0.1, p = 2, q = 3, tubularSegments = 64, radialSegments = 8 } = options; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createTorusKnotData, + [radius, tubeRadius, tubularSegments, radialSegments, p, q], + options + ); + } + + /** + * Create an axis-aligned cuboid with rounded edges and corners. + * @remarks + * UVs preserve the cuboid's face orientations and account for rounded edge length. + * @param engine - The engine that owns the mesh + * @param options - Shape and mesh creation settings + * @returns The generated mesh + */ + static createRoundedCuboid(engine: Engine, options: RoundedCuboidMeshOptions = {}): ModelMesh { + const { width = 1, height = width, depth = width, cornerRadius = 0.1, segments = 2 } = options; + return PrimitiveMesh._createMesh( + engine, + PrimitiveMesh._createRoundedCuboidData, + [width, height, depth, cornerRadius, segments], + options + ); + } + + private static _createPlaneData( + width: number, + height: number, + horizontalSegments: number, + verticalSegments: number + ): PrimitiveMeshBuilder { + const columns = PrimitiveMesh._getSegmentCount(horizontalSegments); + const rows = PrimitiveMesh._getSegmentCount(verticalSegments); + 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) * height, 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, height / 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 + ): PrimitiveMeshBuilder { + const radial = PrimitiveMesh._getSegmentCount(radialSegments, 3); + const vertical = PrimitiveMesh._getSegmentCount(heightSegments); + const startAngle = 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); + if (includeTopCap) { + cap(radiusTop, 1); + } + if (includeBottomCap) { + cap(radiusBottom, -1); + } + 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); + // 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 cos = circle[x * 2]; + const sin = circle[x * 2 + 1]; + data.addVertex( + radius * sin, + (sign * height) / 2, + radius * cos, + 0, + sign, + 0, + (sin + 1) / 2, + (cos * sign + 1) / 2 + ); + } + for (let x = 0; x < radial; x++) { + const current = center + x + 1; + const next = full && x === radial - 1 ? center + 1 : current + 1; + if (sign > 0) { + data.addTriangle(center, current, next); + } else { + data.addTriangle(center, next, current); + } + } + data.addGroup(start); + } + } + + private static _createCapsuleData( radius: number, - step: number, - noLongerAccessible: boolean, - isRestoreMode: boolean, - restoreVertexBuffer?: Buffer + height: 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 + height; + 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 = -height / 2 + radius * ny; + distance = (y / caps) * capLength; + } else if (y <= caps + vertical) { + ringRadius = radius; + ny = 0; + py = -height / 2 + ((y - caps) / vertical) * height; + distance = capLength + ((y - caps) / vertical) * height; + } else { + const angle = (((y - caps - vertical) / caps) * Math.PI) / 2; + ringRadius = radius * Math.cos(angle); + ny = Math.sin(angle); + py = height / 2 + radius * ny; + distance = capLength + height + ((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, height / 2 + radius, radius); + return data; + } + + private static _createTorusData( + radius: number, + tubeRadius: number, + radialSegments: number, + tubularSegments: number, + arcDegrees: number, + tubeStartAngleDegrees: number, + tubeArcDegrees: number, + startAngleDegrees: number + ): PrimitiveMeshBuilder { + const radial = PrimitiveMesh._getSegmentCount(radialSegments, 3); + const tubular = PrimitiveMesh._getSegmentCount(tubularSegments, 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, + radialSegments: number, + widthSegments: number, + startAngle: number, + arcDegrees: number + ): PrimitiveMeshBuilder { + const radial = PrimitiveMesh._getSegmentCount(radialSegments, 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, + edgeSegments: 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(edgeSegments); + 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 _createLatheData( + points: readonly Vector2[], + segmentCount: number, + startAngle: number, + arcDegrees: number + ): PrimitiveMeshBuilder { + if (points.length < 2) { + throw new Error("A lathe 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, + tubularSegments: number, + radialSegments: number, + closed: boolean + ): PrimitiveMeshBuilder { + const tangents: Vector3[] = []; + const points = MeshPathUtils.sample(path, PrimitiveMesh._getSegmentCount(tubularSegments), closed, tangents); + return PrimitiveMesh._createTubeSurfaceData(points, radius, radialSegments, closed, tangents); + } + + private static _createTubeSurfaceData( + points: readonly Vector3[], + radius: number, + radialSegments: number, + closed: boolean, + fallbackTangents?: readonly Vector3[] + ): PrimitiveMeshBuilder { + const count = points.length - 1; + const radial = PrimitiveMesh._getSegmentCount(radialSegments, 3); + const frames = MeshPathUtils.computeFrames(points, closed, 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, + tubularSegments: number, + radialSegments: number, + p: number, + q: number + ): PrimitiveMeshBuilder { + if (p === 0 && q === 0) { + throw new Error("A torus knot needs at least one nonzero winding."); + } + const count = PrimitiveMesh._getSegmentCount(tubularSegments); + const points: Vector3[] = []; + const tangents: Vector3[] = []; + for (let i = 0; i < count; i++) { + const angle = (i / count) * Math.PI * 2; + const u = p * angle; + const v = q * 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 = -q * Math.sin(v); + const angularDerivative = p * (2 + Math.cos(v)); + tangents.push( + new Vector3( + radialDerivative * Math.cos(u) - angularDerivative * Math.sin(u), + radialDerivative * Math.sin(u) + angularDerivative * Math.cos(u), + q * 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); + } - 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 _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 _createExtrusionData( + shapes: readonly PolygonShape[], + depth: number, + stepCount: number, + pathInput: readonly Vector3[] | undefined, + closed: boolean, + bevelThickness: number, + bevelSize: number, + bevelOffset: number, + bevelSegmentCount: number + ): PrimitiveMeshBuilder { + const data = new PrimitiveMeshBuilder(); + const steps = PrimitiveMesh._getSegmentCount(stepCount, closed ? 3 : 1); + const tangents: Vector3[] = []; + const path = pathInput ? MeshPathUtils.sample(pathInput, steps, closed, tangents) : undefined; + const frames = path ? MeshPathUtils.computeFrames(path, closed, tangents) : undefined; + const bevelEnabled = !path && bevelSize > 0; + const bevelSegments = bevelEnabled ? PrimitiveMesh._getSegmentCount(bevelSegmentCount) : 0; + const thickness = bevelEnabled ? Math.min(bevelThickness, depth / 2) : 0; + const size = bevelEnabled ? bevelSize : 0; + const offset = path ? 0 : bevelOffset; + 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 (!closed) { + 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; + } + + 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, + subdivisions: 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, subdivisions); + return PrimitiveMesh._createSphereSectionData( + surface, + radius, + horizontalStart, + horizontalArc, + verticalStart, + verticalEnd + ); + } + + const data = PrimitiveMesh._createSphereSurfaceData(radius, subdivisions); + 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, subdivisions: number): PrimitiveMeshBuilder { + // Level 7 exceeds the 16-bit vertex index range + const level = MathUtil.clamp(Math.floor(subdivisions), 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 +1810,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 +1831,181 @@ 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); - } - - /** - * @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; - } - } - } + const data = new PrimitiveMeshBuilder(); + data.setData(vertices, indices); + data.boundsExtent = new Vector3(radius, radius, radius); + return data; } - /** - * 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, + { keepData = false, separateMaterials = false }: { keepData?: boolean; separateMaterials?: boolean } + ): ModelMesh { + 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; - } - - if (!isRestoreMode) { - const { bounds } = planeMesh; - bounds.min.set(-halfWidth, 0, -halfHeight); - bounds.max.set(halfWidth, 0, halfHeight); + 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, keepData); + mesh.setVertexBufferBinding(vertexBuffer, 32, 0); + mesh._initializeTangents(MeshTangentUtils.calculateTangentsFromBuffer(vertices, indices), !keepData); + mesh.setIndices(indices); + PrimitiveMesh._setBounds(mesh, data); + mesh.uploadData(!keepData); + mesh.clearSubMesh(); + if (separateMaterials && 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); - } - - /** - * @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); + mesh.bounds.min.set(minX, minY, minZ); + mesh.bounds.max.set(maxX, maxY, maxZ); } - /** - * @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..e9dc7243ef --- /dev/null +++ b/packages/core/src/mesh/PrimitiveMeshOptions.ts @@ -0,0 +1,627 @@ +import type { Vector2, Vector3 } from "@galacean/engine-math"; +import type { PrimitiveMeshCapMode } from "./enums/PrimitiveMeshCapMode"; + +/** + * Settings shared by all primitive meshes. + */ +export interface PrimitiveMeshOptions { + /** + * Whether to retain readable CPU copies of vertex attributes and indices after upload. + * @defaultValue `false` + */ + keepData?: 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 radius in local units. + * @defaultValue `0.5` + */ + radius?: number; + /** + * The subdivision level, rounded down and clamped to 1 through 6. + * @defaultValue `3` + */ + subdivisions?: 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)` + */ + horizontalRange?: 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)` + */ + verticalRange?: Vector2; +} + +/** + * Settings for an axis-aligned cuboid centered at the origin. + */ +export interface CuboidMeshOptions extends PrimitiveMeshOptions { + /** + * The full size along X in local units. + * @defaultValue `1` + */ + width?: number; + /** + * The full size along Y in local units. + * @defaultValue The value of `width`. + */ + height?: number; + /** + * The full size along Z in local units. + * @defaultValue The value of `width`. + */ + depth?: number; + /** + * 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` + */ + separateMaterials?: boolean; +} + +/** + * Settings for a plane in XZ facing +Y, centered at the origin. + */ +export interface PlaneMeshOptions extends PrimitiveMeshOptions { + /** + * The full size along X in local units. + * @defaultValue `1` + */ + width?: number; + /** + * The full size along Z in local units. + * @defaultValue The value of `width`. + */ + height?: number; + /** + * The number of subdivisions along X, rounded down with a minimum of 1. + * @defaultValue `1` + */ + horizontalSegments?: number; + /** + * The number of subdivisions along Z, rounded down with a minimum of 1. + * @defaultValue The value of `horizontalSegments`. + */ + verticalSegments?: number; +} + +/** + * Settings for a cylinder centered on Y with equal end radii. + */ +export interface CylinderMeshOptions extends PrimitiveMeshOptions { + /** + * The radius in local units. + * @defaultValue `0.5` + */ + radius?: number; + /** + * The full size along Y in local units. + * @defaultValue `2` + */ + height?: number; + /** + * 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` + */ + separateMaterials?: boolean; +} + +/** + * Settings for a truncated cone centered on Y with independently sized ends. + */ +export interface TruncatedConeMeshOptions extends PrimitiveMeshOptions { + /** + * The top radius in local units. + * @defaultValue `0.25` + */ + topRadius?: number; + /** + * The bottom radius in local units. + * @defaultValue `0.5` + */ + bottomRadius?: number; + /** + * The full size along Y in local units. + * @defaultValue `2` + */ + height?: number; + /** + * 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` + */ + separateMaterials?: boolean; +} + +/** + * Settings for a cone centered on Y with its tip at the top. + */ +export interface ConeMeshOptions extends PrimitiveMeshOptions { + /** + * The bottom radius in local units. + * @defaultValue `0.5` + */ + radius?: number; + /** + * The full size along Y in local units. + * @defaultValue `2` + */ + height?: number; + /** + * 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` + */ + separateMaterials?: boolean; +} + +/** + * Settings for a capsule centered on Y. + */ +export interface CapsuleMeshOptions extends PrimitiveMeshOptions { + /** + * The radius of the cylinder and hemispherical ends in local units. + * @defaultValue `0.5` + */ + radius?: number; + /** + * The straight cylindrical section's height in local units. Total height is `height + 2 * radius`. + * @defaultValue `2` + */ + height?: number; + /** + * 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 distance from the origin to the tube centerline in local units. + * @defaultValue `0.5` + */ + radius?: number; + /** + * The radius of the tube cross-section in local units. + * @defaultValue `0.1` + */ + tubeRadius?: number; + /** + * The number of segments around the torus, rounded down with a minimum of 1. + * @defaultValue `30` + */ + tubularSegments?: 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)` + */ + angleRange?: 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)` + */ + tubeRange?: Vector2; +} + +/** + * Settings for a filled disk or sector in XY facing +Z. + */ +export interface CircleMeshOptions extends PrimitiveMeshOptions { + /** + * The radius in local units. + * @defaultValue `0.5` + */ + radius?: number; + /** + * 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 outer radius in local units. + * @defaultValue `0.5` + */ + outerRadius?: number; + /** + * The inner radius in local units. + * @defaultValue Half of `outerRadius`. + */ + innerRadius?: number; + /** + * The number of segments along the arc, rounded down with a minimum of 3. + * @defaultValue `32` + */ + radialSegments?: 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 distance from the origin to each vertex in local units. + * @defaultValue `0.5` + */ + radius?: number; + /** + * 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` + */ + segments?: number; +} + +/** + * Settings for revolving a radius-height profile around Y. + */ +export interface LatheMeshOptions 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 radius of the cross-section in local units. + * @defaultValue `0.5` + */ + radius?: number; + /** + * The number of segments along the resampled path, rounded down with a minimum of 1. + * @defaultValue `64` + */ + tubularSegments?: 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` + */ + closed?: boolean; +} + +/** + * Settings for triangulating polygons 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` + */ + separateMaterials?: boolean; +} + +/** + * Settings for extruding polygons along +Z. + */ +export interface LinearExtrusionMeshOptions extends PrimitiveMeshOptions { + /** + * The total extrusion depth in local units, including both bevels. + * @defaultValue `1` + */ + depth?: number; + /** + * The number of subdivisions along the extrusion, rounded down with a minimum of 1. + * @defaultValue `1` + */ + steps?: number; + /** + * The inset of each end cap relative to the side wall in local units. Zero disables bevels. + * @defaultValue `0` + */ + bevelSize?: number; + /** + * The bevel depth at each end in local units, limited to half of `depth`. + * @defaultValue The value of `bevelSize`. + */ + bevelThickness?: 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` + */ + bevelOffset?: 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` + */ + separateMaterials?: boolean; + /** + * A path selects path extrusion, which cannot be combined with depth or bevel settings. + */ + path?: never; + /** + * Closing is only available for path extrusion. + */ + closed?: never; +} + +/** + * Settings for extruding polygons along a polyline, without bevels. + * Polygon X and Y coordinates become offsets along the moving cross-section's axes. + */ +export interface PathExtrusionMeshOptions extends PrimitiveMeshOptions { + /** + * The path points, resampled at equal distances along the polyline. At least two distinct points are required. + */ + path: readonly Vector3[]; + /** + * 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 `closed` is true. + */ + steps?: number; + /** + * Whether to join the path ends with matching cross-sections and omit end caps. + * The closing point need not be repeated. + * @defaultValue `false` + */ + closed?: 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` + */ + separateMaterials?: boolean; + /** + * Depth is determined by the path. + */ + depth?: never; + /** + * Path extrusion does not support bevels. + */ + bevelSize?: never; + /** + * Path extrusion does not support bevels. + */ + bevelThickness?: never; + /** + * Path extrusion does not support contour offsets. + */ + bevelOffset?: never; + /** + * Path extrusion does not support bevels. + */ + bevelSegments?: never; +} + +/** + * Settings for linear extrusion or path extrusion. Providing `path` selects path extrusion. + */ +export type ExtrusionMeshOptions = LinearExtrusionMeshOptions | PathExtrusionMeshOptions; + +/** + * Settings for a closed torus knot. At least one of `p` and `q` must be nonzero. + */ +export interface TorusKnotMeshOptions extends PrimitiveMeshOptions { + /** + * The base radius of the torus in local units. + * @defaultValue `0.5` + */ + radius?: number; + /** + * The radius of the tube cross-section in local units. + * @defaultValue `0.1` + */ + tubeRadius?: number; + /** + * The signed integer revolution count around the torus axis. Negative values reverse the winding. + * @defaultValue `2` + */ + p?: number; + /** + * The signed integer revolution count through the torus hole. Negative values reverse the winding. + * @defaultValue `3` + */ + q?: number; + /** + * The number of segments along the knot, rounded down with a minimum of 1. + * @defaultValue `64` + */ + tubularSegments?: 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 full size along X in local units. + * @defaultValue `1` + */ + width?: number; + /** + * The full size along Y in local units. + * @defaultValue The value of `width`. + */ + height?: number; + /** + * The full size along Z in local units. + * @defaultValue The value of `width`. + */ + depth?: number; + /** + * The edge and corner radius in local units, clamped between zero and half the smallest dimension. + * @defaultValue `0.1` + */ + cornerRadius?: number; + /** + * The rounding subdivision count, rounded down with a minimum of 1. + * When `cornerRadius` is positive, each face uses `2 * segments + 1` subdivisions per axis. + * @defaultValue `2` + */ + segments?: number; + /** + * Whether to create one sub-mesh per face, ordered +Y, -Y, -X, +X, +Z, -Z. + * @defaultValue `false` + */ + separateMaterials?: 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..7329a57fc7 100644 --- a/packages/core/src/mesh/index.ts +++ b/packages/core/src/mesh/index.ts @@ -4,6 +4,30 @@ 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, + LatheMeshOptions, + TubeMeshOptions, + PolygonMeshOptions, + ExtrusionMeshOptions, + TorusKnotMeshOptions, + RoundedCuboidMeshOptions, + PolygonShape, + LinearExtrusionMeshOptions, + PathExtrusionMeshOptions +} 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..830dcf1c82 --- /dev/null +++ b/packages/core/src/mesh/primitive/PolygonUtils.ts @@ -0,0 +1,741 @@ +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); + } + points.push(...contours[i]); + } + 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 && + p.next.y !== p.y && + 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..b5fbe3949b --- /dev/null +++ b/packages/core/src/mesh/primitive/PrimitiveMeshRestorer.ts @@ -0,0 +1,67 @@ +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 vertexBuffer = this._vertexBuffer; + const indices = mesh.accessible ? mesh.getIndices() : null; + let generated: PrimitiveMeshBuilder | undefined; + // Only regenerate owned buffers; readable data includes changes made after creation + for (const binding of mesh.vertexBufferBindings) { + const buffer = binding?.buffer; + if (!buffer) { + continue; + } + if (buffer.readable) { + buffer.setData(buffer.data!); + } else if (buffer === vertexBuffer) { + generated ??= this._generateData(); + buffer.setData(generated.vertices); + } else if (buffer === this._tangentBuffer) { + generated ??= this._generateData(); + const vertexData = vertexBuffer.readable ? vertexBuffer.data : null; + const vertices = vertexData + ? new Float32Array(vertexData.buffer, vertexData.byteOffset, vertexBuffer.byteLength / 4) + : generated.vertices; + buffer.setData(MeshTangentUtils.calculateTangentsFromBuffer(vertices, indices ?? generated.indices)); + } + } + const indexBuffer = mesh._primitive.indexBufferBinding?._buffer; + if (indexBuffer) { + if (indices) { + indexBuffer.setData(indices); + } else if (indexBuffer === this._indexBuffer) { + generated ??= this._generateData(); + indexBuffer.setData(generated.indices); + } + } + } + + private _generateData(): PrimitiveMeshBuilder { + const data = this._generate(...this._args); + data.trim(); + return data; + } +} 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/README.md b/packages/galacean/README.md index 8551c2785b..216cea0a5f 100644 --- a/packages/galacean/README.md +++ b/packages/galacean/README.md @@ -62,7 +62,7 @@ const meshEntity = rootEntity.createChild("Sphere"); const meshRenderer = meshEntity.addComponent(MeshRenderer); const material = new BlinnPhongMaterial(engine); meshRenderer.setMaterial(material); -meshRenderer.mesh = PrimitiveMesh.createSphere(engine, 1); +meshRenderer.mesh = PrimitiveMesh.createSphere(engine, { radius: 1 }); // Run engine engine.run(); diff --git a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md index 51face621a..9a5868478d 100644 --- a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md +++ b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md @@ -2,18 +2,17 @@ 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). -The table describes meshes created with omitted size arguments and an entity scale of `(1, 1, 1)`. - -| 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 | +The table describes meshes created with default options and an entity scale of `(1, 1, 1)`. + +| Primitive | Default extent | Local orientation | +| --------- | ------------------------------------------------ | ---------------------------- | +| Cuboid | width 1, height 1, depth 1 | centered at the origin | +| 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 | ## Placement consequences @@ -28,7 +27,7 @@ Primitive meshes and collider shapes own independent dimensions. Their defaults Set collider dimensions from the intended collision geometry. Do not infer them from the assigned mesh or assume entity scale repairs a default mismatch. -Exact constructor arguments remain declaration-owned. Use this page only for the default spatial semantics that are easy to misremember. +Exact option fields and defaults remain declaration-owned. Use this page only for the default spatial semantics that are easy to misremember. ## Draw-ready custom mesh @@ -49,3 +48,35 @@ export function createTriangle(engine: Engine, renderer: MeshRenderer): void { renderer.mesh = mesh; } ``` + +## Procedural generators + +Each factory accepts one named options object, with dimensions, subdivision counts and mesh settings in that object. Every shape has a public options type, such as `SphereMeshOptions`; the four regular polyhedra share `RegularPolyhedronMeshOptions`. Query the factory and its options type for fields, units and defaults. + +For example, `createSphere(engine, { radius: 1, subdivisions: 3 })` sets radius and subdivision level. `createCuboid(engine, { width: 2 })` creates a cube with all dimensions equal to 2; omitted plane height likewise uses its width. Later plane/cuboid subdivision counts use the first direction by default. + +`createCylinder(engine, { radius, height })` creates equal end radii. Use `createTruncatedCone(engine, { topRadius, bottomRadius, height })` for different radii. Tubes take a required `Vector3` path followed by `TubeMeshOptions`; lathe profiles take a required `Vector2` array followed by `LatheMeshOptions`. + +Torus-knot `p` and `q` are signed integer revolution counts, independent of mesh subdivisions. Negative values reverse the corresponding winding direction; zero keeps that angle fixed. + +Angles use degrees. Ranges use `Vector2`, with `x` as the start angle and `y` as the end angle, such as `new Vector2(30, 180)`. Spherical sections use `horizontalRange` and `verticalRange` in their options. Cylinder and frustum `caps` use the exported `PrimitiveMeshCapMode` enum: `Both` (default), `Top`, `Bottom`, `None`. Top faces +Y and bottom faces -Y; angular cut boundaries remain open. Cones use a boolean `cap`. Plane is in XZ facing +Y; circles, rings and polygons are in XY facing +Z. Capsule height excludes its hemispheres. + +`createSphere(engine, { radius, subdivisions, horizontalRange, verticalRange })` projects a subdivided cube onto a sphere. The subdivision level defaults to 3 and is clamped to 1 through 6. It accepts `horizontalRange` and `verticalRange`. These clip the subdivided surface and leave open boundaries. Horizontal angles start at -X towards +Z, and vertical angles start at +Y. Continuous horizontal intervals such as `new Vector2(350, 370)` cross the seam. Complete spheres and sections use the same subdivision level. + +Additional generators include circle, ring, four regular polyhedra, lathe, tube, polygon, extrusion, torus knot and rounded cuboid. Angle ranges belong to options. A ring's omitted `innerRadius` is half its `outerRadius`. Contours and lathe profiles use `Vector2` arrays; paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points outside the mesh API. A simple polygon is a point array; holes use `{ points, holes }`. Extrusion takes `LinearExtrusionMeshOptions` with optional `depth`, or `PathExtrusionMeshOptions` with a required `path`. These types reject combining paths with depth or bevel settings, including through variables. Straight extrusion defaults to no bevel; a positive `bevelSize` enables it, with `bevelThickness` defaulting to the same value. Path extrusion has no bevels. + +For straight extrusion, `bevelOffset` shifts the side-wall outline and defaults to `0`. Positive values expand the solid and contract holes; negative values do the reverse. The offset also applies when `bevelSize` is `0`. Bevels are cut into the shifted outline and included in the total `depth`. + +For tubes and path extrusions, `closed` defaults to `false`. When enabled, the path ends join with matching cross-sections, and the closing point need not be repeated. Closed extrusions use at least three steps and have no end caps. Open extrusions have both end caps; tubes have no end caps in either mode. + +Mesh settings share the same options object. `keepData` retains readable CPU attributes and defaults to false. `separateMaterials` defaults to false and is only available for cuboids, cylinders, truncated cones, cones, polygons, extrusions and rounded cuboids. With it enabled, cuboid slots follow +Y, -Y, -X, +X, +Z, -Z; cylinders use side, top, bottom; cones use side, bottom. Disabled or zero-radius caps do not reserve slots. Polygon slots follow shape order, with holes sharing the outer contour's slot. Each open extrusion shape contributes two consecutive slots: both caps, then all walls and bevels. Closed path extrusions contribute one wall slot per shape. Rebuilding a mesh with different parts requires matching the material array to its new slot order. Input values are captured at creation for deterministic device restoration. + +## Serializable primitive assets + +`PrimitiveMeshAsset` is exported from `@galacean/engine` and `@galacean/engine-loader` and covers every `PrimitiveMesh.createX` method. Each asset `type` uses the matching lower-camel name: `sphere`, `cuboid`, `plane`, `cylinder`, `truncatedCone`, `cone`, `capsule`, `torus`, `circle`, `ring`, `tetrahedron`, `octahedron`, `icosahedron`, `dodecahedron`, `lathe`, `tube`, `polygon`, `extrusion`, `torusKnot`, `roundedCuboid`. + +JSON keeps the type prefix for geometry inputs and the options object: `{ type: "sphere", sphereOptions: { radius: 1, subdivisions: 3, keepData: true } }`. Each `Options` uses the factory's named configuration fields and omitted defaults. Angular ranges store `Vector2` components as `{ x, y }`, for example `{ type: "circle", circleOptions: { angleRange: { x: 30, y: 180 } } }`. `sphere` uses the subdivided-cube algorithm; `sphereOptions.subdivisions` sets its subdivision level. `cylinderOptions.radius` controls both end radii; unequal radii use `truncatedConeOptions.topRadius` and `truncatedConeOptions.bottomRadius`. + +TypeScript assets use `PrimitiveMeshCapMode` for `caps`; JSON stores its string values `"both"`, `"top"`, `"bottom"`, `"none"`. + +Serialized profiles and contours use `{ x, y }`; paths use `{ x, y, z }`. `polygonShapes` and `extrusionShapes` are arrays of `{ points, holes? }`. Straight extrusion uses `extrusionOptions.depth`; path extrusion uses `extrusionOptions.path` and has no bevel options. Set `extrusionOptions.closed` to `true` for a closed path without end caps. Editor previews and saved assets must select the same factory and parameters. diff --git a/packages/loader/src/PrimitiveMeshAsset.ts b/packages/loader/src/PrimitiveMeshAsset.ts new file mode 100644 index 0000000000..dc914ba9bc --- /dev/null +++ b/packages/loader/src/PrimitiveMeshAsset.ts @@ -0,0 +1,125 @@ +import type { + CapsuleMeshOptions, + CircleMeshOptions, + ConeMeshOptions, + CuboidMeshOptions, + CylinderMeshOptions, + LatheMeshOptions, + LinearExtrusionMeshOptions, + PathExtrusionMeshOptions, + PlaneMeshOptions, + PolygonMeshOptions, + RegularPolyhedronMeshOptions, + RingMeshOptions, + RoundedCuboidMeshOptions, + SphereMeshOptions, + TorusKnotMeshOptions, + TorusMeshOptions, + TruncatedConeMeshOptions, + TubeMeshOptions +} from "@galacean/engine-core"; +import type { Vector2 } from "@galacean/engine-math"; + +/** + * @internal + */ +export type SerializedPrimitiveMeshOptions = { + [Key in keyof T]: Extract extends never ? T[Key] : { x: number; y: number }; +}; + +type SerializedPolygonShape = { + points: readonly { x: number; y: number }[]; + holes?: readonly (readonly { x: number; y: number }[])[]; +}; + +/** + * Serialized data for every primitive mesh factory, using the same option defaults and constraints. + * Vector inputs store their components as plain JSON objects. + */ +export type PrimitiveMeshAsset = + | { + type: "sphere"; + sphereOptions?: SerializedPrimitiveMeshOptions; + } + | { + type: "cuboid"; + cuboidOptions?: CuboidMeshOptions; + } + | { + type: "plane"; + planeOptions?: PlaneMeshOptions; + } + | { + type: "cylinder"; + cylinderOptions?: SerializedPrimitiveMeshOptions; + } + | { + type: "truncatedCone"; + truncatedConeOptions?: SerializedPrimitiveMeshOptions; + } + | { + type: "cone"; + coneOptions?: SerializedPrimitiveMeshOptions; + } + | { + type: "capsule"; + capsuleOptions?: CapsuleMeshOptions; + } + | { + type: "torus"; + torusOptions?: SerializedPrimitiveMeshOptions; + } + | { + type: "circle"; + circleOptions?: SerializedPrimitiveMeshOptions; + } + | { + type: "ring"; + ringOptions?: SerializedPrimitiveMeshOptions; + } + | { + type: "tetrahedron"; + tetrahedronOptions?: RegularPolyhedronMeshOptions; + } + | { + type: "octahedron"; + octahedronOptions?: RegularPolyhedronMeshOptions; + } + | { + type: "icosahedron"; + icosahedronOptions?: RegularPolyhedronMeshOptions; + } + | { + type: "dodecahedron"; + dodecahedronOptions?: RegularPolyhedronMeshOptions; + } + | { + type: "lathe"; + latheProfile: readonly { x: number; y: number }[]; + latheOptions?: SerializedPrimitiveMeshOptions; + } + | { + type: "tube"; + tubePath: readonly { x: number; y: number; z: number }[]; + tubeOptions?: TubeMeshOptions; + } + | { + type: "polygon"; + polygonShapes: readonly SerializedPolygonShape[]; + polygonOptions?: PolygonMeshOptions; + } + | { + type: "extrusion"; + extrusionShapes: readonly SerializedPolygonShape[]; + extrusionOptions?: + | LinearExtrusionMeshOptions + | (Omit & { path: readonly { x: number; y: number; z: number }[] }); + } + | { + type: "torusKnot"; + torusKnotOptions?: TorusKnotMeshOptions; + } + | { + type: "roundedCuboid"; + roundedCuboidOptions?: RoundedCuboidMeshOptions; + }; diff --git a/packages/loader/src/PrimitiveMeshLoader.ts b/packages/loader/src/PrimitiveMeshLoader.ts index 4f98fa25b5..25b7bb4b46 100644 --- a/packages/loader/src/PrimitiveMeshLoader.ts +++ b/packages/loader/src/PrimitiveMeshLoader.ts @@ -1,115 +1,114 @@ 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, SerializedPrimitiveMeshOptions } 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)); } -} -/** @internal */ -enum PrimitiveMeshType { - Sphere = "sphere", - Cuboid = "cuboid", - Plane = "plane", - Cylinder = "cylinder", - Torus = "torus", - Cone = "cone", - Capsule = "capsule" -} + private _createPrimitiveMesh(engine: Engine, data: PrimitiveMeshAsset): ModelMesh { + const { type } = data; + switch (type) { + case "sphere": + return PrimitiveMesh.createSphere(engine, this._parseRangeOptions(data.sphereOptions)); + case "cuboid": + return PrimitiveMesh.createCuboid(engine, data.cuboidOptions); + case "plane": + return PrimitiveMesh.createPlane(engine, data.planeOptions); + case "cylinder": + return PrimitiveMesh.createCylinder(engine, this._parseRangeOptions(data.cylinderOptions)); + case "truncatedCone": + return PrimitiveMesh.createTruncatedCone(engine, this._parseRangeOptions(data.truncatedConeOptions)); + case "cone": + return PrimitiveMesh.createCone(engine, this._parseRangeOptions(data.coneOptions)); + case "capsule": + return PrimitiveMesh.createCapsule(engine, data.capsuleOptions); + case "torus": + return PrimitiveMesh.createTorus(engine, this._parseRangeOptions(data.torusOptions)); + case "circle": + return PrimitiveMesh.createCircle(engine, this._parseRangeOptions(data.circleOptions)); + case "ring": + return PrimitiveMesh.createRing(engine, this._parseRangeOptions(data.ringOptions)); + case "tetrahedron": + return PrimitiveMesh.createTetrahedron(engine, data.tetrahedronOptions); + case "octahedron": + return PrimitiveMesh.createOctahedron(engine, data.octahedronOptions); + case "icosahedron": + return PrimitiveMesh.createIcosahedron(engine, data.icosahedronOptions); + case "dodecahedron": + return PrimitiveMesh.createDodecahedron(engine, data.dodecahedronOptions); + case "lathe": + return PrimitiveMesh.createLathe( + engine, + this._parseVector2s(data.latheProfile), + this._parseRangeOptions(data.latheOptions) + ); + case "tube": + return PrimitiveMesh.createTube(engine, this._parseVector3s(data.tubePath), data.tubeOptions); + case "polygon": + return PrimitiveMesh.createPolygon(engine, this._parseShapes(data.polygonShapes), data.polygonOptions); + case "extrusion": { + const shapes = this._parseShapes(data.extrusionShapes); + const options = data.extrusionOptions; + return PrimitiveMesh.createExtrusion( + engine, + shapes, + options?.path ? { ...options, path: this._parseVector3s(options.path) } : options + ); + } + case "torusKnot": + return PrimitiveMesh.createTorusKnot(engine, data.torusKnotOptions); + case "roundedCuboid": + return PrimitiveMesh.createRoundedCuboid(engine, data.roundedCuboidOptions); + default: { + const unsupportedType: never = type; + throw new Error(`Unknown primitive mesh type: ${unsupportedType}`); + } + } + } -/** @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 _parseRangeOptions(options: SerializedPrimitiveMeshOptions | undefined): T | undefined { + if (!options) { + return; + } + const result = { ...options } as T; + for (const key in options) { + const value: unknown = options[key]; + if (value && typeof value === "object") { + const range = value as { x: number; y: number }; + result[key] = new Vector2(range.x, range.y) as T[typeof key]; + } + } + return result; + } + + private _parseVector2s(points: readonly { x: number; y: number }[]): Vector2[] { + return points.map(({ x, y }) => new Vector2(x, y)); + } + + private _parseVector3s(points: readonly { x: number; y: number; z: number }[]): Vector3[] { + return points.map(({ x, y, z }) => new Vector3(x, y, z)); + } + + private _parseShapes(shapes: Extract["polygonShapes"]): 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..46ae5c221e --- /dev/null +++ b/tests/package-consumer/PrimitiveMeshApi.test.ts @@ -0,0 +1,89 @@ +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, `Expected one call signature: ${factory.name}`).toHaveLength(1); + const examples = calls.filter( + (call) => ts.isPropertyAccessExpression(call.expression) && call.expression.name.text === factory.name + ); + for (const signature of signatures) { + expect( + examples.some((call) => checker.getResolvedSignature(call)?.getDeclaration() === signature.getDeclaration()), + `Missing overload example: ${factory.name}${checker.signatureToString(signature)}` + ).toBe(true); + + const optionsIndex = signature.getParameters().findIndex((parameter) => parameter.name === "options"); + const optionsType = checker.getNonNullableType( + checker.getTypeOfSymbolAtLocation(signature.getParameters()[optionsIndex], source) + ); + const documentedFields = new Set( + examples.flatMap((call) => { + const options = call.arguments[optionsIndex]; + return options + ? checker + .getTypeAtLocation(options) + .getProperties() + .map((field) => field.name) + : []; + }) + ); + for (const field of optionsType.getProperties()) { + expect(documentedFields.has(field.name), `Missing option example: ${factory.name}.${field.name}`).toBe(true); + } + } + + const parameters = signatures.map((signature) => signature.getDeclaration()!.parameters); + const minimum = Math.min( + ...parameters.map( + (list) => list.filter((parameter) => !parameter.questionToken && !parameter.initializer).length + ) + ); + const maximum = Math.max(...parameters.map((list) => list.length)); + for (let count = minimum; count <= maximum; count++) { + expect( + examples.some((call) => call.arguments.length === count), + `Missing optional-argument example: ${factory.name} 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..6bae877870 --- /dev/null +++ b/tests/package-consumer/fixtures/PrimitiveMeshApi.ts @@ -0,0 +1,315 @@ +import { Engine, ModelMesh, PolygonShape, PrimitiveMesh, PrimitiveMeshCapMode } from "../../../packages/core/types"; +import type { + CapsuleMeshOptions, + CircleMeshOptions, + ConeMeshOptions, + CuboidMeshOptions, + CylinderMeshOptions, + ExtrusionMeshOptions, + LatheMeshOptions, + LinearExtrusionMeshOptions, + PathExtrusionMeshOptions, + PlaneMeshOptions, + PolygonMeshOptions, + PrimitiveMeshOptions, + RegularPolyhedronMeshOptions, + 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 = { keepData: true } satisfies PrimitiveMeshOptions; +const sphereOptions = { + radius: 1, + subdivisions: 4, + horizontalRange: new Vector2(350, 370), + verticalRange: new Vector2(30, 150), + keepData: true +} satisfies SphereMeshOptions; +const cuboidOptions = { + width: 2, + height: 3, + depth: 4, + widthSegments: 2, + heightSegments: 3, + depthSegments: 4, + separateMaterials: true, + keepData: true +} satisfies CuboidMeshOptions; +const planeOptions = { + width: 10, + height: 5, + horizontalSegments: 4, + verticalSegments: 2, + keepData: true +} satisfies PlaneMeshOptions; +const cylinderOptions = { + radius: 1, + height: 2, + radialSegments: 32, + heightSegments: 4, + caps: PrimitiveMeshCapMode.Bottom, + angleRange: new Vector2(0, 270), + separateMaterials: true, + keepData: true +} satisfies CylinderMeshOptions; +const truncatedConeOptions = { + topRadius: 0.5, + bottomRadius: 1, + height: 2, + radialSegments: 32, + heightSegments: 4, + caps: PrimitiveMeshCapMode.None, + angleRange: new Vector2(0, 270), + separateMaterials: true, + keepData: true +} satisfies TruncatedConeMeshOptions; +const coneOptions = { + radius: 1, + height: 2, + radialSegments: 32, + heightSegments: 4, + cap: false, + angleRange: new Vector2(0, 270), + separateMaterials: true, + keepData: true +} satisfies ConeMeshOptions; +const capsuleOptions = { + radius: 0.5, + height: 2, + radialSegments: 12, + capSegments: 6, + heightSegments: 3, + keepData: true +} satisfies CapsuleMeshOptions; +const torusOptions = { + radius: 1, + tubeRadius: 0.2, + tubularSegments: 64, + radialSegments: 16, + angleRange: new Vector2(0, 270), + tubeRange: new Vector2(0, 180), + keepData: true +} satisfies TorusMeshOptions; +const circleOptions = { + radius: 1, + segments: 32, + angleRange: new Vector2(0, 180), + keepData: true +} satisfies CircleMeshOptions; +const ringOptions = { + outerRadius: 1, + innerRadius: 0.5, + radialSegments: 32, + widthSegments: 4, + angleRange: new Vector2(0, 270), + keepData: true +} satisfies RingMeshOptions; +const regularPolyhedronOptions = { radius: 1, segments: 2, keepData: true } satisfies RegularPolyhedronMeshOptions; +const latheOptions = { segments: 32, angleRange: new Vector2(0, 270), keepData: true } satisfies LatheMeshOptions; +const tubeOptions = { + radius: 0.1, + tubularSegments: 64, + radialSegments: 8, + closed: true, + keepData: true +} satisfies TubeMeshOptions; +const polygonOptions = { separateMaterials: true, keepData: true } satisfies PolygonMeshOptions; +const linearExtrusionOptions = { + depth: 2, + steps: 4, + bevelSize: 0.1, + bevelThickness: 0.2, + bevelOffset: 0.1, + bevelSegments: 3, + separateMaterials: true, + keepData: true +} satisfies LinearExtrusionMeshOptions; +const pathExtrusionOptions = { + path, + steps: 32, + closed: true, + separateMaterials: true, + keepData: true +} satisfies PathExtrusionMeshOptions; +const extrusionOptions: ExtrusionMeshOptions = pathExtrusionOptions; +const torusKnotOptions = { + radius: 1, + tubeRadius: 0.2, + p: 2, + q: 3, + tubularSegments: 64, + radialSegments: 12, + keepData: true +} satisfies TorusKnotMeshOptions; +const roundedCuboidOptions = { + width: 2, + height: 3, + depth: 4, + cornerRadius: 0.2, + segments: 4, + separateMaterials: true, + keepData: true +} satisfies RoundedCuboidMeshOptions; + +// Every factory lists its default call and a configuration containing all supported fields +const meshes: ModelMesh[] = [ + PrimitiveMesh.createSphere(engine), + PrimitiveMesh.createSphere(engine, sphereOptions), + PrimitiveMesh.createCuboid(engine), + PrimitiveMesh.createCuboid(engine, cuboidOptions), + PrimitiveMesh.createPlane(engine), + PrimitiveMesh.createPlane(engine, planeOptions), + PrimitiveMesh.createCylinder(engine), + PrimitiveMesh.createCylinder(engine, cylinderOptions), + PrimitiveMesh.createTruncatedCone(engine), + PrimitiveMesh.createTruncatedCone(engine, truncatedConeOptions), + PrimitiveMesh.createCone(engine), + PrimitiveMesh.createCone(engine, coneOptions), + PrimitiveMesh.createCapsule(engine), + PrimitiveMesh.createCapsule(engine, capsuleOptions), + PrimitiveMesh.createTorus(engine), + PrimitiveMesh.createTorus(engine, torusOptions), + PrimitiveMesh.createCircle(engine), + PrimitiveMesh.createCircle(engine, circleOptions), + PrimitiveMesh.createRing(engine), + PrimitiveMesh.createRing(engine, ringOptions), + PrimitiveMesh.createTetrahedron(engine), + PrimitiveMesh.createTetrahedron(engine, regularPolyhedronOptions), + PrimitiveMesh.createOctahedron(engine), + PrimitiveMesh.createOctahedron(engine, regularPolyhedronOptions), + PrimitiveMesh.createIcosahedron(engine), + PrimitiveMesh.createIcosahedron(engine, regularPolyhedronOptions), + PrimitiveMesh.createDodecahedron(engine), + PrimitiveMesh.createDodecahedron(engine, regularPolyhedronOptions), + PrimitiveMesh.createLathe(engine, profile), + PrimitiveMesh.createLathe(engine, profile, latheOptions), + PrimitiveMesh.createTube(engine, path), + PrimitiveMesh.createTube(engine, path, tubeOptions), + PrimitiveMesh.createPolygon(engine, contour), + PrimitiveMesh.createPolygon(engine, contour, polygonOptions), + PrimitiveMesh.createPolygon(engine, polygon), + PrimitiveMesh.createPolygon(engine, polygon, polygonOptions), + PrimitiveMesh.createPolygon(engine, polygons), + PrimitiveMesh.createPolygon(engine, polygons, polygonOptions), + PrimitiveMesh.createExtrusion(engine, contour), + PrimitiveMesh.createExtrusion(engine, contour, linearExtrusionOptions), + PrimitiveMesh.createExtrusion(engine, polygon), + PrimitiveMesh.createExtrusion(engine, polygon, linearExtrusionOptions), + PrimitiveMesh.createExtrusion(engine, polygons), + PrimitiveMesh.createExtrusion(engine, polygons, linearExtrusionOptions), + PrimitiveMesh.createExtrusion(engine, contour, pathExtrusionOptions), + PrimitiveMesh.createExtrusion(engine, polygon, pathExtrusionOptions), + PrimitiveMesh.createExtrusion(engine, polygons, pathExtrusionOptions), + PrimitiveMesh.createExtrusion(engine, polygons, extrusionOptions), + PrimitiveMesh.createTorusKnot(engine), + PrimitiveMesh.createTorusKnot(engine, torusKnotOptions), + PrimitiveMesh.createRoundedCuboid(engine), + PrimitiveMesh.createRoundedCuboid(engine, roundedCuboidOptions), + + // Partial configuration and common settings remain convenient + PrimitiveMesh.createSphere(engine, commonOptions), + PrimitiveMesh.createSphere(engine, { radius: 1 }), + PrimitiveMesh.createSphere(engine, { subdivisions: 4 }), + PrimitiveMesh.createRing(engine, { outerRadius: 1 }), + PrimitiveMesh.createCuboid(engine, { width: 2 }), + PrimitiveMesh.createCylinder(engine, { caps: PrimitiveMeshCapMode.Both }), + PrimitiveMesh.createCylinder(engine, { caps: PrimitiveMeshCapMode.Top }), + PrimitiveMesh.createExtrusion(engine, polygon, { path }) +]; +void meshes; + +// @ts-expect-error Numeric positional overloads are not part of the API +PrimitiveMesh.createSphere(engine, 1); +// @ts-expect-error Sphere options are an object +PrimitiveMesh.createSphere(engine, false); +// @ts-expect-error Spheres do not define material groups +PrimitiveMesh.createSphere(engine, { separateMaterials: true }); +// @ts-expect-error Planes do not define material groups +PrimitiveMesh.createPlane(engine, { separateMaterials: true }); +// @ts-expect-error Tori do not define material groups +PrimitiveMesh.createTorus(engine, { separateMaterials: true }); +// @ts-expect-error Tubes do not define material groups +PrimitiveMesh.createTube(engine, path, { separateMaterials: 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, { horizontalSegments: 32 }); +// @ts-expect-error Angular ranges use Vector2 rather than arrays +PrimitiveMesh.createCircle(engine, { angleRange: [0, 180] }); +// @ts-expect-error Runtime ranges require Vector2 instances +PrimitiveMesh.createSphere(engine, { horizontalRange: { x: 0, y: 180 } }); +// @ts-expect-error A cylinder cap selection must describe a supported combination +PrimitiveMesh.createCylinder(engine, { caps: "left" }); +// @ts-expect-error Cap modes use the exported enum rather than raw strings +PrimitiveMesh.createCylinder(engine, { caps: "top" }); +// @ts-expect-error Truncated cones use the same cap-mode enum +PrimitiveMesh.createTruncatedCone(engine, { caps: "none" }); +// @ts-expect-error Path extrusion does not support bevels +PrimitiveMesh.createExtrusion(engine, polygon, { path, bevelSize: 0.1 }); +// @ts-expect-error Path extrusion does not support contour offsets +PrimitiveMesh.createExtrusion(engine, polygon, { path, bevelOffset: 0.1 }); +// @ts-expect-error Only path extrusion can be closed +PrimitiveMesh.createExtrusion(engine, polygon, { depth: 2, closed: true }); +// @ts-expect-error Bevel offsets use numeric local units +PrimitiveMesh.createExtrusion(engine, polygon, { bevelOffset: "0.1" }); + +const mixedExtrusion = { path, depth: 2 }; +// @ts-expect-error Incompatible extrusion settings are rejected through variables too +PrimitiveMesh.createExtrusion(engine, polygon, mixedExtrusion); +const beveledPath = { path, bevelSize: 0.1 }; +// @ts-expect-error Variables cannot combine paths with bevels +PrimitiveMesh.createExtrusion(engine, polygon, beveledPath); + +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); +// @ts-expect-error Extrusion paths accept point arrays +PrimitiveMesh.createExtrusion(engine, polygon, { path: samplePath }); +// @ts-expect-error A lathe requires a profile +PrimitiveMesh.createLathe(engine); +// @ts-expect-error A tube requires a path +PrimitiveMesh.createTube(engine); +// @ts-expect-error A polygon requires contours +PrimitiveMesh.createPolygon(engine); + +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 Lathe profiles use Vector2 instances +PrimitiveMesh.createLathe(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); diff --git a/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts new file mode 100644 index 0000000000..ab76d95ec7 --- /dev/null +++ b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts @@ -0,0 +1,136 @@ +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", + sphereOptions: { verticalRange: { x: 0, y: 90 }, keepData: true, radius: 1, subdivisions: 3 } +}; +const exportedFromEngine: EnginePrimitiveMeshAsset = sphere; +const sphereSection: PrimitiveMeshAsset = { + type: "sphere", + sphereOptions: { horizontalRange: { x: 350, y: 370 }, verticalRange: { x: 30, y: 150 }, radius: 1, subdivisions: 3 } +}; +const ungroupedSphere: PrimitiveMeshAsset = { + type: "sphere", + sphereOptions: { + // @ts-expect-error Sphere assets do not define material groups + separateMaterials: 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; + +const tube: PrimitiveMeshAsset = { type: "tube", tubePath: path, tubeOptions: { closed: true } }; +const polygon: PrimitiveMeshAsset = { type: "polygon", polygonShapes: shapes }; +const extrusion: PrimitiveMeshAsset = { + type: "extrusion", + extrusionShapes: shapes, + extrusionOptions: { bevelSize: 0.1, bevelOffset: 0.2, separateMaterials: true, depth: 2 } +}; +const pathExtrusion: PrimitiveMeshAsset = { + type: "extrusion", + extrusionShapes: shapes, + extrusionOptions: { closed: true, path: path } +}; +const torusKnot: PrimitiveMeshAsset = { type: "torusKnot", torusKnotOptions: { p: -2, q: -3 } }; +const cylinder: PrimitiveMeshAsset = { + type: "cylinder", + cylinderOptions: { caps: PrimitiveMeshCapMode.Bottom } +}; +const truncatedCone: PrimitiveMeshAsset = { + type: "truncatedCone", + 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" }; +// @ts-expect-error Asset paths contain coordinates, not callbacks +const callbackPath: PrimitiveMeshAsset = { type: "tube", tubePath: (t: number) => t }; +// @ts-expect-error A polygon asset needs its contours +const missingShapes: PrimitiveMeshAsset = { type: "polygon" }; +const mixedExtrusion: PrimitiveMeshAsset = { + type: "extrusion", + extrusionShapes: shapes, + // @ts-expect-error An extrusion uses either a depth or a path + extrusionOptions: { depth: 2, path: path } +}; +const beveledPath: PrimitiveMeshAsset = { + type: "extrusion", + extrusionShapes: shapes, + // @ts-expect-error Path extrusion does not support bevels + extrusionOptions: { bevelSize: 1, path: path } +}; +const offsetPath: PrimitiveMeshAsset = { + type: "extrusion", + extrusionShapes: shapes, + // @ts-expect-error Path extrusion does not support contour offsets + extrusionOptions: { bevelOffset: 0.1, path: path } +}; +const closedDepth: PrimitiveMeshAsset = { + type: "extrusion", + extrusionShapes: shapes, + // @ts-expect-error Only path extrusion can be closed + extrusionOptions: { closed: true, depth: 2 } +}; +// @ts-expect-error Shape options cannot be applied to another primitive +const wrongOptions: PrimitiveMeshAsset = { type: "sphere", sphereOptions: { caps: PrimitiveMeshCapMode.Both } }; +// @ts-expect-error TypeScript assets use the cap-mode enum +const stringCap: PrimitiveMeshAsset = { type: "cylinder", cylinderOptions: { caps: "top" } }; +// @ts-expect-error Serialized angular ranges use coordinate objects rather than arrays +const wrongRange: PrimitiveMeshAsset = { type: "circle", circleOptions: { angleRange: [0, 180] } }; +// @ts-expect-error Spheres use one subdivision level rather than independent segment counts +const segmentedSphere: PrimitiveMeshAsset = { type: "sphere", sphereOptions: { horizontalSegments: 32 } }; +// @ts-expect-error Spheres have one canonical asset type +const duplicateSphere: PrimitiveMeshAsset = { type: "subdivisionSphere" }; +// @ts-expect-error End radii belong to truncatedCone +const endRadiiAsCylinder: PrimitiveMeshAsset = { type: "cylinder", cylinderOptions: { radiusTop: 1 } }; + +void [ + everyFactoryHasAnAsset, + everyAssetHasAFactory, + exportedFromEngine, + sphereSection, + ungroupedSphere, + tube, + polygon, + extrusion, + pathExtrusion, + torusKnot, + cylinder, + truncatedCone, + invalidType, + missingPath, + callbackPath, + missingShapes, + mixedExtrusion, + beveledPath, + offsetPath, + closedDepth, + wrongOptions, + stringCap, + wrongRange, + segmentedSphere, + duplicateSphere, + endRadiiAsCylinder +]; diff --git a/tests/src/core/DeviceLost.test.ts b/tests/src/core/DeviceLost.test.ts index 9a44fc0256..7b013845a6 100644 --- a/tests/src/core/DeviceLost.test.ts +++ b/tests/src/core/DeviceLost.test.ts @@ -41,7 +41,7 @@ describe("Device lost test", function () { const meshRenderer = meshEntity.addComponent(MeshRenderer); const material = new BlinnPhongMaterial(engine); meshRenderer.setMaterial(material); - meshRenderer.mesh = PrimitiveMesh.createSphere(engine, 1); + meshRenderer.mesh = PrimitiveMesh.createSphere(engine, { radius: 1 }); engine.update(); diff --git a/tests/src/core/Light.test.ts b/tests/src/core/Light.test.ts index e70a7e7173..d9dd93a487 100644 --- a/tests/src/core/Light.test.ts +++ b/tests/src/core/Light.test.ts @@ -244,7 +244,7 @@ describe("Light test", function () { const skyMaterial = new SkyBoxMaterial(engine); scene.background.mode = BackgroundMode.Sky; sky.material = skyMaterial; - sky.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); + sky.mesh = PrimitiveMesh.createCuboid(engine); ambientLightA = await engine.resourceManager.load({ type: AssetType.AmbientLight, diff --git a/tests/src/core/MeshRenderer.test.ts b/tests/src/core/MeshRenderer.test.ts index 5fe9b5a9db..7a4fd6bec7 100644 --- a/tests/src/core/MeshRenderer.test.ts +++ b/tests/src/core/MeshRenderer.test.ts @@ -38,7 +38,7 @@ describe("MeshRenderer", async function () { it("mesh", () => { // Test set mesh and get mesh work correctly. const mr = cubeEntity.getComponent(MeshRenderer); - const cubeMesh2 = PrimitiveMesh.createCuboid(engine, 1, 1, 1); + const cubeMesh2 = PrimitiveMesh.createCuboid(engine); mr.mesh = cubeMesh2; expect(mr.mesh).to.be.equal(cubeMesh2); expect(cubeMesh2.refCount).to.be.equal(1); @@ -47,7 +47,7 @@ describe("MeshRenderer", async function () { mr.mesh = cubeMesh2; expect(cubeMesh2.refCount).to.be.equal(1); - cubeMesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); + cubeMesh = PrimitiveMesh.createCuboid(engine, { width: 2 }); mr.mesh = cubeMesh; expect(mr.mesh).to.equal(cubeMesh); expect(cubeMesh2.refCount).to.be.equal(0); diff --git a/tests/src/core/Shader.test.ts b/tests/src/core/Shader.test.ts index 4c459924e5..2c91353fc4 100644 --- a/tests/src/core/Shader.test.ts +++ b/tests/src/core/Shader.test.ts @@ -156,7 +156,7 @@ describe("Shader", () => { const meshRenderer = meshEntity.addComponent(MeshRenderer); const material = new BlinnPhongMaterial(engine); meshRenderer.setMaterial(material); - meshRenderer.mesh = PrimitiveMesh.createSphere(engine, 1); + meshRenderer.mesh = PrimitiveMesh.createSphere(engine, { radius: 1 }); // Call update will compile shader internally engine.update(); @@ -198,7 +198,7 @@ describe("Shader", () => { const meshEntity = scene.createRootEntity("mesh"); const mr = meshEntity.addComponent(MeshRenderer); - mr.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); + mr.mesh = PrimitiveMesh.createCuboid(engine); mr.setMaterial(new Material(engine, shader)); // Test that shader compile variant successfully, if use shaderCompiler. diff --git a/tests/src/core/mesh/BlendShape.test.ts b/tests/src/core/mesh/BlendShape.test.ts index 2346126886..5c71220502 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); 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..f387dfc8ac 100644 --- a/tests/src/core/mesh/BlendShapeManager.test.ts +++ b/tests/src/core/mesh/BlendShapeManager.test.ts @@ -217,7 +217,15 @@ describe("BlendShapeManager", () => { ] ); blendShapeWeights0_7.addFrame(frame); - const modelMeshWebgl2 = PrimitiveMesh.createCuboid(engineWebGL2, 1, 1, 1, false); + const modelMeshWebgl2 = PrimitiveMesh.createCuboid(engineWebGL2, { + keepData: true, + width: 1, + height: 1, + depth: 1, + widthSegments: 1, + heightSegments: 1, + depthSegments: 1 + }); modelMeshWebgl2.addBlendShape(blendShapeWeights0_5); modelMeshWebgl2.addBlendShape(blendShapeWeights0_7); modelMeshWebgl2.addBlendShape(blendShapeWeights0_7); @@ -276,7 +284,7 @@ describe("BlendShapeManager", () => { const skinnedMREntity2 = rootEntity2.createChild("skinnedMR"); const meshRendererWebgl1 = skinnedMREntity2.addComponent(SkinnedMeshRenderer); - const modelMeshWebgl1 = PrimitiveMesh.createCuboid(engineWebGL1, 0.5, 0.5, 0.5); + const modelMeshWebgl1 = PrimitiveMesh.createCuboid(engineWebGL1, { width: 0.5 }); modelMeshWebgl1.addBlendShape(blendShapeWeights0_5); modelMeshWebgl1.addBlendShape(blendShapeWeights0_7); modelMeshWebgl1.addBlendShape(blendShapeWeights0_7); @@ -294,7 +302,7 @@ describe("BlendShapeManager", () => { }); it("_addBlendShape and _clearBlendShapes", () => { - const modelMesh = PrimitiveMesh.createPlane(engineWebGL2, 1, 1, 1, 1); + const modelMesh = PrimitiveMesh.createPlane(engineWebGL2); modelMesh.addBlendShape(new BlendShape("BlendShape1")); modelMesh.addBlendShape(new BlendShape("BlendShape2")); expect(modelMesh.blendShapeCount).to.be.equal(2); @@ -310,7 +318,7 @@ describe("BlendShapeManager", () => { }); it("_update", () => { - const modelMesh = PrimitiveMesh.createPlane(engineWebGL2, 1, 1, 1, 1); + const modelMesh = PrimitiveMesh.createPlane(engineWebGL2); 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 +328,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); blendShape.frames[0].deltaPositions = [ new Vector3(1, 0, 0), new Vector3(0, 1, 1), @@ -330,7 +338,7 @@ describe("BlendShapeManager", () => { modelMesh2.addBlendShape(blendShape); modelMesh2.uploadData(true); - const modelMesh3 = PrimitiveMesh.createCuboid(engineWebGL2, 1, 1, 1); + const modelMesh3 = PrimitiveMesh.createCuboid(engineWebGL2); modelMesh3.addBlendShape(blendShape); // Test that _update throw error if use released blendShape. expect(() => { diff --git a/tests/src/core/mesh/PrimitiveMesh.test.ts b/tests/src/core/mesh/PrimitiveMesh.test.ts index 1956ba4574..a43b909251 100644 --- a/tests/src/core/mesh/PrimitiveMesh.test.ts +++ b/tests/src/core/mesh/PrimitiveMesh.test.ts @@ -1,6 +1,6 @@ import { Camera, GLCapabilityType, PrimitiveMesh } from "@galacean/engine-core"; import { WebGLEngine } from "@galacean/engine"; -import { Vector3 } from "@galacean/engine-math"; +import { Vector2, Vector3 } from "@galacean/engine-math"; import { describe, beforeAll, expect, it } from "vitest"; describe("PrimitiveMesh", () => { @@ -19,31 +19,20 @@ 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 subdivisions = 3.2; + const sphereMesh = PrimitiveMesh.createSphere(engine, { + keepData: true, + radius, + subdivisions + }); 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 +40,15 @@ 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, { + keepData: true, + width, + height, + depth, + widthSegments: 1, + heightSegments: 1, + depthSegments: 1 + }); expect(cuboidMesh.vertexCount).equal(24); expect(cuboidMesh.vertexElements.length).equal(4); @@ -61,8 +58,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 +67,26 @@ describe("PrimitiveMesh", () => { const heightSegments = 1.00001; const floorRadialSegments = Math.floor(radialSegments); const floorHeightSegments = Math.floor(heightSegments); - const cylinderMesh = PrimitiveMesh.createCylinder( - engine, - radiusTop, - radiusBottom, + const truncatedConeMesh = PrimitiveMesh.createTruncatedCone(engine, { + keepData: true, + topRadius: radiusTop, + bottomRadius: radiusBottom, height, 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", () => { @@ -102,15 +98,14 @@ describe("PrimitiveMesh", () => { const floorRadialSegments = Math.floor(radialSegments); const floorTubularSegments = Math.floor(tubularSegments); const arc = 180; - const torusMesh = PrimitiveMesh.createTorus( - engine, + const torusMesh = PrimitiveMesh.createTorus(engine, { + keepData: true, + angleRange: new Vector2(0, 0 + arc), radius, tubeRadius, - radialSegments, tubularSegments, - arc, - false - ); + radialSegments + }); const outerRadius = radius + tubeRadius; expect(torusMesh.vertexCount).equal((floorRadialSegments + 1) * (floorTubularSegments + 1)); @@ -129,7 +124,13 @@ 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, { + keepData: true, + width, + height, + horizontalSegments: hSegments, + verticalSegments: vSegments + }); expect(planeMesh.vertexCount).equal((floorHSegments + 1) * (floorVSegments + 1)); expect(planeMesh.vertexElements.length).equal(4); @@ -147,13 +148,19 @@ 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, { + keepData: true, + radius, + height, + 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 +171,55 @@ 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, { + keepData: true, + radius, + height, + 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, { + keepData: true, + width: radius * 2, + height: radius * 2, + horizontalSegments: segments, + verticalSegments: 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, { + keepData: true, + width: radius * 2, + height: radius * 2, + horizontalSegments: segments, + verticalSegments: segments + }) + ).throw("The vertex count is out of range."); } }); }); diff --git a/tests/src/core/mesh/ProceduralMesh.test.ts b/tests/src/core/mesh/ProceduralMesh.test.ts new file mode 100644 index 0000000000..1939c20cc9 --- /dev/null +++ b/tests/src/core/mesh/ProceduralMesh.test.ts @@ -0,0 +1,2072 @@ +import { + Buffer, + BufferBindFlag, + BufferUsage, + EngineEventType, + ModelMesh, + PrimitiveMesh, + PrimitiveMeshCapMode, + SetDataOptions, + Vector2, + Vector3, + 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, { keepData: true, radius: 2, subdivisions: 2 })], + [ + "cuboid", + () => + PrimitiveMesh.createCuboid(engine, { + keepData: true, + width: 1, + height: 1, + depth: 1, + widthSegments: 3, + heightSegments: 2, + depthSegments: 2 + }) + ], + [ + "plane", + () => + PrimitiveMesh.createPlane(engine, { + keepData: true, + width: 1, + height: 1, + horizontalSegments: 3, + verticalSegments: 2 + }) + ], + [ + "cylinder", + () => + PrimitiveMesh.createTruncatedCone(engine, { + keepData: true, + topRadius: 0.25, + bottomRadius: 1, + height: 2, + radialSegments: 12, + heightSegments: 1 + }) + ], + [ + "cone", + () => + PrimitiveMesh.createCone(engine, { + keepData: true, + radius: 0.5, + height: 2, + radialSegments: 12, + heightSegments: 1 + }) + ], + [ + "capsule", + () => + PrimitiveMesh.createCapsule(engine, { + keepData: true, + radius: 0.5, + height: 2, + radialSegments: 12, + capSegments: 4, + heightSegments: 1 + }) + ], + [ + "torus", + () => + PrimitiveMesh.createTorus(engine, { + keepData: true, + angleRange: new Vector2(0, 360), + radius: 0.5, + tubeRadius: 0.1, + tubularSegments: 16, + radialSegments: 8 + }) + ], + [ + "circle", + () => + PrimitiveMesh.createCircle(engine, { keepData: true, angleRange: new Vector2(0, 180), radius: 0.5, segments: 12 }) + ], + [ + "ring", + () => + PrimitiveMesh.createRing(engine, { + keepData: true, + angleRange: new Vector2(0, 360), + outerRadius: 0.5, + innerRadius: 0.25, + radialSegments: 12, + widthSegments: 2 + }) + ], + ["tetrahedron", () => PrimitiveMesh.createTetrahedron(engine, { keepData: true, radius: 0.5, segments: 1 })], + ["octahedron", () => PrimitiveMesh.createOctahedron(engine, { keepData: true, radius: 0.5, segments: 1 })], + ["icosahedron", () => PrimitiveMesh.createIcosahedron(engine, { keepData: true, radius: 0.5, segments: 2 })], + ["dodecahedron", () => PrimitiveMesh.createDodecahedron(engine, { keepData: true, radius: 0.5, segments: 1 })], + [ + "lathe", + () => + PrimitiveMesh.createLathe(engine, [new Vector2(0, -1), new Vector2(1, 0), new Vector2(0, 1)], { + keepData: true, + angleRange: new Vector2(0, 360), + segments: 12 + }) + ], + [ + "tube", + () => + PrimitiveMesh.createTube(engine, path, { keepData: true, radius: 0.5, tubularSegments: 12, radialSegments: 8 }) + ], + ["polygon", () => PrimitiveMesh.createPolygon(engine, polygon, { keepData: true })], + ["extrusion", () => PrimitiveMesh.createExtrusion(engine, polygon, { keepData: true, depth: 2, steps: 1 })], + [ + "extrusion", + () => + PrimitiveMesh.createExtrusion(engine, polygon, { + keepData: true, + bevelSize: 0.1, + bevelOffset: 0.2, + depth: 1, + steps: 1 + }) + ], + ["extrusion", () => PrimitiveMesh.createExtrusion(engine, polygon, { keepData: true, path, steps: 5 })], + [ + "extrusion", + () => + PrimitiveMesh.createExtrusion( + 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) + ] + }, + { keepData: true, bevelSize: 0.05, bevelThickness: 0.1, bevelOffset: -0.05, depth: 1, steps: 1 } + ) + ], + [ + "torusKnot", + () => + PrimitiveMesh.createTorusKnot(engine, { + keepData: true, + radius: 0.5, + tubeRadius: 0.1, + p: 2, + q: 3, + tubularSegments: 32, + radialSegments: 8 + }) + ], + [ + "torusKnot", + () => + PrimitiveMesh.createTorusKnot(engine, { + keepData: true, + radius: 0.5, + tubeRadius: 0.1, + p: -2, + q: -3, + tubularSegments: 32, + radialSegments: 8 + }) + ], + [ + "roundedCuboid", + () => + PrimitiveMesh.createRoundedCuboid(engine, { + keepData: true, + width: 1, + height: 1, + depth: 1, + cornerRadius: 0.15, + segments: 3 + }) + ] +]; + +describe("primitive mesh defaults", () => { + const options = { keepData: true }; + const profile = [new Vector2(0, -1), new Vector2(1, 0), new Vector2(0, 1)]; + const cases: [string, () => ModelMesh, () => ModelMesh][] = [ + [ + "sphere", + () => PrimitiveMesh.createSphere(engine, { ...options, radius: 1 }), + () => PrimitiveMesh.createSphere(engine, { ...options, radius: 1, subdivisions: 3 }) + ], + [ + "cuboid", + () => PrimitiveMesh.createCuboid(engine, { ...options, width: 2, height: 3, depth: 4, widthSegments: 3 }), + () => + PrimitiveMesh.createCuboid(engine, { + ...options, + width: 2, + height: 3, + depth: 4, + widthSegments: 3, + heightSegments: 3, + depthSegments: 3 + }) + ], + [ + "plane", + () => PrimitiveMesh.createPlane(engine, { ...options, width: 2, height: 3, horizontalSegments: 2 }), + () => + PrimitiveMesh.createPlane(engine, { + ...options, + width: 2, + height: 3, + horizontalSegments: 2, + verticalSegments: 2 + }) + ], + [ + "cylinder", + () => PrimitiveMesh.createCylinder(engine, { ...options, radius: 1, height: 2 }), + () => + PrimitiveMesh.createCylinder(engine, { + ...options, + radius: 1, + height: 2, + radialSegments: 20, + heightSegments: 1 + }) + ], + [ + "truncated cone", + () => PrimitiveMesh.createTruncatedCone(engine, { ...options, topRadius: 0.25, bottomRadius: 1, height: 2 }), + () => + PrimitiveMesh.createTruncatedCone(engine, { + ...options, + topRadius: 0.25, + bottomRadius: 1, + height: 2, + radialSegments: 20, + heightSegments: 1 + }) + ], + [ + "cone", + () => PrimitiveMesh.createCone(engine, { ...options, radius: 1, height: 2 }), + () => + PrimitiveMesh.createCone(engine, { ...options, radius: 1, height: 2, radialSegments: 20, heightSegments: 1 }) + ], + [ + "capsule", + () => PrimitiveMesh.createCapsule(engine, { ...options, radius: 1, height: 2, radialSegments: 12 }), + () => + PrimitiveMesh.createCapsule(engine, { + ...options, + radius: 1, + height: 2, + radialSegments: 12, + capSegments: 12, + heightSegments: 1 + }) + ], + [ + "torus", + () => PrimitiveMesh.createTorus(engine, { ...options, radius: 1, tubeRadius: 0.2 }), + () => + PrimitiveMesh.createTorus(engine, { + ...options, + radius: 1, + tubeRadius: 0.2, + tubularSegments: 30, + radialSegments: 30 + }) + ], + [ + "circle", + () => PrimitiveMesh.createCircle(engine, { ...options, radius: 1 }), + () => PrimitiveMesh.createCircle(engine, { ...options, radius: 1, segments: 32 }) + ], + [ + "ring", + () => PrimitiveMesh.createRing(engine, { ...options, outerRadius: 1, innerRadius: 0.5 }), + () => + PrimitiveMesh.createRing(engine, { + ...options, + outerRadius: 1, + innerRadius: 0.5, + radialSegments: 32, + widthSegments: 1 + }) + ], + [ + "tetrahedron", + () => PrimitiveMesh.createTetrahedron(engine, { ...options, radius: 1 }), + () => PrimitiveMesh.createTetrahedron(engine, { ...options, radius: 1, segments: 1 }) + ], + [ + "octahedron", + () => PrimitiveMesh.createOctahedron(engine, { ...options, radius: 1 }), + () => PrimitiveMesh.createOctahedron(engine, { ...options, radius: 1, segments: 1 }) + ], + [ + "icosahedron", + () => PrimitiveMesh.createIcosahedron(engine, { ...options, radius: 1 }), + () => PrimitiveMesh.createIcosahedron(engine, { ...options, radius: 1, segments: 1 }) + ], + [ + "dodecahedron", + () => PrimitiveMesh.createDodecahedron(engine, { ...options, radius: 1 }), + () => PrimitiveMesh.createDodecahedron(engine, { ...options, radius: 1, segments: 1 }) + ], + [ + "lathe", + () => PrimitiveMesh.createLathe(engine, profile, { ...options }), + () => PrimitiveMesh.createLathe(engine, profile, { ...options, segments: 12 }) + ], + [ + "tube", + () => PrimitiveMesh.createTube(engine, path, { ...options, radius: 0.2 }), + () => PrimitiveMesh.createTube(engine, path, { ...options, radius: 0.2, tubularSegments: 64, radialSegments: 8 }) + ], + [ + "depth extrusion", + () => PrimitiveMesh.createExtrusion(engine, polygon, { ...options, depth: 2 }), + () => PrimitiveMesh.createExtrusion(engine, polygon, { ...options, depth: 2, steps: 1 }) + ], + [ + "path extrusion", + () => PrimitiveMesh.createExtrusion(engine, polygon, { ...options, path }), + () => PrimitiveMesh.createExtrusion(engine, polygon, { ...options, path, steps: 1 }) + ], + [ + "torus knot", + () => PrimitiveMesh.createTorusKnot(engine, { ...options, radius: 1, tubeRadius: 0.2, p: 2, q: 3 }), + () => + PrimitiveMesh.createTorusKnot(engine, { + ...options, + radius: 1, + tubeRadius: 0.2, + p: 2, + q: 3, + tubularSegments: 64, + radialSegments: 8 + }) + ], + [ + "rounded cuboid", + () => PrimitiveMesh.createRoundedCuboid(engine, { ...options, width: 2, height: 3, depth: 4, cornerRadius: 0.2 }), + () => + PrimitiveMesh.createRoundedCuboid(engine, { + ...options, + width: 2, + height: 3, + depth: 4, + cornerRadius: 0.2, + segments: 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, { ...options, outerRadius: radius }); + const defaultMesh = PrimitiveMesh.createRing(engine, { outerRadius: radius }); + 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 uniform size and subdivision defaults for partial options", () => { + const cube = PrimitiveMesh.createCuboid(engine, { width: 2 }); + const plane = PrimitiveMesh.createPlane(engine, { width: 3 }); + const sphere = PrimitiveMesh.createSphere(engine, { radius: 1 }); + const detailedSphere = PrimitiveMesh.createSphere(engine, { radius: 1, subdivisions: 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, { radius: 1, height: 3 }); + const frustum = PrimitiveMesh.createTruncatedCone(engine, { topRadius: 0.5, bottomRadius: 1.5, height: 4 }); + const topOnly = PrimitiveMesh.createCylinder(engine, { + caps: PrimitiveMeshCapMode.Top, + keepData: true, + radius: 1, + height: 3, + 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(); + } + }); + + it("uses one polygon algorithm for contours and polygons with holes", () => { + const fromContours = PrimitiveMesh.createPolygon( + engine, + { points: polygon.points, holes: polygon.holes }, + { keepData: true } + ); + const fromShape = PrimitiveMesh.createPolygon(engine, polygon, { keepData: true }); + const withoutHoles = PrimitiveMesh.createPolygon(engine, polygon.points, { keepData: 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, { + keepData: true, + angleRange: new Vector2(90, 180), + radius: 1, + tubeRadius: 0.25, + tubularSegments: 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([ + { p: 2, q: 3, expected: new Vector3(1, Math.sqrt(3), 1) }, + { p: 2, q: -3, expected: new Vector3(1, Math.sqrt(3), -1) }, + { p: -2, q: 3, expected: new Vector3(1, -Math.sqrt(3), 1) }, + { p: -2, q: -3, expected: new Vector3(1, -Math.sqrt(3), -1) }, + { p: 0, q: 1, expected: new Vector3(2 + Math.sqrt(3) / 2, 0, 0.5) }, + { p: 1, q: 0, expected: new Vector3((3 * Math.sqrt(3)) / 2, 1.5, 0) } + ])("preserves torus knot windings p=$p, q=$q during creation and restoration", ({ p, q, expected }) => { + const radialSegments = 8; + const mesh = PrimitiveMesh.createTorusKnot(engine, { + keepData: true, + radius: 2, + tubeRadius: 0.2, + p, + q, + tubularSegments: 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, { + keepData: true, + radius: 1, + height: 2, + 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 lathe", ({ segments, crossSection }) => { + const mesh = PrimitiveMesh.createLathe(engine, [new Vector2(1, -1), new Vector2(1, 1)], { + keepData: 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, { + keepData: true, + separateMaterials: true, + width: sizes.x, + height: sizes.y, + depth: sizes.z, + cornerRadius: radius, + 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 = { keepData: true, separateMaterials: true }; + const meshes = [ + PrimitiveMesh.createCuboid(engine, { + ...options, + width: 2, + height: 3, + depth: 4, + widthSegments: 1, + heightSegments: 1, + depthSegments: 1 + }), + PrimitiveMesh.createRoundedCuboid(engine, { + ...options, + width: 2, + height: 3, + depth: 4, + cornerRadius: 0, + segments: 4 + }), + PrimitiveMesh.createRoundedCuboid(engine, { + ...options, + width: 2, + height: 3, + depth: 4, + cornerRadius: -1, + segments: 4 + }), + PrimitiveMesh.createRoundedCuboid(engine, { + ...options, + width: 2, + height: 3, + depth: 4, + cornerRadius: 1, + segments: 3 + }), + PrimitiveMesh.createRoundedCuboid(engine, { + ...options, + width: 2, + height: 3, + depth: 4, + cornerRadius: 8, + segments: 3 + }), + PrimitiveMesh.createRoundedCuboid(engine, { + ...options, + width: 2, + height: 3, + depth: 4, + cornerRadius: 0.2, + segments: 0 + }), + PrimitiveMesh.createRoundedCuboid(engine, { + ...options, + width: 2, + height: 3, + depth: 4, + cornerRadius: 0.2, + segments: 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, { + keepData: true, + width, + height, + depth, + cornerRadius: radius, + segments: 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 keepData=%s", (keepData) => { + const mesh = PrimitiveMesh.createSphere(engine, { keepData, radius: 0.5, subdivisions: 1 }); + try { + for (const binding of mesh.vertexBufferBindings) { + expect(binding!.buffer.readable).toBe(keepData); + } + if (keepData) { + 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, { keepData: true, radius: 2, subdivisions: 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, { + keepData: true, + verticalRange: new Vector2(0, 90), + radius: 0.5, + subdivisions: 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, { + keepData: true, + horizontalRange: new Vector2(horizontal[0], horizontal[1]), + verticalRange: new Vector2(vertical[0], vertical[1]), + radius, + subdivisions: 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, { keepData: true, radius: 1, subdivisions: 2 }); + const rotated = PrimitiveMesh.createSphere(engine, { + keepData: true, + horizontalRange: new Vector2(90, 450), + radius: 1, + subdivisions: 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 horizontalRange = new Vector2(20, 290); + const verticalRange = new Vector2(30, 150); + const mesh = PrimitiveMesh.createSphere(engine, { horizontalRange, verticalRange, radius: 1, subdivisions: 3 }); + try { + const buffer = mesh.vertexBufferBindings[0]!.buffer; + const original = MeshTestUtils.readBuffer(buffer); + horizontalRange.y = 360; + verticalRange.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, { + keepData: true, + caps: PrimitiveMeshCapMode.None, + radius: 0.5, + height: 2, + radialSegments: 8, + heightSegments: 1 + }); + const grouped = PrimitiveMesh.createCylinder(engine, { + separateMaterials: true, + radius: 0.5, + height: 2, + radialSegments: 8, + heightSegments: 1 + }); + const cube = PrimitiveMesh.createCuboid(engine, { + separateMaterials: true, + width: 1, + height: 1, + depth: 1, + 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, { + keepData: true, + separateMaterials: true, + width: 1, + height: 2, + depth: 3, + 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, { + keepData: true, + separateMaterials: true, + radius: 1, + height: 2, + radialSegments: 8, + heightSegments: 1 + }), + parts: ["side", "top", "bottom"] + }, + { + name: "cylinder with only its top cap", + create: () => + PrimitiveMesh.createCylinder(engine, { + keepData: true, + separateMaterials: true, + caps: PrimitiveMeshCapMode.Top, + radius: 1, + height: 2, + radialSegments: 8, + heightSegments: 1 + }), + parts: ["side", "top"] + }, + { + name: "cylinder with only its bottom cap", + create: () => + PrimitiveMesh.createCylinder(engine, { + keepData: true, + separateMaterials: true, + caps: PrimitiveMeshCapMode.Bottom, + radius: 1, + height: 2, + radialSegments: 8, + heightSegments: 1 + }), + parts: ["side", "bottom"] + }, + { + name: "cylinder without caps", + create: () => + PrimitiveMesh.createCylinder(engine, { + keepData: true, + separateMaterials: true, + caps: PrimitiveMeshCapMode.None, + radius: 1, + height: 2, + radialSegments: 8, + heightSegments: 1 + }), + parts: ["side"] + }, + { + name: "truncated cone with a zero top radius", + create: () => + PrimitiveMesh.createTruncatedCone(engine, { + keepData: true, + separateMaterials: true, + topRadius: 0, + bottomRadius: 1, + height: 2, + radialSegments: 8, + heightSegments: 1 + }), + parts: ["side", "bottom"] + }, + { + name: "truncated cone with a zero bottom radius", + create: () => + PrimitiveMesh.createTruncatedCone(engine, { + keepData: true, + separateMaterials: true, + topRadius: 1, + bottomRadius: 0, + height: 2, + radialSegments: 8, + heightSegments: 1 + }), + parts: ["side", "top"] + }, + { + name: "cone with its bottom cap", + create: () => + PrimitiveMesh.createCone(engine, { + keepData: true, + separateMaterials: true, + radius: 1, + height: 2, + radialSegments: 8, + heightSegments: 1 + }), + parts: ["side", "bottom"] + }, + { + name: "cone without its bottom cap", + create: () => + PrimitiveMesh.createCone(engine, { + keepData: true, + separateMaterials: true, + cap: false, + radius: 1, + height: 2, + 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, { keepData: true, separateMaterials: 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.createExtrusion(engine, shapes, { + keepData: true, + separateMaterials: true, + depth: 2, + steps: 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", (bevelOffset) => { + const options = { keepData: true, separateMaterials: true, bevelSize: 0.1, bevelThickness: 0.2, bevelOffset }; + const mesh = PrimitiveMesh.createExtrusion(engine, polygon, { ...options, depth: 2, steps: 2 }); + try { + const outer = 2 + bevelOffset; + const hole = 1 - bevelOffset; + 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.bevelOffset = 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", (bevelOffset) => { + const mesh = PrimitiveMesh.createExtrusion(engine, polygon, { keepData: true, bevelOffset, depth: 2, steps: 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 + bevelOffset; + const hole = 1 - bevelOffset; + 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, { keepData: 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, { keepData: 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.createExtrusion(engine, { points, holes }, { keepData: true, depth: 3, steps: 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("restores captured geometry after caller-owned inputs and buffers change", () => { + const points = [new Vector3(0, 0, 0), new Vector3(0, 1, 1), new Vector3(1, 2, 2)]; + const mesh = PrimitiveMesh.createTube(engine, points, { + keepData: true, + radius: 0.5, + tubularSegments: 8, + radialSegments: 8 + }); + try { + const before = mesh.getPositions()!.map((p) => p.toJSON()); + const indices = Array.from(mesh.getIndices()!); + points[1].set(100, 200, 300); + const buffer = mesh.vertexBufferBindings[0]!.buffer; + MeshTestUtils.clearBuffer(buffer); + const restorers = (engine.resourceManager as any)._contentRestorerPool; + restorers[mesh.instanceId].restoreContent(); + expect(mesh.getPositions()!.map((p) => p.toJSON())).toEqual(before); + expect(Array.from(mesh.getIndices()!)).toEqual(indices); + expect(mesh.vertexBufferBindings[0]!.buffer).toBe(buffer); + } finally { + mesh.destroy(); + } + }); + + it.each([ + { type: "tube", keepData: false }, + { type: "tube", keepData: true }, + { type: "extrusion", keepData: false }, + { type: "extrusion", keepData: true } + ])("copies $type path points for device restoration with keepData=$keepData", ({ type, keepData }) => { + const points = path.map((point) => point.clone()); + const mesh = + type === "tube" + ? PrimitiveMesh.createTube(engine, points, { + keepData, + radius: 0.5, + tubularSegments: 12, + radialSegments: 8 + }) + : PrimitiveMesh.createExtrusion(engine, polygon, { keepData, path: points, steps: 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); + 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, { keepData: true, radius: 0.5, subdivisions: 2 }), + PrimitiveMesh.createSphere(engine, { keepData: true, radius: 2, subdivisions: 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, { + keepData: true, + width: 1, + height: 1, + horizontalSegments: 256, + verticalSegments: 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, { + keepData: true, + closed: true, + radius: 0.5, + tubularSegments: 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, { + keepData: true, + radius: 1, + tubeRadius: 0.2, + p: 2, + q: 3, + tubularSegments: 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, { radius: 1, tubeRadius: 0.2, p: 0, q: 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, { + keepData: true, + closed: true, + radius: 0.5, + tubularSegments: 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 = { keepData: true, closed: true }; + const mesh = PrimitiveMesh.createExtrusion(engine, profile, { ...options, path: points, steps: 32 }); + const repeated = PrimitiveMesh.createExtrusion(engine, profile, { + ...options, + path: [...points, points[0].clone()], + steps: 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.closed = 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.createExtrusion(engine, shapes, { + keepData: true, + separateMaterials: true, + closed: true, + path: points, + steps: 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("uses at least three steps 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.createExtrusion(engine, profile, { keepData: true, closed: true, path: points }); + 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)], { + keepData: true, + radius: 0.5, + tubularSegments: 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, { radius: 1, segments, keepData: 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); + 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("preserves edited primitive data and material groups after device restoration", async () => { + const restoredEngine = await WebGLEngine.create({ canvas: document.createElement("canvas") }); + const released = PrimitiveMesh.createSphere(restoredEngine, { radius: 1, subdivisions: 1 }); + const mesh = PrimitiveMesh.createCuboid(restoredEngine, { + keepData: true, + separateMaterials: true, + width: 1, + height: 1, + depth: 1, + widthSegments: 1, + heightSegments: 1, + depthSegments: 1 + }); + try { + const uvs = mesh.getUVs()!.map((uv) => new Vector2(uv.x * 2 + 0.25, uv.y * 3 - 0.5)); + const secondaryUVs = uvs.map((uv) => uv.clone().scale(0.5)); + mesh.setUVs(uvs); + mesh.setUVs(secondaryUVs, 1); + mesh.calculateTangents(); + mesh.setIndices(mesh.getIndices()!.slice(0, 6)); + mesh.clearSubMesh(); + const subMesh = mesh.addSubMesh(0, 6); + mesh.bounds.min.set(-2, -3, -4); + mesh.bounds.max.set(2, 3, 4); + mesh.uploadData(false); + const bindings = mesh.vertexBufferBindings.map((binding) => binding!.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 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.getUVs()!.map((uv) => uv.toJSON())).toEqual(uvs.map((uv) => uv.toJSON())); + expect(mesh.getUVs(1)!.map((uv) => uv.toJSON())).toEqual(secondaryUVs.map((uv) => uv.toJSON())); + expect(mesh.getIndices()!).toHaveLength(6); + expect(mesh.subMeshes).toHaveLength(1); + expect(mesh.subMeshes[0]).toBe(subMesh); + expect(mesh.bounds.min.toJSON()).toEqual({ x: -2, y: -3, z: -4 }); + expect(mesh.bounds.max.toJSON()).toEqual({ x: 2, y: 3, z: 4 }); + bindings.forEach((buffer, index) => { + expect(mesh.vertexBufferBindings[index]!.buffer).toBe(buffer); + expect(MeshTestUtils.readBuffer(buffer)).toEqual(buffers[index]); + }); + releasedBindings.forEach((buffer, index) => { + expect(MeshTestUtils.readBuffer(buffer)).toEqual(releasedBuffers[index]); + }); + } finally { + restoredEngine.destroy(); + } + }); + + it("restores released tangents from edited primitive UVs", () => { + const mesh = PrimitiveMesh.createPlane(engine, { + keepData: true, + width: 2, + height: 3, + horizontalSegments: 1, + verticalSegments: 1 + }); + try { + mesh.setUVs(mesh.getUVs()!.map((uv) => new Vector2(uv.y, uv.x))); + mesh.calculateTangents(); + mesh.uploadData(true); + const bindings = mesh.vertexBufferBindings.map((binding) => binding!.buffer); + bindings.push(mesh._primitive.indexBufferBinding!._buffer); + const original = bindings.map((buffer) => MeshTestUtils.readBuffer(buffer)); + bindings.forEach((buffer) => MeshTestUtils.clearBuffer(buffer)); + (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); + bindings.forEach((buffer, index) => { + expect(MeshTestUtils.readBuffer(buffer)).toEqual(original[index]); + }); + } finally { + mesh.destroy(); + } + }); + + it.each([1, 1e-8])("normalizes tangents for a plane of size %s", (size) => { + const mesh = PrimitiveMesh.createPlane(engine, { + keepData: true, + width: size, + height: size, + horizontalSegments: 1, + verticalSegments: 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, { keepData: true, subdivisions: 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("releases primitive tangent data through the ModelMesh buffer lifecycle", () => { + const mesh = PrimitiveMesh.createPlane(engine, { keepData: 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("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.createExtrusion(engine, contour, { keepData: true, steps: 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.createExtrusion( + 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) + ] + }, + { keepData: true, bevelSize: 0.1, depth: 1, steps: 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/physics/ColliderLayer.test.ts b/tests/src/core/physics/ColliderLayer.test.ts index 1df326a0e5..6de03c9d39 100644 --- a/tests/src/core/physics/ColliderLayer.test.ts +++ b/tests/src/core/physics/ColliderLayer.test.ts @@ -101,7 +101,15 @@ 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, { + keepData: true, + width: 1, + height: 1, + depth: 1, + 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..a9133f793f 100644 --- a/tests/src/core/physics/MeshColliderLayer.test.ts +++ b/tests/src/core/physics/MeshColliderLayer.test.ts @@ -25,7 +25,15 @@ 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, { + keepData: true, + width: 10, + height: 1, + depth: 10, + 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..d6fcd82adf --- /dev/null +++ b/tests/src/loader/PrimitiveMeshLoader.test.ts @@ -0,0 +1,643 @@ +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 = { keepData: true }; +const groupedOptions = { keepData: true, separateMaterials: true }; + +describe("PrimitiveMeshLoader", () => { + const defaults = { + sphere: { data: { type: "sphere" }, create: () => PrimitiveMesh.createSphere(engine) }, + cuboid: { data: { type: "cuboid" }, create: () => PrimitiveMesh.createCuboid(engine) }, + plane: { data: { type: "plane" }, create: () => PrimitiveMesh.createPlane(engine) }, + cylinder: { data: { type: "cylinder" }, create: () => PrimitiveMesh.createCylinder(engine) }, + truncatedCone: { data: { type: "truncatedCone" }, create: () => PrimitiveMesh.createTruncatedCone(engine) }, + cone: { data: { type: "cone" }, create: () => PrimitiveMesh.createCone(engine) }, + capsule: { data: { type: "capsule" }, create: () => PrimitiveMesh.createCapsule(engine) }, + torus: { data: { type: "torus" }, create: () => PrimitiveMesh.createTorus(engine) }, + circle: { data: { type: "circle" }, create: () => PrimitiveMesh.createCircle(engine) }, + ring: { data: { type: "ring" }, create: () => PrimitiveMesh.createRing(engine) }, + tetrahedron: { data: { type: "tetrahedron" }, create: () => PrimitiveMesh.createTetrahedron(engine) }, + octahedron: { data: { type: "octahedron" }, create: () => PrimitiveMesh.createOctahedron(engine) }, + icosahedron: { data: { type: "icosahedron" }, create: () => PrimitiveMesh.createIcosahedron(engine) }, + dodecahedron: { data: { type: "dodecahedron" }, create: () => PrimitiveMesh.createDodecahedron(engine) }, + lathe: { + data: { type: "lathe", latheProfile: profile }, + create: () => PrimitiveMesh.createLathe(engine, profileVectors) + }, + tube: { data: { type: "tube", tubePath: path }, create: () => PrimitiveMesh.createTube(engine, pathVectors) }, + polygon: { + data: { type: "polygon", polygonShapes: shapes }, + create: () => PrimitiveMesh.createPolygon(engine, shapeVectors) + }, + extrusion: { + data: { type: "extrusion", extrusionShapes: shapes }, + create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors) + }, + torusKnot: { data: { type: "torusKnot" }, create: () => PrimitiveMesh.createTorusKnot(engine) }, + roundedCuboid: { data: { type: "roundedCuboid" }, create: () => PrimitiveMesh.createRoundedCuboid(engine) } + } satisfies Record ModelMesh }>; + + const configured: { name: string; data: PrimitiveMeshAsset; create: () => ModelMesh }[] = [ + { + name: "sphere ranges and subdivision level", + data: { + type: "sphere", + sphereOptions: { + ...options, + horizontalRange: { x: 20, y: 260 }, + verticalRange: { x: 30, y: 150 }, + radius: 2, + subdivisions: 3 + } + }, + create: () => + PrimitiveMesh.createSphere(engine, { + ...options, + horizontalRange: new Vector2(20, 260), + verticalRange: new Vector2(30, 150), + radius: 2, + subdivisions: 3 + }) + }, + { + name: "sphere", + data: { type: "sphere", sphereOptions: { ...options, radius: 1.5, subdivisions: 2 } }, + create: () => PrimitiveMesh.createSphere(engine, { ...options, radius: 1.5, subdivisions: 2 }) + }, + { + name: "sphere angular ranges", + data: { + type: "sphere", + sphereOptions: { + ...options, + horizontalRange: { x: 350, y: 370 }, + verticalRange: { x: 30, y: 150 }, + radius: 2, + subdivisions: 3 + } + }, + create: () => + PrimitiveMesh.createSphere(engine, { + ...options, + horizontalRange: new Vector2(350, 370), + verticalRange: new Vector2(30, 150), + radius: 2, + subdivisions: 3 + }) + }, + { + name: "cuboid dimensions and segment counts", + data: { + type: "cuboid", + cuboidOptions: { + ...groupedOptions, + width: 2, + height: 3, + depth: 4, + widthSegments: 2, + heightSegments: 3, + depthSegments: 4 + } + }, + create: () => + PrimitiveMesh.createCuboid(engine, { + ...groupedOptions, + width: 2, + height: 3, + depth: 4, + widthSegments: 2, + heightSegments: 3, + depthSegments: 4 + }) + }, + { + name: "plane dimensions and segment counts", + data: { + type: "plane", + planeOptions: { ...options, width: 3, height: 5, horizontalSegments: 2, verticalSegments: 4 } + }, + create: () => + PrimitiveMesh.createPlane(engine, { + ...options, + width: 3, + height: 5, + horizontalSegments: 2, + verticalSegments: 4 + }) + }, + { + name: "cylinder caps and range", + data: { + type: "cylinder", + cylinderOptions: { + ...groupedOptions, + caps: PrimitiveMeshCapMode.Bottom, + angleRange: { x: 20, y: 270 }, + radius: 0.75, + height: 3, + radialSegments: 12, + heightSegments: 2 + } + }, + create: () => + PrimitiveMesh.createCylinder(engine, { + ...groupedOptions, + caps: PrimitiveMeshCapMode.Bottom, + angleRange: new Vector2(20, 270), + radius: 0.75, + height: 3, + radialSegments: 12, + heightSegments: 2 + }) + }, + { + name: "truncated cone end radii", + data: { + type: "truncatedCone", + truncatedConeOptions: { + ...groupedOptions, + caps: PrimitiveMeshCapMode.Top, + angleRange: { x: 30, y: 250 }, + topRadius: 0.25, + bottomRadius: 1, + height: 3, + radialSegments: 12, + heightSegments: 2 + } + }, + create: () => + PrimitiveMesh.createTruncatedCone(engine, { + ...groupedOptions, + caps: PrimitiveMeshCapMode.Top, + angleRange: new Vector2(30, 250), + topRadius: 0.25, + bottomRadius: 1, + height: 3, + radialSegments: 12, + heightSegments: 2 + }) + }, + { + name: "cone cap and range", + data: { + type: "cone", + coneOptions: { + ...groupedOptions, + cap: false, + angleRange: { x: 20, y: 270 }, + radius: 0.75, + height: 3, + radialSegments: 12, + heightSegments: 2 + } + }, + create: () => + PrimitiveMesh.createCone(engine, { + ...groupedOptions, + cap: false, + angleRange: new Vector2(20, 270), + radius: 0.75, + height: 3, + radialSegments: 12, + heightSegments: 2 + }) + }, + { + name: "capsule independent segment counts", + data: { + type: "capsule", + capsuleOptions: { ...options, radius: 0.75, height: 3, radialSegments: 12, capSegments: 5, heightSegments: 2 } + }, + create: () => + PrimitiveMesh.createCapsule(engine, { + ...options, + radius: 0.75, + height: 3, + radialSegments: 12, + capSegments: 5, + heightSegments: 2 + }) + }, + { + name: "torus major and tube ranges", + data: { + type: "torus", + torusOptions: { + ...options, + tubeRange: { x: 45, y: 300 }, + angleRange: { x: 20, y: 200 }, + radius: 2, + tubeRadius: 0.25, + tubularSegments: 12, + radialSegments: 8 + } + }, + create: () => + PrimitiveMesh.createTorus(engine, { + ...options, + tubeRange: new Vector2(45, 300), + angleRange: new Vector2(20, 200), + radius: 2, + tubeRadius: 0.25, + tubularSegments: 12, + radialSegments: 8 + }) + }, + { + name: "circle sector", + data: { type: "circle", circleOptions: { ...options, angleRange: { x: 30, y: 240 }, radius: 2, segments: 12 } }, + create: () => + PrimitiveMesh.createCircle(engine, { ...options, angleRange: new Vector2(30, 240), radius: 2, segments: 12 }) + }, + { + name: "ring sector", + data: { + type: "ring", + ringOptions: { + ...options, + angleRange: { x: 40, y: 240 }, + innerRadius: 0.5, + outerRadius: 2, + radialSegments: 12, + widthSegments: 3 + } + }, + create: () => + PrimitiveMesh.createRing(engine, { + ...options, + angleRange: new Vector2(40, 240), + outerRadius: 2, + innerRadius: 0.5, + radialSegments: 12, + widthSegments: 3 + }) + }, + { + name: "ring radius defaults", + data: { type: "ring", ringOptions: { ...options, outerRadius: 2 } }, + create: () => PrimitiveMesh.createRing(engine, { ...options, outerRadius: 2 }) + }, + { + name: "tetrahedron subdivision", + data: { type: "tetrahedron", tetrahedronOptions: { ...options, radius: 2, segments: 3 } }, + create: () => PrimitiveMesh.createTetrahedron(engine, { ...options, radius: 2, segments: 3 }) + }, + { + name: "octahedron subdivision", + data: { type: "octahedron", octahedronOptions: { ...options, radius: 1.5, segments: 2 } }, + create: () => PrimitiveMesh.createOctahedron(engine, { ...options, radius: 1.5, segments: 2 }) + }, + { + name: "icosahedron subdivision", + data: { type: "icosahedron", icosahedronOptions: { ...options, radius: 2, segments: 3 } }, + create: () => PrimitiveMesh.createIcosahedron(engine, { ...options, radius: 2, segments: 3 }) + }, + { + name: "dodecahedron subdivision", + data: { type: "dodecahedron", dodecahedronOptions: { ...options, radius: 1.5, segments: 2 } }, + create: () => PrimitiveMesh.createDodecahedron(engine, { ...options, radius: 1.5, segments: 2 }) + }, + { + name: "lathe profile and range", + data: { + type: "lathe", + latheProfile: profile, + latheOptions: { ...options, angleRange: { x: 30, y: 270 }, segments: 16 } + }, + create: () => + PrimitiveMesh.createLathe(engine, profileVectors, { + ...options, + angleRange: new Vector2(30, 270), + segments: 16 + }) + }, + { + name: "closed tube path", + data: { + type: "tube", + tubePath: path, + tubeOptions: { ...options, closed: true, radius: 0.2, tubularSegments: 16, radialSegments: 6 } + }, + create: () => + PrimitiveMesh.createTube(engine, pathVectors, { + ...options, + closed: true, + radius: 0.2, + tubularSegments: 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: "extrusion", + extrusionShapes: shapes, + extrusionOptions: { + ...groupedOptions, + bevelSize: 0.1, + bevelThickness: 0.2, + bevelOffset: 0.2, + bevelSegments: 2, + depth: 2, + steps: 3 + } + }, + create: () => + PrimitiveMesh.createExtrusion(engine, shapeVectors, { + ...groupedOptions, + bevelSize: 0.1, + bevelThickness: 0.2, + bevelOffset: 0.2, + bevelSegments: 2, + depth: 2, + steps: 3 + }) + }, + { + name: "inset extrusion without bevels", + data: { + type: "extrusion", + extrusionShapes: shapes, + extrusionOptions: { ...options, bevelOffset: -0.1, depth: 2 } + }, + create: () => + PrimitiveMesh.createExtrusion(engine, shapeVectors, { ...options, bevelOffset: -0.1, depth: 2, steps: 1 }) + }, + { + name: "extrusion along a path", + data: { + type: "extrusion", + extrusionShapes: shapes, + extrusionOptions: { ...groupedOptions, path: path, steps: 6 } + }, + create: () => + PrimitiveMesh.createExtrusion(engine, shapeVectors, { ...groupedOptions, path: pathVectors, steps: 6 }) + }, + { + name: "closed extrusion path", + data: { + type: "extrusion", + extrusionShapes: shapes, + extrusionOptions: { ...groupedOptions, closed: true, path: path, steps: 12 } + }, + create: () => + PrimitiveMesh.createExtrusion(engine, shapeVectors, { + ...groupedOptions, + closed: true, + path: pathVectors, + steps: 12 + }) + }, + { + name: "torus knot winding", + data: { + type: "torusKnot", + torusKnotOptions: { ...options, radius: 2, tubeRadius: 0.2, p: 3, q: 4, tubularSegments: 48, radialSegments: 6 } + }, + create: () => + PrimitiveMesh.createTorusKnot(engine, { + ...options, + radius: 2, + tubeRadius: 0.2, + p: 3, + q: 4, + tubularSegments: 48, + radialSegments: 6 + }) + }, + { + name: "negative torus knot windings", + data: { + type: "torusKnot", + torusKnotOptions: { + ...options, + radius: 2, + tubeRadius: 0.2, + p: -2, + q: -3, + tubularSegments: 48, + radialSegments: 8 + } + }, + create: () => + PrimitiveMesh.createTorusKnot(engine, { + ...options, + radius: 2, + tubeRadius: 0.2, + p: -2, + q: -3, + tubularSegments: 48, + radialSegments: 8 + }) + }, + { + name: "rounded cuboid", + data: { + type: "roundedCuboid", + roundedCuboidOptions: { ...groupedOptions, width: 2, height: 3, depth: 4, cornerRadius: 0.2, segments: 3 } + }, + create: () => + PrimitiveMesh.createRoundedCuboid(engine, { + ...groupedOptions, + width: 2, + height: 3, + depth: 4, + cornerRadius: 0.2, + segments: 3 + }) + }, + { + name: "cuboid inherited defaults", + data: { type: "cuboid", cuboidOptions: { width: 2, widthSegments: 3 } }, + create: () => PrimitiveMesh.createCuboid(engine, { width: 2, widthSegments: 3 }) + }, + { + name: "plane inherited defaults", + data: { type: "plane", planeOptions: { width: 2, horizontalSegments: 4 } }, + create: () => PrimitiveMesh.createPlane(engine, { width: 2, horizontalSegments: 4 }) + }, + { + name: "capsule inherited cap segments", + data: { type: "capsule", capsuleOptions: { radialSegments: 10 } }, + create: () => PrimitiveMesh.createCapsule(engine, { 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("converts serialized ranges to Vector2 without modifying the asset", async () => { + const data: PrimitiveMeshAsset = { + type: "sphere", + sphereOptions: { + horizontalRange: { x: 350, y: 370 }, + verticalRange: { 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][1]!; + expect(ranges.horizontalRange).toBeInstanceOf(Vector2); + expect(ranges.verticalRange).toBeInstanceOf(Vector2); + expect(ranges.horizontalRange!.toJSON()).toEqual({ x: 350, y: 370 }); + expect(ranges.verticalRange!.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 data = JSON.parse( + JSON.stringify({ type, [optionsKey]: { caps, keepData: true, separateMaterials: 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(); + } + }); +}); diff --git a/tests/src/spine/SpineAlpha.test.ts b/tests/src/spine/SpineAlpha.test.ts index 8ac3e00353..eb6bdc7675 100644 --- a/tests/src/spine/SpineAlpha.test.ts +++ b/tests/src/spine/SpineAlpha.test.ts @@ -121,7 +121,7 @@ describe("Spine atlas alpha encoding", () => { renderer.entity.destroy(); const meshRenderer = engine.sceneManager.activeScene.createRootEntity().addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 0.1); + meshRenderer.mesh = PrimitiveMesh.createCuboid(engine, { width: 2, height: 2, depth: 0.1 }); const material = new UnlitMaterial(engine); material.baseColor.set(0, 1, 0, 1); meshRenderer.setMaterial(material); From 121dd6fe793f19f092434b078a077a88f9900de5 Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sat, 14 Nov 2026 20:35:32 +0800 Subject: [PATCH 02/24] refactor(core): simplify extrusion options Keep linear and path extrusion settings as independent interfaces and use their union directly in createExtrusion. Remove the combined options alias and forbidden fields, following normal TypeScript structural compatibility. Document which settings apply to each mode, ignore closed without a path, and update serialized loading, consumer fixtures and regression coverage. --- docs/en/graphics/mesh/primitiveMesh.mdx | 4 +- docs/zh/graphics/mesh/primitiveMesh.mdx | 4 +- packages/core/src/mesh/PrimitiveMesh.ts | 12 ++++-- .../core/src/mesh/PrimitiveMeshOptions.ts | 33 ---------------- packages/core/src/mesh/index.ts | 1 - .../references/mesh-geometry.md | 4 +- packages/loader/src/PrimitiveMeshLoader.ts | 2 +- .../fixtures/PrimitiveMeshApi.ts | 14 +++---- .../fixtures/PrimitiveMeshAsset.ts | 4 -- tests/src/core/mesh/ProceduralMesh.test.ts | 39 +++++++++++++++++++ tests/src/loader/PrimitiveMeshLoader.test.ts | 28 +++++++++++++ 11 files changed, 89 insertions(+), 56 deletions(-) diff --git a/docs/en/graphics/mesh/primitiveMesh.mdx b/docs/en/graphics/mesh/primitiveMesh.mdx index 9af04d7a1f..b44e042054 100644 --- a/docs/en/graphics/mesh/primitiveMesh.mdx +++ b/docs/en/graphics/mesh/primitiveMesh.mdx @@ -203,7 +203,7 @@ const loop = [new Vector3(-4, 0, -4), new Vector3(4, 0, -4), new Vector3(4, 0, 4 const closed = PrimitiveMesh.createExtrusion(engine, outline, { closed: true, path: loop, steps: 32 }); ``` -Extrusion uses `LinearExtrusionMeshOptions` for `depth` and bevels, or `PathExtrusionMeshOptions` with a required `path`. TypeScript rejects combinations of a path with depth or bevel settings. The default extrusion goes along +Z without bevels. A positive `bevelSize` enables beveling; `bevelThickness` defaults to the same value. Path extrusion does not generate bevels. Paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points before creating the mesh, as shown above. +Extrusion uses `LinearExtrusionMeshOptions` for `depth` and bevels, or `PathExtrusionMeshOptions` with a required `path`. Each interface declares the settings for its mode. Providing `path` selects path extrusion; depth and bevel settings are ignored in that mode. Without a path, `closed` is ignored. The default extrusion goes along +Z without bevels. A positive `bevelSize` enables beveling; `bevelThickness` defaults to the same value. Path extrusion does not generate bevels. Paths accept `Vector3` arrays and 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, `closed` 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 steps and have no end caps. Open extrusions have two end caps; tubes have no end caps in either mode. @@ -299,6 +299,6 @@ Profiles and polygon contours store `{ x, y }` points; paths store `{ x, y, z }` } ``` -Path extrusion uses `extrusionOptions.path` in place of `extrusionOptions.depth` and does not accept bevel options. Set `extrusionOptions.closed` to `true` for a closed path without end caps. Save path points as `{ x, y, z }`. +Path extrusion uses `extrusionOptions.path` and ignores depth and bevel settings. Set `extrusionOptions.closed` to `true` for a closed path without end caps. Save path points as `{ x, y, z }`. The type-prefixed fields, including `Options`, pass through the Editor's primitive asset bundler. Editor previews should select the same creation method and parameters as the saved asset. diff --git a/docs/zh/graphics/mesh/primitiveMesh.mdx b/docs/zh/graphics/mesh/primitiveMesh.mdx index 85383e639f..4016f27313 100644 --- a/docs/zh/graphics/mesh/primitiveMesh.mdx +++ b/docs/zh/graphics/mesh/primitiveMesh.mdx @@ -209,7 +209,7 @@ const loop = [new Vector3(-4, 0, -4), new Vector3(4, 0, -4), new Vector3(4, 0, 4 const closed = PrimitiveMesh.createExtrusion(engine, outline, { closed: true, path: loop, steps: 32 }); ``` -拉伸配置分为 `LinearExtrusionMeshOptions` 和 `PathExtrusionMeshOptions`:前者指定 `depth` 与倒角,后者必须指定 `path`。TypeScript 会拒绝同时传入路径与深度或倒角的组合。默认沿 +Z 直线拉伸且不倒角;`bevelSize > 0` 时开启倒角,`bevelThickness` 默认等于 `bevelSize`。沿路径拉伸不生成倒角。路径接收 `Vector3` 数组,并按折线长度均匀采样。使用曲线时,在外层采样成点数组后传入,如上例所示。 +拉伸配置分为 `LinearExtrusionMeshOptions` 和 `PathExtrusionMeshOptions`:前者指定 `depth` 与倒角,后者必须指定 `path`。两个接口分别声明各自模式的设置。提供 `path` 时选择路径挤出,忽略深度和倒角设置;未提供路径时忽略 `closed`。默认沿 +Z 直线拉伸且不倒角;`bevelSize > 0` 时开启倒角,`bevelThickness` 默认等于 `bevelSize`。沿路径拉伸不生成倒角。路径接收 `Vector3` 数组,并按折线长度均匀采样。使用曲线时,在外层采样成点数组后传入,如上例所示。 管道和路径挤出的 `closed` 默认关闭;开启后自动连接路径首尾并对齐截面,不必重复首点。闭合挤出至少使用三段,不生成端盖。开放挤出保留两端端盖;管道在两种模式下都不生成端盖。 @@ -305,6 +305,6 @@ const asset = { } ``` -沿路径拉伸使用 `extrusionOptions.path` 替代 `extrusionOptions.depth`,不接受倒角选项。`extrusionOptions.closed` 设为 `true` 时闭合路径且不生成端盖。路径点保存为 `{ x, y, z }`。 +沿路径拉伸使用 `extrusionOptions.path`,忽略深度和倒角设置。`extrusionOptions.closed` 设为 `true` 时闭合路径且不生成端盖。路径点保存为 `{ x, y, z }`。 以上类型前缀字段及 `Options` 都能经过 Editor 现有的基础网格打包过滤。Editor 预览应使用与保存资产相同的创建方法和参数。 diff --git a/packages/core/src/mesh/PrimitiveMesh.ts b/packages/core/src/mesh/PrimitiveMesh.ts index b943b0f632..aa523c4792 100644 --- a/packages/core/src/mesh/PrimitiveMesh.ts +++ b/packages/core/src/mesh/PrimitiveMesh.ts @@ -20,7 +20,8 @@ import type { LatheMeshOptions, TubeMeshOptions, PolygonMeshOptions, - ExtrusionMeshOptions, + LinearExtrusionMeshOptions, + PathExtrusionMeshOptions, TorusKnotMeshOptions, RoundedCuboidMeshOptions, PolygonShape @@ -533,6 +534,9 @@ export class PrimitiveMesh { /** * Extrude polygons along +Z or a spatial path. + * @remarks + * Providing `path` selects path extrusion and ignores depth and bevel settings. + * Without a path, extrusion follows +Z and ignores `closed`. * @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 - Linear or path extrusion settings @@ -541,7 +545,7 @@ export class PrimitiveMesh { static createExtrusion( engine: Engine, shapes: readonly Vector2[] | PolygonShape | readonly PolygonShape[], - options: ExtrusionMeshOptions = {} + options: LinearExtrusionMeshOptions | PathExtrusionMeshOptions = {} ): ModelMesh { const { depth = 1, @@ -552,7 +556,7 @@ export class PrimitiveMesh { bevelThickness = bevelSize, bevelOffset = 0, bevelSegments = 3 - } = options; + }: LinearExtrusionMeshOptions & Partial = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createExtrusionData, @@ -561,7 +565,7 @@ export class PrimitiveMesh { depth, steps, path, - closed, + path ? closed : false, bevelThickness, bevelSize, bevelOffset, diff --git a/packages/core/src/mesh/PrimitiveMeshOptions.ts b/packages/core/src/mesh/PrimitiveMeshOptions.ts index e9dc7243ef..f30f385741 100644 --- a/packages/core/src/mesh/PrimitiveMeshOptions.ts +++ b/packages/core/src/mesh/PrimitiveMeshOptions.ts @@ -490,14 +490,6 @@ export interface LinearExtrusionMeshOptions extends PrimitiveMeshOptions { * @defaultValue `false` */ separateMaterials?: boolean; - /** - * A path selects path extrusion, which cannot be combined with depth or bevel settings. - */ - path?: never; - /** - * Closing is only available for path extrusion. - */ - closed?: never; } /** @@ -526,33 +518,8 @@ export interface PathExtrusionMeshOptions extends PrimitiveMeshOptions { * @defaultValue `false` */ separateMaterials?: boolean; - /** - * Depth is determined by the path. - */ - depth?: never; - /** - * Path extrusion does not support bevels. - */ - bevelSize?: never; - /** - * Path extrusion does not support bevels. - */ - bevelThickness?: never; - /** - * Path extrusion does not support contour offsets. - */ - bevelOffset?: never; - /** - * Path extrusion does not support bevels. - */ - bevelSegments?: never; } -/** - * Settings for linear extrusion or path extrusion. Providing `path` selects path extrusion. - */ -export type ExtrusionMeshOptions = LinearExtrusionMeshOptions | PathExtrusionMeshOptions; - /** * Settings for a closed torus knot. At least one of `p` and `q` must be nonzero. */ diff --git a/packages/core/src/mesh/index.ts b/packages/core/src/mesh/index.ts index 7329a57fc7..a04efc11e3 100644 --- a/packages/core/src/mesh/index.ts +++ b/packages/core/src/mesh/index.ts @@ -20,7 +20,6 @@ export type { LatheMeshOptions, TubeMeshOptions, PolygonMeshOptions, - ExtrusionMeshOptions, TorusKnotMeshOptions, RoundedCuboidMeshOptions, PolygonShape, diff --git a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md index 9a5868478d..af10fe1c48 100644 --- a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md +++ b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md @@ -63,7 +63,7 @@ Angles use degrees. Ranges use `Vector2`, with `x` as the start angle and `y` as `createSphere(engine, { radius, subdivisions, horizontalRange, verticalRange })` projects a subdivided cube onto a sphere. The subdivision level defaults to 3 and is clamped to 1 through 6. It accepts `horizontalRange` and `verticalRange`. These clip the subdivided surface and leave open boundaries. Horizontal angles start at -X towards +Z, and vertical angles start at +Y. Continuous horizontal intervals such as `new Vector2(350, 370)` cross the seam. Complete spheres and sections use the same subdivision level. -Additional generators include circle, ring, four regular polyhedra, lathe, tube, polygon, extrusion, torus knot and rounded cuboid. Angle ranges belong to options. A ring's omitted `innerRadius` is half its `outerRadius`. Contours and lathe profiles use `Vector2` arrays; paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points outside the mesh API. A simple polygon is a point array; holes use `{ points, holes }`. Extrusion takes `LinearExtrusionMeshOptions` with optional `depth`, or `PathExtrusionMeshOptions` with a required `path`. These types reject combining paths with depth or bevel settings, including through variables. Straight extrusion defaults to no bevel; a positive `bevelSize` enables it, with `bevelThickness` defaulting to the same value. Path extrusion has no bevels. +Additional generators include circle, ring, four regular polyhedra, lathe, tube, polygon, extrusion, torus knot and rounded cuboid. Angle ranges belong to options. A ring's omitted `innerRadius` is half its `outerRadius`. Contours and lathe profiles use `Vector2` arrays; paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points outside the mesh API. A simple polygon is a point array; holes use `{ points, holes }`. Extrusion takes `LinearExtrusionMeshOptions` with optional `depth`, or `PathExtrusionMeshOptions` with a required `path`. Each interface declares only its mode's settings. Providing `path` selects path extrusion and ignores depth and bevel settings; without a path, `closed` is ignored. Straight extrusion defaults to no bevel; a positive `bevelSize` enables it, with `bevelThickness` defaulting to the same value. Path extrusion has no bevels. For straight extrusion, `bevelOffset` shifts the side-wall outline and defaults to `0`. Positive values expand the solid and contract holes; negative values do the reverse. The offset also applies when `bevelSize` is `0`. Bevels are cut into the shifted outline and included in the total `depth`. @@ -79,4 +79,4 @@ JSON keeps the type prefix for geometry inputs and the options object: `{ type: TypeScript assets use `PrimitiveMeshCapMode` for `caps`; JSON stores its string values `"both"`, `"top"`, `"bottom"`, `"none"`. -Serialized profiles and contours use `{ x, y }`; paths use `{ x, y, z }`. `polygonShapes` and `extrusionShapes` are arrays of `{ points, holes? }`. Straight extrusion uses `extrusionOptions.depth`; path extrusion uses `extrusionOptions.path` and has no bevel options. Set `extrusionOptions.closed` to `true` for a closed path without end caps. Editor previews and saved assets must select the same factory and parameters. +Serialized profiles and contours use `{ x, y }`; paths use `{ x, y, z }`. `polygonShapes` and `extrusionShapes` are arrays of `{ points, holes? }`. Straight extrusion uses `extrusionOptions.depth`; path extrusion uses `extrusionOptions.path` and ignores depth and bevel settings. Set `extrusionOptions.closed` to `true` for a closed path without end caps. Editor previews and saved assets must select the same factory and parameters. diff --git a/packages/loader/src/PrimitiveMeshLoader.ts b/packages/loader/src/PrimitiveMeshLoader.ts index 25b7bb4b46..004e1e501d 100644 --- a/packages/loader/src/PrimitiveMeshLoader.ts +++ b/packages/loader/src/PrimitiveMeshLoader.ts @@ -68,7 +68,7 @@ class PrimitiveMeshLoader extends Loader { return PrimitiveMesh.createExtrusion( engine, shapes, - options?.path ? { ...options, path: this._parseVector3s(options.path) } : options + options && "path" in options ? { ...options, path: this._parseVector3s(options.path) } : options ); } case "torusKnot": diff --git a/tests/package-consumer/fixtures/PrimitiveMeshApi.ts b/tests/package-consumer/fixtures/PrimitiveMeshApi.ts index 6bae877870..40e3557257 100644 --- a/tests/package-consumer/fixtures/PrimitiveMeshApi.ts +++ b/tests/package-consumer/fixtures/PrimitiveMeshApi.ts @@ -5,7 +5,6 @@ import type { ConeMeshOptions, CuboidMeshOptions, CylinderMeshOptions, - ExtrusionMeshOptions, LatheMeshOptions, LinearExtrusionMeshOptions, PathExtrusionMeshOptions, @@ -151,7 +150,7 @@ const pathExtrusionOptions = { separateMaterials: true, keepData: true } satisfies PathExtrusionMeshOptions; -const extrusionOptions: ExtrusionMeshOptions = pathExtrusionOptions; +const extrusionOptions: LinearExtrusionMeshOptions | PathExtrusionMeshOptions = pathExtrusionOptions; const torusKnotOptions = { radius: 1, tubeRadius: 0.2, @@ -266,22 +265,23 @@ PrimitiveMesh.createCylinder(engine, { caps: "left" }); PrimitiveMesh.createCylinder(engine, { caps: "top" }); // @ts-expect-error Truncated cones use the same cap-mode enum PrimitiveMesh.createTruncatedCone(engine, { caps: "none" }); -// @ts-expect-error Path extrusion does not support bevels +// Extra fields from the other mode follow normal structural compatibility PrimitiveMesh.createExtrusion(engine, polygon, { path, bevelSize: 0.1 }); -// @ts-expect-error Path extrusion does not support contour offsets PrimitiveMesh.createExtrusion(engine, polygon, { path, bevelOffset: 0.1 }); -// @ts-expect-error Only path extrusion can be closed PrimitiveMesh.createExtrusion(engine, polygon, { depth: 2, closed: true }); // @ts-expect-error Bevel offsets use numeric local units PrimitiveMesh.createExtrusion(engine, polygon, { bevelOffset: "0.1" }); const mixedExtrusion = { path, depth: 2 }; -// @ts-expect-error Incompatible extrusion settings are rejected through variables too PrimitiveMesh.createExtrusion(engine, polygon, mixedExtrusion); const beveledPath = { path, bevelSize: 0.1 }; -// @ts-expect-error Variables cannot combine paths with bevels PrimitiveMesh.createExtrusion(engine, polygon, beveledPath); +// @ts-expect-error Explicit linear settings do not declare a path +const invalidLinearOptions: LinearExtrusionMeshOptions = { path }; +// @ts-expect-error Explicit path settings do not declare bevels +const invalidPathOptions: PathExtrusionMeshOptions = { path, bevelSize: 0.1 }; + const samplePath = (t: number, out: Vector3): void => { out.set(t, t * t, 0); }; diff --git a/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts index ab76d95ec7..c95daba611 100644 --- a/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts +++ b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts @@ -72,25 +72,21 @@ const missingShapes: PrimitiveMeshAsset = { type: "polygon" }; const mixedExtrusion: PrimitiveMeshAsset = { type: "extrusion", extrusionShapes: shapes, - // @ts-expect-error An extrusion uses either a depth or a path extrusionOptions: { depth: 2, path: path } }; const beveledPath: PrimitiveMeshAsset = { type: "extrusion", extrusionShapes: shapes, - // @ts-expect-error Path extrusion does not support bevels extrusionOptions: { bevelSize: 1, path: path } }; const offsetPath: PrimitiveMeshAsset = { type: "extrusion", extrusionShapes: shapes, - // @ts-expect-error Path extrusion does not support contour offsets extrusionOptions: { bevelOffset: 0.1, path: path } }; const closedDepth: PrimitiveMeshAsset = { type: "extrusion", extrusionShapes: shapes, - // @ts-expect-error Only path extrusion can be closed extrusionOptions: { closed: true, depth: 2 } }; // @ts-expect-error Shape options cannot be applied to another primitive diff --git a/tests/src/core/mesh/ProceduralMesh.test.ts b/tests/src/core/mesh/ProceduralMesh.test.ts index 1939c20cc9..4924070472 100644 --- a/tests/src/core/mesh/ProceduralMesh.test.ts +++ b/tests/src/core/mesh/ProceduralMesh.test.ts @@ -1734,6 +1734,45 @@ describe("procedural mesh geometry", () => { } }); + it("ignores settings from the inactive extrusion mode", () => { + const linearOptions = { keepData: true, depth: 2, steps: 2, bevelSize: 0.1, separateMaterials: true }; + const pathOptions = { keepData: true, path, steps: 5, separateMaterials: true }; + const pairs = [ + [ + PrimitiveMesh.createExtrusion(engine, polygon, linearOptions), + PrimitiveMesh.createExtrusion(engine, polygon, { ...linearOptions, closed: true }) + ], + [ + PrimitiveMesh.createExtrusion(engine, polygon, pathOptions), + PrimitiveMesh.createExtrusion(engine, polygon, { + ...pathOptions, + depth: 7, + bevelSize: 0.25, + bevelThickness: 0.4, + bevelOffset: 0.5, + bevelSegments: 8 + }) + ] + ]; + 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 steps 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)]; diff --git a/tests/src/loader/PrimitiveMeshLoader.test.ts b/tests/src/loader/PrimitiveMeshLoader.test.ts index d6fcd82adf..fd2cadbe05 100644 --- a/tests/src/loader/PrimitiveMeshLoader.test.ts +++ b/tests/src/loader/PrimitiveMeshLoader.test.ts @@ -451,6 +451,34 @@ describe("PrimitiveMeshLoader", () => { steps: 12 }) }, + { + name: "linear extrusion ignores path-only settings", + data: { + type: "extrusion", + extrusionShapes: shapes, + extrusionOptions: { ...groupedOptions, depth: 2, steps: 2, closed: true } + }, + create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors, { ...groupedOptions, depth: 2, steps: 2 }) + }, + { + name: "path extrusion ignores linear-only settings", + data: { + type: "extrusion", + extrusionShapes: shapes, + extrusionOptions: { + ...groupedOptions, + path, + steps: 6, + depth: 7, + bevelSize: 0.25, + bevelThickness: 0.4, + bevelOffset: 0.5, + bevelSegments: 8 + } + }, + create: () => + PrimitiveMesh.createExtrusion(engine, shapeVectors, { ...groupedOptions, path: pathVectors, steps: 6 }) + }, { name: "torus knot winding", data: { From 2d809e631fbd304eb2ab7958678652835b1d12d6 Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sat, 14 Nov 2026 20:59:51 +0800 Subject: [PATCH 03/24] refactor(core): require primitive shape inputs Separate required dimensions, radii and shape data from optional generation settings across all primitive factories. Align serialized assets, loaders, examples and API contract coverage. BREAKING CHANGE: Primitive factories require explicit shape inputs before options. Primitive assets require matching type-prefixed input fields. --- README.md | 2 +- docs/en/graphics/background/sky.mdx | 2 +- docs/en/graphics/mesh/primitiveMesh.mdx | 104 ++-- docs/en/graphics/renderer/meshRenderer.mdx | 2 +- docs/zh/graphics/background/sky.mdx | 2 +- docs/zh/graphics/mesh/primitiveMesh.mdx | 102 ++-- docs/zh/graphics/renderer/meshRenderer.mdx | 2 +- e2e/case/.initPostProcessEnv.ts | 2 +- e2e/case/camera-opaque-texture.ts | 2 +- e2e/case/camera-ssao.ts | 8 +- e2e/case/canvas-transparency.ts | 6 +- e2e/case/gpu-instancing-custom-data.ts | 2 +- e2e/case/material-LUT.ts | 2 +- e2e/case/material-white-furnace.ts | 2 +- e2e/case/multi-camera-no-clear.ts | 4 +- e2e/case/multi-scene-clear.ts | 4 +- e2e/case/multi-scene-no-clear.ts | 4 +- ...rticleRenderer-emit-billboard-stretched.ts | 2 +- ...sh-cone-scale-3d-rotation-life-seperate.ts | 4 +- ...nderer-emit-mesh-cone-scale-3d-rotation.ts | 4 +- ...-mesh-cone-scale-rotation-life-seperate.ts | 4 +- ...erer-emit-mesh-cone-scale-rotation-life.ts | 4 +- ...rer-emit-mesh-cone-scale-rotation-world.ts | 4 +- ...eRenderer-emit-mesh-cone-scale-rotation.ts | 4 +- e2e/case/particleRenderer-emit-mesh-cone.ts | 4 +- ...rticleRenderer-emit-mesh-no-shape-world.ts | 4 +- .../particleRenderer-emit-mesh-no-shape.ts | 4 +- ...leRenderer-emit-mesh-size-over-lifetime.ts | 2 +- e2e/case/physx-collision-group.ts | 8 +- e2e/case/physx-collision.ts | 4 +- e2e/case/physx-customUrl.ts | 4 +- e2e/case/physx-deferred-contact.ts | 2 +- e2e/case/physx-mesh-collider.ts | 2 +- e2e/case/primitive-all.ts | 77 +-- e2e/case/primitive-capsule.ts | 2 +- e2e/case/primitive-cone.ts | 2 +- e2e/case/primitive-contours.ts | 24 +- e2e/case/primitive-cuboid.ts | 2 +- e2e/case/primitive-cylinder.ts | 2 +- e2e/case/primitive-materials.ts | 23 +- e2e/case/primitive-plane.ts | 2 +- e2e/case/primitive-sections.ts | 31 +- e2e/case/primitive-sphere-sections.ts | 7 +- e2e/case/primitive-sphere.ts | 2 +- e2e/case/primitive-topology.ts | 56 +- e2e/case/primitive-torus.ts | 2 +- e2e/case/shader-mrt.ts | 2 +- e2e/case/shader-renderState.ts | 4 +- e2e/case/shadow-basic.ts | 2 +- e2e/case/shadow-transparent.ts | 2 +- e2e/case/texture-R8G8.ts | 2 +- e2e/case/texture-hdr-ktx2.ts | 2 +- e2e/case/texture-hdr.ts | 2 +- e2e/case/texture-sRGB-KTX2.ts | 2 +- examples/src/gltf-loader.ts | 2 +- examples/src/gpu-instancing-auto-batch.ts | 2 +- examples/src/gpu-instancing-custom-data.ts | 2 +- examples/src/paricle-emit-mesh.ts | 4 +- examples/src/shader-01-basic-shader.ts | 2 +- examples/src/shader-02-render-state.ts | 2 +- examples/src/shader-03-ui-script.ts | 2 +- examples/src/shader-04-multi-pass.ts | 2 +- packages/core/src/mesh/PrimitiveMesh.ts | 224 ++++---- .../core/src/mesh/PrimitiveMeshOptions.ts | 163 +----- packages/galacean/README.md | 2 +- .../references/mesh-geometry.md | 46 +- packages/loader/src/PrimitiveMeshAsset.ts | 153 ++++- packages/loader/src/PrimitiveMeshLoader.ts | 90 ++- .../package-consumer/PrimitiveMeshApi.test.ts | 25 +- .../fixtures/PrimitiveMeshApi.ts | 316 ++++++----- .../fixtures/PrimitiveMeshAsset.ts | 98 +++- tests/src/core/DeviceLost.test.ts | 2 +- tests/src/core/Light.test.ts | 2 +- tests/src/core/MeshRenderer.test.ts | 4 +- tests/src/core/Shader.test.ts | 4 +- tests/src/core/ShaderIdentity.test.ts | 2 +- tests/src/core/mesh/BlendShape.test.ts | 2 +- tests/src/core/mesh/BlendShapeManager.test.ts | 15 +- tests/src/core/mesh/PrimitiveMesh.test.ts | 40 +- tests/src/core/mesh/ProceduralMesh.test.ts | 525 +++++------------- .../core/particle/ParticleRenderer.test.ts | 8 +- .../core/particle/SizeOverLifetime.test.ts | 2 +- tests/src/core/particle/SubEmitter.test.ts | 2 +- .../core/particle/SubEmitterRendering.test.ts | 2 +- tests/src/core/physics/ColliderLayer.test.ts | 5 +- .../core/physics/MeshColliderLayer.test.ts | 5 +- tests/src/loader/PrimitiveMeshLoader.test.ts | 351 ++++++------ tests/src/spine/SpineAlpha.test.ts | 2 +- 88 files changed, 1245 insertions(+), 1425 deletions(-) diff --git a/README.md b/README.md index 62397da938..0013443a68 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ const meshEntity = rootEntity.createChild("Sphere"); const meshRenderer = meshEntity.addComponent(MeshRenderer); const material = new BlinnPhongMaterial(engine); meshRenderer.setMaterial(material); -meshRenderer.mesh = PrimitiveMesh.createSphere(engine, { radius: 1 }); +meshRenderer.mesh = PrimitiveMesh.createSphere(engine, 1); // Run engine engine.run(); diff --git a/docs/en/graphics/background/sky.mdx b/docs/en/graphics/background/sky.mdx index e72d673465..dfaf6bff67 100644 --- a/docs/en/graphics/background/sky.mdx +++ b/docs/en/graphics/background/sky.mdx @@ -49,7 +49,7 @@ 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); ``` ### Properties diff --git a/docs/en/graphics/mesh/primitiveMesh.mdx b/docs/en/graphics/mesh/primitiveMesh.mdx index b44e042054..d189fd7634 100644 --- a/docs/en/graphics/mesh/primitiveMesh.mdx +++ b/docs/en/graphics/mesh/primitiveMesh.mdx @@ -44,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); @@ -57,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); @@ -70,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); @@ -83,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); @@ -96,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); @@ -109,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); @@ -122,7 +122,7 @@ 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); @@ -131,21 +131,21 @@ renderer.setMaterial(material); ## Procedural geometry -Each factory accepts one named options object. Every options type documents its fields, units and defaults. Omit the object to use all defaults, or specify only the fields you need. For example, `createSphere` accepts `SphereMeshOptions`: +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 unitSphere = PrimitiveMesh.createSphere(engine); -const sphere = PrimitiveMesh.createSphere(engine, { radius: 1 }); -const smoothSphere = PrimitiveMesh.createSphere(engine, { radius: 1, subdivisions: 4 }); -const cube = PrimitiveMesh.createCuboid(engine, { width: 2 }); -const box = PrimitiveMesh.createCuboid(engine, { width: 2, height: 3, depth: 4 }); -const ground = PrimitiveMesh.createPlane(engine, { width: 10 }); -const cylinder = PrimitiveMesh.createCylinder(engine, { radius: 0.5, height: 2 }); -const frustum = PrimitiveMesh.createTruncatedCone(engine, { topRadius: 0.25, bottomRadius: 0.5, height: 2 }); -const mirroredKnot = PrimitiveMesh.createTorusKnot(engine, { radius: 1, tubeRadius: 0.1, p: 2, q: -3 }); +const unitSphere = PrimitiveMesh.createSphere(engine, 0.5); +const sphere = PrimitiveMesh.createSphere(engine, 1); +const smoothSphere = PrimitiveMesh.createSphere(engine, 1, { subdivisions: 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 height and depth default to its width. Plane height defaults to its width. 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 outer radius first; the inner radius defaults to half the outer radius. +Cuboid width, height and depth are separate required arguments. Plane width and height 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, `p` and `q` are signed integer revolution counts, independent of mesh subdivisions. Negative values reverse the corresponding winding direction; zero keeps that angle fixed. @@ -159,17 +159,17 @@ For torus knots, `p` and `q` are signed integer revolution counts, independent o ### Subdivisions, angles and caps -Dimensions and subdivisions are named fields in the same options object. For tubes and tori, `tubularSegments` controls longitudinal subdivisions and `radialSegments` controls the cross-section. Capsule `capSegments` controls each pole-to-equator section independently; its height describes the cylindrical section. +Dimensions are required arguments; subdivision counts remain in the optional settings object. For tubes and tori, `tubularSegments` controls longitudinal subdivisions and `radialSegments` controls the cross-section. Capsule `capSegments` controls each pole-to-equator section independently; its height describes the cylindrical section. 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, cones and lathes rotate around Y starting from +Z; a sphere's vertical angle starts at +Y. ```ts import { PrimitiveMeshCapMode, Vector2 } from "@galacean/engine"; -const hemisphere = PrimitiveMesh.createSphere(engine, { verticalRange: new Vector2(0, 90), radius: 1 }); -const openCylinder = PrimitiveMesh.createCylinder(engine, { caps: PrimitiveMeshCapMode.None, radius: 0.5, height: 2 }); -const cupWall = PrimitiveMesh.createCylinder(engine, { caps: PrimitiveMeshCapMode.Bottom, radius: 0.5, height: 2 }); -const halfRing = PrimitiveMesh.createRing(engine, { angleRange: new Vector2(0, 180), outerRadius: 1, innerRadius: 0.5 }); +const hemisphere = PrimitiveMesh.createSphere(engine, 1, { verticalRange: 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. @@ -186,24 +186,19 @@ import { Vector2, Vector3 } from "@galacean/engine"; 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.createExtrusion(engine, { points: outline, holes: [hole] }, { depth: 0.5 }); -const beveled = PrimitiveMesh.createExtrusion(engine, outline, { - bevelSize: 0.05, - bevelOffset: 0.02, - depth: 0.5, - steps: 1 -}); +const solid = PrimitiveMesh.createExtrusion(engine, { points: outline, holes: [hole] }, 0.5); +const beveled = PrimitiveMesh.createExtrusion(engine, outline, 0.5, { bevelSize: 0.05, bevelOffset: 0.02, steps: 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, { radius: 0.1, tubularSegments: 64 }); -const swept = PrimitiveMesh.createExtrusion(engine, outline, { path: path, steps: 64 }); +const tube = PrimitiveMesh.createTube(engine, path, 0.1, { tubularSegments: 64 }); +const swept = PrimitiveMesh.createExtrusion(engine, outline, path, { steps: 64 }); const loop = [new Vector3(-4, 0, -4), new Vector3(4, 0, -4), new Vector3(4, 0, 4), new Vector3(-4, 0, 4)]; -const closed = PrimitiveMesh.createExtrusion(engine, outline, { closed: true, path: loop, steps: 32 }); +const closed = PrimitiveMesh.createExtrusion(engine, outline, loop, { closed: true, steps: 32 }); ``` -Extrusion uses `LinearExtrusionMeshOptions` for `depth` and bevels, or `PathExtrusionMeshOptions` with a required `path`. Each interface declares the settings for its mode. Providing `path` selects path extrusion; depth and bevel settings are ignored in that mode. Without a path, `closed` is ignored. The default extrusion goes along +Z without bevels. A positive `bevelSize` enables beveling; `bevelThickness` defaults to the same value. Path extrusion does not generate bevels. Paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points before creating the mesh, as shown above. +Extrusion requires a third argument: a numeric depth for linear extrusion, or a `Vector3` array for path extrusion. `LinearExtrusionMeshOptions` contains optional bevel settings; `PathExtrusionMeshOptions` contains optional path settings. Each interface declares its mode's settings. A path ignores bevel settings; a numeric depth ignores `closed`. Linear extrusion goes along +Z without bevels unless requested. A positive `bevelSize` enables beveling; `bevelThickness` defaults to the same value. Path extrusion does not generate bevels. Paths accept `Vector3` arrays and 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, `closed` 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 steps and have no end caps. Open extrusions have two end caps; tubes have no end caps in either mode. @@ -211,15 +206,12 @@ For tubes and path extrusions, `closed` defaults to `false`. Set it to `true` to ### Mesh data and materials -Mesh settings belong to the same options object as dimensions and subdivisions: +Mesh settings and subdivision counts belong to the optional settings object: ```ts -const editable = PrimitiveMesh.createSphere(engine, { keepData: true, radius: 1, subdivisions: 3 }); -const sixMaterials = PrimitiveMesh.createCuboid(engine, { +const editable = PrimitiveMesh.createSphere(engine, 1, { keepData: true, subdivisions: 3 }); +const sixMaterials = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { separateMaterials: true, - width: 1, - height: 1, - depth: 1, widthSegments: 1, heightSegments: 1, depthSegments: 1 @@ -253,24 +245,31 @@ import type { PrimitiveMeshAsset } from "@galacean/engine"; const asset = { type: "sphere", - sphereOptions: { radius: 1, subdivisions: 3, keepData: true } + sphereRadius: 1, + sphereOptions: { subdivisions: 3, keepData: true } } satisfies PrimitiveMeshAsset; ``` -Each `type` selects the matching `PrimitiveMesh.createX` method. `Options` follows that factory's named fields and defaults. 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 fields use the creation API's defaults, including defaults derived from another field. Angles remain in degrees. +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. -| Asset types | Required geometry fields | +| Asset type | Required geometry fields | | --- | --- | -| `sphere`, `cuboid`, `plane` | None | -| `cylinder`, `truncatedCone`, `cone`, `capsule` | None | -| `torus`, `circle`, `ring`, `torusKnot`, `roundedCuboid` | None | -| `tetrahedron`, `octahedron`, `icosahedron`, `dodecahedron` | None | +| `sphere`, `circle` | `Radius` | +| `cuboid` | `cuboidWidth`, `cuboidHeight`, `cuboidDepth` | +| `plane` | `planeWidth`, `planeHeight` | +| `cylinder`, `cone`, `capsule` | `Radius`, `Height` | +| `truncatedCone` | `truncatedConeTopRadius`, `truncatedConeBottomRadius`, `truncatedConeHeight` | +| `torus` | `torusRadius`, `torusTubeRadius` | +| `ring` | `ringOuterRadius`, `ringInnerRadius` | +| `tetrahedron`, `octahedron`, `icosahedron`, `dodecahedron` | `Radius` | | `lathe` | `latheProfile` | -| `tube` | `tubePath` | +| `tube` | `tubePath`, `tubeRadius` | | `polygon` | `polygonShapes` | -| `extrusion` | `extrusionShapes`; optional `extrusionOptions.depth` or `extrusionOptions.path` | +| `extrusion` | `extrusionShapes`, plus `extrusionDepth` or `extrusionPath` | +| `torusKnot` | `torusKnotRadius`, `torusKnotTubeRadius`, `torusKnotP`, `torusKnotQ` | +| `roundedCuboid` | `roundedCuboidWidth`, `roundedCuboidHeight`, `roundedCuboidDepth`, `roundedCuboidCornerRadius` | -`sphere` creates a subdivided cube projected onto a sphere; `sphereOptions.subdivisions` controls its subdivision level. `cylinder` has one radius; `truncatedCone` has independent `truncatedConeOptions.topRadius` and `truncatedConeOptions.bottomRadius`. +`sphere` creates a subdivided cube projected onto a sphere; `sphereOptions.subdivisions` 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`: @@ -295,10 +294,11 @@ Profiles and polygon contours store `{ x, y }` points; paths store `{ x, y, z }` ] } ], - "extrusionOptions": { "depth": 2, "bevelSize": 0.1, "bevelOffset": 0.2, "separateMaterials": true } + "extrusionDepth": 2, + "extrusionOptions": { "bevelSize": 0.1, "bevelOffset": 0.2, "separateMaterials": true } } ``` -Path extrusion uses `extrusionOptions.path` and ignores depth and bevel settings. Set `extrusionOptions.closed` to `true` for a closed path without end caps. Save path points as `{ x, y, z }`. +Path extrusion uses the required `extrusionPath` field instead of `extrusionDepth` and ignores bevel settings. Set `extrusionOptions.closed` to `true` for a closed path without end caps. Save path points as `{ x, y, z }`. The type-prefixed fields, including `Options`, pass through the Editor's primitive asset bundler. Editor previews should select the same creation method and parameters as the saved asset. diff --git a/docs/en/graphics/renderer/meshRenderer.mdx b/docs/en/graphics/renderer/meshRenderer.mdx index 1a4b24e2e6..af4226e3b1 100644 --- a/docs/en/graphics/renderer/meshRenderer.mdx +++ b/docs/en/graphics/renderer/meshRenderer.mdx @@ -23,7 +23,7 @@ Here's how to use it in code: ```typescript const cubeEntity = rootEntity.createChild("cube"); const cube = cubeEntity.addComponent(MeshRenderer); -cube.mesh = PrimitiveMesh.createCuboid(engine, { width: 2 }); +cube.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); cube.setMaterial(new BlinnPhongMaterial(engine)); ``` diff --git a/docs/zh/graphics/background/sky.mdx b/docs/zh/graphics/background/sky.mdx index 5e178e0307..fbd1d1919b 100644 --- a/docs/zh/graphics/background/sky.mdx +++ b/docs/zh/graphics/background/sky.mdx @@ -49,7 +49,7 @@ 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 4016f27313..a081079931 100644 --- a/docs/zh/graphics/mesh/primitiveMesh.mdx +++ b/docs/zh/graphics/mesh/primitiveMesh.mdx @@ -44,7 +44,7 @@ label: Graphics/Mesh 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); @@ -57,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); @@ -70,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); @@ -83,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); @@ -96,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); @@ -109,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); @@ -122,7 +122,7 @@ 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); @@ -131,25 +131,25 @@ renderer.setMaterial(material); ## 程序化几何 -每个工厂方法接收一个具名配置对象。配置类型逐字段说明含义、单位和默认值;省略对象或其中的字段即可使用默认值。例如,`createSphere` 接收 `SphereMeshOptions`: +每个工厂方法先接收必填的形状参数,再接收可选的具名配置对象。尺寸、半径、轮廓和路径必须明确指定;细分、角度范围和网格设置保留在 options 中,省略时使用注释说明的默认值。例如,`createSphere` 先接收半径,再接收 `SphereMeshOptions`: ```ts -const unitSphere = PrimitiveMesh.createSphere(engine); -const sphere = PrimitiveMesh.createSphere(engine, { radius: 1 }); -const smoothSphere = PrimitiveMesh.createSphere(engine, { radius: 1, subdivisions: 4 }); +const unitSphere = PrimitiveMesh.createSphere(engine, 0.5); +const sphere = PrimitiveMesh.createSphere(engine, 1); +const smoothSphere = PrimitiveMesh.createSphere(engine, 1, { subdivisions: 4 }); -const cube = PrimitiveMesh.createCuboid(engine, { width: 2 }); -const box = PrimitiveMesh.createCuboid(engine, { width: 2, height: 3, depth: 4 }); -const ground = PrimitiveMesh.createPlane(engine, { width: 10 }); +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, { radius: 0.5, height: 2 }); -const frustum = PrimitiveMesh.createTruncatedCone(engine, { topRadius: 0.25, bottomRadius: 0.5, height: 2 }); -const mirroredKnot = PrimitiveMesh.createTorusKnot(engine, { radius: 1, tubeRadius: 0.1, p: 2, q: -3 }); +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` 的 `innerRadius` 默认等于 `outerRadius` 的一半。 +`createCuboid` 的宽、高、深是三个独立的必填参数;`createPlane` 的宽、高也必须分别指定。平面和长方体的后续分段数默认沿用第一个方向的分段数。球体使用一个细分层级,默认为 3,限制在 1 到 6 之间。`createCylinder` 只有一个半径;上下半径不同的圆台使用 `createTruncatedCone`。`createRing` 先接收外半径,再接收内半径,两者都必须指定。 -尺寸、分段和网格设置都使用具名字段,可以只修改其中任意一项。 +尺寸必须显式传入;分段和网格设置使用具名字段,可以只指定需要调整的可选项。 环面结的 `p`、`q` 是有符号整数缠绕次数,与网格分段数无关。负值反转对应方向的缠绕,`0` 表示该方向的角度保持不变。 @@ -170,10 +170,10 @@ const mirroredKnot = PrimitiveMesh.createTorusKnot(engine, { radius: 1, tubeRadi ```ts import { PrimitiveMeshCapMode, Vector2 } from "@galacean/engine"; -const hemisphere = PrimitiveMesh.createSphere(engine, { verticalRange: new Vector2(0, 90), radius: 1 }); -const openCylinder = PrimitiveMesh.createCylinder(engine, { caps: PrimitiveMeshCapMode.None, radius: 0.5, height: 2 }); -const cupWall = PrimitiveMesh.createCylinder(engine, { caps: PrimitiveMeshCapMode.Bottom, radius: 0.5, height: 2 }); -const halfRing = PrimitiveMesh.createRing(engine, { angleRange: new Vector2(0, 180), outerRadius: 1, innerRadius: 0.5 }); +const hemisphere = PrimitiveMesh.createSphere(engine, 1, { verticalRange: 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。 @@ -191,25 +191,20 @@ const outline = [new Vector2(-2, -2), new Vector2(2, -2), new Vector2(2, 2), new 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.createExtrusion(engine, { points: outline, holes: [hole] }, { depth: 0.5 }); -const beveled = PrimitiveMesh.createExtrusion(engine, outline, { - bevelSize: 0.05, - bevelOffset: 0.02, - depth: 0.5, - steps: 1 -}); +const solid = PrimitiveMesh.createExtrusion(engine, { points: outline, holes: [hole] }, 0.5); +const beveled = PrimitiveMesh.createExtrusion(engine, outline, 0.5, { bevelSize: 0.05, bevelOffset: 0.02, steps: 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, { radius: 0.1, tubularSegments: 64 }); -const swept = PrimitiveMesh.createExtrusion(engine, outline, { path: path, steps: 64 }); +const tube = PrimitiveMesh.createTube(engine, path, 0.1, { tubularSegments: 64 }); +const swept = PrimitiveMesh.createExtrusion(engine, outline, path, { steps: 64 }); const loop = [new Vector3(-4, 0, -4), new Vector3(4, 0, -4), new Vector3(4, 0, 4), new Vector3(-4, 0, 4)]; -const closed = PrimitiveMesh.createExtrusion(engine, outline, { closed: true, path: loop, steps: 32 }); +const closed = PrimitiveMesh.createExtrusion(engine, outline, loop, { closed: true, steps: 32 }); ``` -拉伸配置分为 `LinearExtrusionMeshOptions` 和 `PathExtrusionMeshOptions`:前者指定 `depth` 与倒角,后者必须指定 `path`。两个接口分别声明各自模式的设置。提供 `path` 时选择路径挤出,忽略深度和倒角设置;未提供路径时忽略 `closed`。默认沿 +Z 直线拉伸且不倒角;`bevelSize > 0` 时开启倒角,`bevelThickness` 默认等于 `bevelSize`。沿路径拉伸不生成倒角。路径接收 `Vector3` 数组,并按折线长度均匀采样。使用曲线时,在外层采样成点数组后传入,如上例所示。 +拉伸的第三个参数必填:传入数值深度时沿 +Z 直线拉伸,传入 `Vector3` 数组时沿路径挤出。`LinearExtrusionMeshOptions` 包含可选的倒角设置,`PathExtrusionMeshOptions` 包含可选的路径设置。两个接口分别声明各自模式的设置。沿路径挤出时忽略倒角设置;直线拉伸时忽略 `closed`。直线拉伸默认不倒角;`bevelSize > 0` 时开启倒角,`bevelThickness` 默认等于 `bevelSize`。沿路径拉伸不生成倒角。路径接收 `Vector3` 数组,并按折线长度均匀采样。使用曲线时,在外层采样成点数组后传入,如上例所示。 管道和路径挤出的 `closed` 默认关闭;开启后自动连接路径首尾并对齐截面,不必重复首点。闭合挤出至少使用三段,不生成端盖。开放挤出保留两端端盖;管道在两种模式下都不生成端盖。 @@ -217,15 +212,12 @@ const closed = PrimitiveMesh.createExtrusion(engine, outline, { closed: true, pa ### 网格数据和材质 -网格设置与尺寸、分段放在同一配置对象中: +网格设置与分段设置放在同一个可选配置对象中: ```ts -const editable = PrimitiveMesh.createSphere(engine, { keepData: true, radius: 1, subdivisions: 3 }); -const sixMaterials = PrimitiveMesh.createCuboid(engine, { +const editable = PrimitiveMesh.createSphere(engine, 1, { keepData: true, subdivisions: 3 }); +const sixMaterials = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { separateMaterials: true, - width: 1, - height: 1, - depth: 1, widthSegments: 1, heightSegments: 1, depthSegments: 1 @@ -259,24 +251,31 @@ import type { PrimitiveMeshAsset } from "@galacean/engine"; const asset = { type: "sphere", - sphereOptions: { radius: 1, subdivisions: 3, keepData: true } + sphereRadius: 1, + sphereOptions: { subdivisions: 3, keepData: true } } satisfies PrimitiveMeshAsset; ``` -每个 `type` 对应同名的 `PrimitiveMesh.createX` 方法,`Options` 使用该工厂的具名字段和默认值。角度范围保存为 `{ x: 起始角, y: 结束角 }`,由 Loader 构造 `Vector2`。例如 `circleOptions: { angleRange: { x: 30, y: 180 } }` 创建从 30 度到 180 度的扇形。省略字段时采用创建 API 的默认值,包括由其他字段决定的默认值;角度仍使用度数。 +每个 `type` 对应同名的 `PrimitiveMesh.createX` 方法。带类型前缀的字段保存必填形状参数,`Options` 仅保存该工厂的可选设置。角度范围保存为 `{ x: 起始角, y: 结束角 }`,由 Loader 构造 `Vector2`。例如 `circleOptions: { angleRange: { x: 30, y: 180 } }` 创建从 30 度到 180 度的扇形。省略可选设置时采用创建 API 的默认值,包括由其他可选设置决定的默认值;角度仍使用度数。 | 资产类型 | 必填几何字段 | | --- | --- | -| `sphere`、`cuboid`、`plane` | 无 | -| `cylinder`、`truncatedCone`、`cone`、`capsule` | 无 | -| `torus`、`circle`、`ring`、`torusKnot`、`roundedCuboid` | 无 | -| `tetrahedron`、`octahedron`、`icosahedron`、`dodecahedron` | 无 | +| `sphere`、`circle` | `Radius` | +| `cuboid` | `cuboidWidth`、`cuboidHeight`、`cuboidDepth` | +| `plane` | `planeWidth`、`planeHeight` | +| `cylinder`、`cone`、`capsule` | `Radius`、`Height` | +| `truncatedCone` | `truncatedConeTopRadius`、`truncatedConeBottomRadius`、`truncatedConeHeight` | +| `torus` | `torusRadius`、`torusTubeRadius` | +| `ring` | `ringOuterRadius`、`ringInnerRadius` | +| `tetrahedron`、`octahedron`、`icosahedron`、`dodecahedron` | `Radius` | | `lathe` | `latheProfile` | -| `tube` | `tubePath` | +| `tube` | `tubePath`、`tubeRadius` | | `polygon` | `polygonShapes` | -| `extrusion` | `extrusionShapes`;可指定 `extrusionOptions.depth` 或 `extrusionOptions.path` | +| `extrusion` | `extrusionShapes`,以及 `extrusionDepth` 或 `extrusionPath` | +| `torusKnot` | `torusKnotRadius`、`torusKnotTubeRadius`、`torusKnotP`、`torusKnotQ` | +| `roundedCuboid` | `roundedCuboidWidth`、`roundedCuboidHeight`、`roundedCuboidDepth`、`roundedCuboidCornerRadius` | -`sphere` 创建立方体细分后投影得到的球体,`sphereOptions.subdivisions` 控制细分层级。`cylinder` 使用一个半径;`truncatedCone` 分别使用 `truncatedConeOptions.topRadius` 和 `truncatedConeOptions.bottomRadius`。 +`sphere` 创建立方体细分后投影得到的球体,`sphereOptions.subdivisions` 控制细分层级。`cylinder` 使用一个半径;`truncatedCone` 分别使用 `truncatedConeTopRadius` 和 `truncatedConeBottomRadius`。 轮廓和旋转截面保存为 `{ x, y }` 点数组,路径保存为 `{ x, y, z }` 点数组,由 Loader 构造对应向量。多边形与拉伸统一使用形状数组,每个形状包含 `points` 和可选的 `holes`: @@ -301,10 +300,11 @@ const asset = { ] } ], - "extrusionOptions": { "depth": 2, "bevelSize": 0.1, "bevelOffset": 0.2, "separateMaterials": true } + "extrusionDepth": 2, + "extrusionOptions": { "bevelSize": 0.1, "bevelOffset": 0.2, "separateMaterials": true } } ``` -沿路径拉伸使用 `extrusionOptions.path`,忽略深度和倒角设置。`extrusionOptions.closed` 设为 `true` 时闭合路径且不生成端盖。路径点保存为 `{ x, y, z }`。 +沿路径拉伸通过必填的 `extrusionPath` 代替 `extrusionDepth`,并忽略倒角设置。`extrusionOptions.closed` 设为 `true` 时闭合路径且不生成端盖。路径点保存为 `{ x, y, z }`。 以上类型前缀字段及 `Options` 都能经过 Editor 现有的基础网格打包过滤。Editor 预览应使用与保存资产相同的创建方法和参数。 diff --git a/docs/zh/graphics/renderer/meshRenderer.mdx b/docs/zh/graphics/renderer/meshRenderer.mdx index dde0fc497a..d93b39ad01 100644 --- a/docs/zh/graphics/renderer/meshRenderer.mdx +++ b/docs/zh/graphics/renderer/meshRenderer.mdx @@ -23,7 +23,7 @@ label: Graphics/Renderer ```typescript const cubeEntity = rootEntity.createChild("cube"); const cube = cubeEntity.addComponent(MeshRenderer); -cube.mesh = PrimitiveMesh.createCuboid(engine, { width: 2 }); +cube.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); cube.setMaterial(new BlinnPhongMaterial(engine)); ``` diff --git a/e2e/case/.initPostProcessEnv.ts b/e2e/case/.initPostProcessEnv.ts index 8a260c660e..bbcba54183 100644 --- a/e2e/case/.initPostProcessEnv.ts +++ b/e2e/case/.initPostProcessEnv.ts @@ -47,7 +47,7 @@ export async function initPostProcessEnv( scene.background.mode = BackgroundMode.Sky; sky.material = skyMaterial; - sky.mesh = PrimitiveMesh.createCuboid(engine, { width: 1, height: 1, depth: 1 }); + sky.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); skyMaterial.texture = ambientLight.specularTexture; return ambientLight; }), diff --git a/e2e/case/camera-opaque-texture.ts b/e2e/case/camera-opaque-texture.ts index 29bcaeca7e..646ae31809 100644 --- a/e2e/case/camera-opaque-texture.ts +++ b/e2e/case/camera-opaque-texture.ts @@ -153,7 +153,7 @@ function showOpaquePlane(engine: Engine, camera: Entity): void { entity.transform.setPosition(0, 0, -1); entity.transform.rotate(new Vector3(90, 0, 0)); const renderer = entity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createPlane(engine, { width: 0.5 }); + renderer.mesh = PrimitiveMesh.createPlane(engine, 0.5, 0.5); // Create material const material = new BaseMaterial(engine, Shader.find("RenderOpaqueTexture")); diff --git a/e2e/case/camera-ssao.ts b/e2e/case/camera-ssao.ts index cb25ac6061..8fbdfeb6f8 100644 --- a/e2e/case/camera-ssao.ts +++ b/e2e/case/camera-ssao.ts @@ -52,7 +52,7 @@ WebGLEngine.create({ const skyMaterial = new SkyBoxMaterial(engine); background.mode = BackgroundMode.Sky; sky.material = skyMaterial; - sky.mesh = PrimitiveMesh.createCuboid(engine); + sky.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); // Sphere const sphereMaterial = new PBRMaterial(engine); @@ -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.createSphere(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 a0c998ea60..b9b22c71c9 100644 --- a/e2e/case/canvas-transparency.ts +++ b/e2e/case/canvas-transparency.ts @@ -82,7 +82,7 @@ WebGLEngine.create({ canvas: "canvas", graphicDeviceOptions: { alpha: false } }) canvasPlaneEntity.transform.setPosition(0, 0, 0); canvasPlaneEntity.transform.rotate(new Vector3(90, 0, 0)); const renderer = canvasPlaneEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createPlane(engine, { width: 2 }); + renderer.mesh = PrimitiveMesh.createPlane(engine, 2, 2); renderer.setMaterial(canvasMaterial); updateForE2E(engine); @@ -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); + 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); + sphereRenderer.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); const sphereMaterial = new UnlitMaterial(engine); sphereRenderer.setMaterial(sphereMaterial); diff --git a/e2e/case/gpu-instancing-custom-data.ts b/e2e/case/gpu-instancing-custom-data.ts index 48982d3861..290f478ca9 100644 --- a/e2e/case/gpu-instancing-custom-data.ts +++ b/e2e/case/gpu-instancing-custom-data.ts @@ -79,7 +79,7 @@ WebGLEngine.create({ canvas: "canvas", shaderCompiler }).then((engine) => { lightEntity.addComponent(DirectLight).color = new Color(1, 1, 1, 1); // Shared mesh and material - const mesh = PrimitiveMesh.createCuboid(engine); + const mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); const material = new Material(engine, Shader.find("CustomInstanceShader")); const customColorProperty = ShaderProperty.getByName("renderer_CustomColor"); diff --git a/e2e/case/material-LUT.ts b/e2e/case/material-LUT.ts index 09ca9fddd0..149c0fd5c1 100644 --- a/e2e/case/material-LUT.ts +++ b/e2e/case/material-LUT.ts @@ -56,7 +56,7 @@ WebGLEngine.create({ canvas: "canvas", shaderCompiler }) const entity = rootEntity.createChild("Entity"); entity.transform.setRotation(90, 0, 0); const renderer = entity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createPlane(engine); + renderer.mesh = PrimitiveMesh.createPlane(engine, 1, 1); const shader = Shader.create(shaderSource); const material = new Material(engine, shader); diff --git a/e2e/case/material-white-furnace.ts b/e2e/case/material-white-furnace.ts index ff19f0fc42..e7df9c5da3 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, { radius: 0.5, subdivisions: 4 }); + renderer.mesh = PrimitiveMesh.createSphere(engine, 0.5, { subdivisions: 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 44c7dc9b07..51c256a5e9 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, { radius: 2, subdivisions: 3 }); + renderer.mesh = PrimitiveMesh.createSphere(engine, 2, { subdivisions: 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, { radius: 2, subdivisions: 3 }); + renderer.mesh = PrimitiveMesh.createSphere(engine, 2, { subdivisions: 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/multi-scene-clear.ts b/e2e/case/multi-scene-clear.ts index 12f124fbe0..78cc90f01b 100644 --- a/e2e/case/multi-scene-clear.ts +++ b/e2e/case/multi-scene-clear.ts @@ -41,7 +41,7 @@ function initFirstScene(engine: Engine): Camera { const cubeEntity = rootEntity.createChild("cube"); cubeEntity.transform.setPosition(-2, 0, 3); const renderer = cubeEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createCuboid(engine, { width: 2 }); + renderer.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); const material = new BlinnPhongMaterial(engine); material.baseColor = new Color(1, 0, 0, 1); renderer.setMaterial(material); @@ -73,7 +73,7 @@ function initSecondScene(engine: Engine): Camera { const cubeEntity = rootEntity.createChild("cube"); cubeEntity.transform.setPosition(2, 0, 3); const renderer = cubeEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createCuboid(engine, { width: 2 }); + renderer.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); 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/multi-scene-no-clear.ts b/e2e/case/multi-scene-no-clear.ts index 22c7eac833..976e67e8ae 100644 --- a/e2e/case/multi-scene-no-clear.ts +++ b/e2e/case/multi-scene-no-clear.ts @@ -48,7 +48,7 @@ function initFirstScene(engine: Engine): Camera { const cubeEntity = rootEntity.createChild("cube"); cubeEntity.transform.setPosition(-2, 0, 3); const renderer = cubeEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createCuboid(engine, { width: 2 }); + renderer.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); const material = new BlinnPhongMaterial(engine); material.baseColor = new Color(1, 0, 0, 1); renderer.setMaterial(material); @@ -80,7 +80,7 @@ function initSecondScene(engine: Engine): Camera { const cubeEntity = rootEntity.createChild("cube"); cubeEntity.transform.setPosition(2, 0, 3); const renderer = cubeEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createCuboid(engine, { width: 2 }); + renderer.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); 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/physx-collision-group.ts b/e2e/case/physx-collision-group.ts index aeff378941..94263f6d80 100644 --- a/e2e/case/physx-collision-group.ts +++ b/e2e/case/physx-collision-group.ts @@ -55,7 +55,7 @@ function createPhysicsSphere( sphereMtl.baseColor.set(color.x, color.y, color.z, 1.0); sphereMtl.metallic = 0.0; sphereMtl.roughness = 0.5; - sphereRenderer.mesh = PrimitiveMesh.createSphere(rootEntity.engine, { radius }); + sphereRenderer.mesh = PrimitiveMesh.createSphere(rootEntity.engine, radius); sphereRenderer.setMaterial(sphereMtl); // Add physics @@ -107,11 +107,7 @@ WebGLEngine.create({ canvas: "canvas", physics: new PhysXPhysics() }).then((engi const cubeSize = new Vector3(10, 0.2, 10); const groundRenderer = groundEntity.addComponent(MeshRenderer); - groundRenderer.mesh = PrimitiveMesh.createCuboid(engine, { - width: cubeSize.x, - height: cubeSize.y, - depth: cubeSize.z - }); + groundRenderer.mesh = PrimitiveMesh.createCuboid(engine, cubeSize.x, cubeSize.y, cubeSize.z); groundRenderer.setMaterial(groundMtl); // Physics for the ground cube diff --git a/e2e/case/physx-collision.ts b/e2e/case/physx-collision.ts index 3f1cd3cfc1..a7e2989974 100644 --- a/e2e/case/physx-collision.ts +++ b/e2e/case/physx-collision.ts @@ -36,7 +36,7 @@ function addBox(rootEntity: Entity, cubeSize: number, x: number, y: number, z: n boxMtl.baseColor.set(0.6, 0.3, 0.3, 1.0); boxMtl.roughness = 0.5; boxMtl.metallic = 0.0; - boxRenderer.mesh = PrimitiveMesh.createCuboid(rootEntity.engine, { width: cubeSize }); + boxRenderer.mesh = PrimitiveMesh.createCuboid(rootEntity.engine, cubeSize, cubeSize, cubeSize); boxRenderer.setMaterial(boxMtl); if (index === 0) { boxMtl.baseColor.set(1, 0, 0, 1.0); @@ -87,7 +87,7 @@ WebGLEngine.create({ canvas: "canvas", physics: new PhysXPhysics() }).then((engi sphereMtl.baseColor.set(Math.random(), Math.random(), Math.random(), 1.0); sphereMtl.metallic = 0.0; sphereMtl.roughness = 0.5; - sphereRenderer.mesh = PrimitiveMesh.createSphere(engine, { radius }); + sphereRenderer.mesh = PrimitiveMesh.createSphere(engine, radius); sphereRenderer.setMaterial(sphereMtl); const physicsSphere = new SphereColliderShape(); diff --git a/e2e/case/physx-customUrl.ts b/e2e/case/physx-customUrl.ts index aa5bc8edc7..ddc1d1a752 100644 --- a/e2e/case/physx-customUrl.ts +++ b/e2e/case/physx-customUrl.ts @@ -35,7 +35,7 @@ function addBox(rootEntity: Entity, cubeSize: number, x: number, y: number, z: n boxMtl.baseColor.set(0.6, 0.3, 0.3, 1.0); boxMtl.roughness = 0.5; boxMtl.metallic = 0.0; - boxRenderer.mesh = PrimitiveMesh.createCuboid(rootEntity.engine, { width: cubeSize }); + boxRenderer.mesh = PrimitiveMesh.createCuboid(rootEntity.engine, cubeSize, cubeSize, cubeSize); boxRenderer.setMaterial(boxMtl); if (index === 0) { boxMtl.baseColor.set(1, 0, 0, 1.0); @@ -92,7 +92,7 @@ WebGLEngine.create({ sphereMtl.baseColor.set(Math.random(), Math.random(), Math.random(), 1.0); sphereMtl.metallic = 0.0; sphereMtl.roughness = 0.5; - sphereRenderer.mesh = PrimitiveMesh.createSphere(engine, { radius }); + sphereRenderer.mesh = PrimitiveMesh.createSphere(engine, radius); sphereRenderer.setMaterial(sphereMtl); const physicsSphere = new SphereColliderShape(); diff --git a/e2e/case/physx-deferred-contact.ts b/e2e/case/physx-deferred-contact.ts index d28d3e9797..a3e903a3d5 100644 --- a/e2e/case/physx-deferred-contact.ts +++ b/e2e/case/physx-deferred-contact.ts @@ -39,7 +39,7 @@ WebGLEngine.create({ canvas: "canvas", physics: new PhysXPhysics() }).then((engi mtl.metallic = 0.0; mtl.roughness = 0.5; const renderer = entity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createCuboid(engine, { width: 2 }); + renderer.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); renderer.setMaterial(mtl); const shape = new BoxColliderShape(); diff --git a/e2e/case/physx-mesh-collider.ts b/e2e/case/physx-mesh-collider.ts index 6836b4fbe2..f3d5f63701 100644 --- a/e2e/case/physx-mesh-collider.ts +++ b/e2e/case/physx-mesh-collider.ts @@ -38,7 +38,7 @@ function createFallingBox( // Visual const renderer = entity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createCuboid(engine, { width: size.x, height: size.y, depth: size.z }); + renderer.mesh = PrimitiveMesh.createCuboid(engine, size.x, size.y, size.z); const material = new PBRMaterial(engine); material.baseColor.copyFrom(color); material.roughness = 0.6; diff --git a/e2e/case/primitive-all.ts b/e2e/case/primitive-all.ts index dd92519235..c53c584f21 100644 --- a/e2e/case/primitive-all.ts +++ b/e2e/case/primitive-all.ts @@ -85,11 +85,8 @@ class PrimitiveMeshGallery { const cases: Record = { cuboid: { label: "Cuboid", - mesh: PrimitiveMesh.createCuboid(engine, { + mesh: PrimitiveMesh.createCuboid(engine, 1, 1, 1, { separateMaterials: true, - width: 1, - height: 1, - depth: 1, widthSegments: 2, heightSegments: 2, depthSegments: 2 @@ -97,117 +94,79 @@ class PrimitiveMeshGallery { }, plane: { label: "Plane", - mesh: PrimitiveMesh.createPlane(engine, { width: 2, height: 2, horizontalSegments: 4, verticalSegments: 4 }), + mesh: PrimitiveMesh.createPlane(engine, 2, 2, { horizontalSegments: 4, verticalSegments: 4 }), rotation: new Vector3(90, 0, 0) }, - sphere: { label: "Sphere", mesh: PrimitiveMesh.createSphere(engine, { radius: 1, subdivisions: 3 }) }, + sphere: { label: "Sphere", mesh: PrimitiveMesh.createSphere(engine, 1, { subdivisions: 3 }) }, cylinder: { label: "Cylinder", - mesh: PrimitiveMesh.createCylinder(engine, { + mesh: PrimitiveMesh.createCylinder(engine, 0.65, 1.5, { separateMaterials: true, - radius: 0.65, - height: 1.5, radialSegments: 24, heightSegments: 2 }) }, cone: { label: "Cone", - mesh: PrimitiveMesh.createCone(engine, { + mesh: PrimitiveMesh.createCone(engine, 0.8, 1.8, { separateMaterials: true, - radius: 0.8, - height: 1.8, radialSegments: 24, heightSegments: 2 }) }, truncatedCone: { label: "Truncated Cone", - mesh: PrimitiveMesh.createTruncatedCone(engine, { + mesh: PrimitiveMesh.createTruncatedCone(engine, 0.35, 0.8, 1.6, { separateMaterials: true, - topRadius: 0.35, - bottomRadius: 0.8, - height: 1.6, radialSegments: 24, heightSegments: 2 }) }, capsule: { label: "Capsule", - mesh: PrimitiveMesh.createCapsule(engine, { - radius: 0.5, - height: 1, - radialSegments: 24, - capSegments: 8, - heightSegments: 2 - }) + mesh: PrimitiveMesh.createCapsule(engine, 0.5, 1, { radialSegments: 24, capSegments: 8, heightSegments: 2 }) }, torus: { label: "Torus", - mesh: PrimitiveMesh.createTorus(engine, { - radius: 0.75, - tubeRadius: 0.25, - tubularSegments: 32, - radialSegments: 12 - }) + mesh: PrimitiveMesh.createTorus(engine, 0.75, 0.25, { tubularSegments: 32, radialSegments: 12 }) }, torusKnot: { label: "Torus Knot", - mesh: PrimitiveMesh.createTorusKnot(engine, { - radius: 0.65, - tubeRadius: 0.17, - p: 2, - q: 3, - tubularSegments: 96, - radialSegments: 10 - }) + mesh: PrimitiveMesh.createTorusKnot(engine, 0.65, 0.17, 2, 3, { tubularSegments: 96, radialSegments: 10 }) }, circle: { label: "Circle", - mesh: PrimitiveMesh.createCircle(engine, { radius: 1, segments: 32 }), + mesh: PrimitiveMesh.createCircle(engine, 1, { segments: 32 }), rotation: new Vector3() }, ring: { label: "Ring", - mesh: PrimitiveMesh.createRing(engine, { - outerRadius: 1, - innerRadius: 0.5, - radialSegments: 32, - widthSegments: 2 - }), + mesh: PrimitiveMesh.createRing(engine, 1, 0.5, { radialSegments: 32, widthSegments: 2 }), rotation: new Vector3() }, - tetrahedron: { label: "Tetrahedron", mesh: PrimitiveMesh.createTetrahedron(engine, { radius: 1 }) }, - octahedron: { label: "Octahedron", mesh: PrimitiveMesh.createOctahedron(engine, { radius: 1 }) }, - icosahedron: { label: "Icosahedron", mesh: PrimitiveMesh.createIcosahedron(engine, { radius: 1 }) }, - dodecahedron: { label: "Dodecahedron", mesh: PrimitiveMesh.createDodecahedron(engine, { radius: 1 }) }, + 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) }, lathe: { label: "Lathe", mesh: PrimitiveMesh.createLathe(engine, profile, { segments: 24 }) }, tube: { label: "Tube", - mesh: PrimitiveMesh.createTube(engine, path, { radius: 0.2, tubularSegments: 48, radialSegments: 10 }) + mesh: PrimitiveMesh.createTube(engine, path, 0.2, { tubularSegments: 48, radialSegments: 10 }) }, polygon: { label: "Polygon", mesh: PrimitiveMesh.createPolygon(engine, polygon), rotation: new Vector3() }, extrusion: { label: "Extrusion", - mesh: PrimitiveMesh.createExtrusion(engine, polygon, { + mesh: PrimitiveMesh.createExtrusion(engine, polygon, 0.6, { bevelSize: 0.1, bevelThickness: 0.1, bevelSegments: 3, separateMaterials: true, - depth: 0.6, steps: 2 }) }, roundedCuboid: { label: "Rounded Cuboid", - mesh: PrimitiveMesh.createRoundedCuboid(engine, { - separateMaterials: true, - width: 2, - height: 1.6, - depth: 1.4, - cornerRadius: 0.3, - segments: 4 - }) + mesh: PrimitiveMesh.createRoundedCuboid(engine, 2, 1.6, 1.4, 0.3, { separateMaterials: true, segments: 4 }) } }; const coveredFactories = Object.keys(cases).map((type) => `create${type[0].toUpperCase()}${type.slice(1)}`); diff --git a/e2e/case/primitive-capsule.ts b/e2e/case/primitive-capsule.ts index 25f998b1e2..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, { radius: 0.5, height: 1, radialSegments: 24 }); + 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 index 7e162c0260..d40a117c47 100644 --- a/e2e/case/primitive-contours.ts +++ b/e2e/case/primitive-contours.ts @@ -66,13 +66,12 @@ class PrimitiveContours { { label: "Straight extrusion", detail: "depth: 0.6 / no bevel", - mesh: PrimitiveMesh.createExtrusion(engine, polygon, { depth: 0.6 }) + mesh: PrimitiveMesh.createExtrusion(engine, polygon, 0.6) }, { label: "Independent bevel depth", detail: "size: 0.16 / thickness: 0.06", - mesh: PrimitiveMesh.createExtrusion(engine, polygon, { - depth: 0.6, + mesh: PrimitiveMesh.createExtrusion(engine, polygon, 0.6, { bevelSize: 0.16, bevelThickness: 0.06, bevelSegments: 4 @@ -81,42 +80,37 @@ class PrimitiveContours { { label: "Expanded contour", detail: "offset: +0.15 / no bevel", - mesh: PrimitiveMesh.createExtrusion(engine, polygon, { depth: 0.6, bevelOffset: 0.15 }) + mesh: PrimitiveMesh.createExtrusion(engine, polygon, 0.6, { bevelOffset: 0.15 }) }, { label: "Contracted contour", detail: "bevelOffset: -0.15", - mesh: PrimitiveMesh.createExtrusion(engine, polygon, { depth: 0.6, bevelOffset: -0.15, bevelSize: 0.08 }) + mesh: PrimitiveMesh.createExtrusion(engine, polygon, 0.6, { bevelOffset: -0.15, bevelSize: 0.08 }) }, { label: "Open tube", detail: "point array / open ends", - mesh: PrimitiveMesh.createTube(engine, path, { radius: 0.15, tubularSegments: 48, radialSegments: 12 }) + mesh: PrimitiveMesh.createTube(engine, path, 0.15, { tubularSegments: 48, radialSegments: 12 }) }, { label: "Closed tube", detail: "closed: true / seamless join", - mesh: PrimitiveMesh.createTube(engine, loop, { - radius: 0.15, - tubularSegments: 64, - radialSegments: 12, - closed: true - }) + mesh: PrimitiveMesh.createTube(engine, loop, 0.15, { tubularSegments: 64, radialSegments: 12, closed: true }) }, { label: "Open profile sweep", detail: "path + steps: 48", - mesh: PrimitiveMesh.createExtrusion(engine, smallProfile, { path, steps: 48 }) + mesh: PrimitiveMesh.createExtrusion(engine, smallProfile, path, { steps: 48 }) }, { label: "Closed profile sweep", detail: "closed: true / no caps", - mesh: PrimitiveMesh.createExtrusion(engine, smallProfile, { path: loop, steps: 64, closed: true }) + mesh: PrimitiveMesh.createExtrusion(engine, smallProfile, loop, { steps: 64, closed: true }) }, { label: "Hollow profile sweep", detail: "path + inner contour", - mesh: PrimitiveMesh.createExtrusion(engine, smallHoleProfile, { path, steps: 48 }) + mesh: PrimitiveMesh.createExtrusion(engine, smallHoleProfile, path, { steps: 48 }) } ], 4 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 index cc03d6ff0d..91e3b82772 100644 --- a/e2e/case/primitive-materials.ts +++ b/e2e/case/primitive-materials.ts @@ -19,11 +19,11 @@ class PrimitiveMaterials { 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", sphereOptions: { radius: 1, subdivisions: 2 } } satisfies PrimitiveMeshAsset; + const asset = { type: "sphere", sphereRadius: 1, sphereOptions: { subdivisions: 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, { radius: 1, subdivisions: 2, keepData: true }); + const retained = PrimitiveMesh.createSphere(engine, 1, { subdivisions: 2, keepData: true }); if (loaded.accessible || !retained.accessible || loaded.vertexCount !== retained.vertexCount) { throw new Error("Primitive data retention or JSON asset creation differs from the factory."); } @@ -31,25 +31,25 @@ class PrimitiveMaterials { { label: "Cuboid / one material", detail: "separateMaterials: false", - mesh: PrimitiveMesh.createCuboid(engine), + mesh: PrimitiveMesh.createCuboid(engine, 1, 1, 1), slots: 1 }, { label: "Cuboid / face materials", detail: "+Y -Y -X +X +Z -Z", - mesh: PrimitiveMesh.createCuboid(engine, { separateMaterials: true }), + mesh: PrimitiveMesh.createCuboid(engine, 1, 1, 1, { separateMaterials: true }), slots: 6 }, { label: "Cylinder / part materials", detail: "side / top / bottom", - mesh: PrimitiveMesh.createCylinder(engine, { height: 1.4, separateMaterials: true }), + mesh: PrimitiveMesh.createCylinder(engine, 0.5, 1.4, { separateMaterials: true }), slots: 3 }, { label: "Cone / part materials", detail: "side / bottom", - mesh: PrimitiveMesh.createCone(engine, { height: 1.4, separateMaterials: true }), + mesh: PrimitiveMesh.createCone(engine, 0.5, 1.4, { separateMaterials: true }), slots: 2, rotation: new Vector3(-25, -28, 0) }, @@ -63,14 +63,13 @@ class PrimitiveMaterials { { label: "Extrusion / cap and wall", detail: "caps / walls + bevels", - mesh: PrimitiveMesh.createExtrusion(engine, square, { depth: 0.6, bevelSize: 0.12, separateMaterials: true }), + mesh: PrimitiveMesh.createExtrusion(engine, square, 0.6, { bevelSize: 0.12, separateMaterials: true }), slots: 2 }, { label: "Closed / two profiles", detail: "one wall slot per profile", - mesh: PrimitiveMesh.createExtrusion(engine, profiles, { - path: loop, + mesh: PrimitiveMesh.createExtrusion(engine, profiles, loop, { steps: 64, closed: true, separateMaterials: true @@ -80,7 +79,7 @@ class PrimitiveMaterials { { label: "Rounded / face materials", detail: "six material slots", - mesh: PrimitiveMesh.createRoundedCuboid(engine, { cornerRadius: 0.2, segments: 4, separateMaterials: true }), + mesh: PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.2, { segments: 4, separateMaterials: true }), slots: 6 }, { @@ -100,14 +99,14 @@ class PrimitiveMaterials { { label: "Mirrored torus knot", detail: "p: 2 / q: -3", - mesh: PrimitiveMesh.createTorusKnot(engine, { q: -3, tubularSegments: 96 }), + mesh: PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2, -3, { tubularSegments: 96 }), slots: 1, appearance: "checker" }, { label: "Clamped corner radius", detail: "radius: 2 clamped to 0.5", - mesh: PrimitiveMesh.createRoundedCuboid(engine, { cornerRadius: 2, segments: 6 }), + mesh: PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 2, { segments: 6 }), slots: 1, appearance: "checker" } 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 index b0a1df2300..3b20ab3f7a 100644 --- a/e2e/case/primitive-sections.ts +++ b/e2e/case/primitive-sections.ts @@ -16,75 +16,70 @@ class PrimitiveSections { { label: "Circle sector", detail: "angleRange: [30, 300]", - mesh: PrimitiveMesh.createCircle(engine, { angleRange: new Vector2(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, { angleRange: new Vector2(30, 300) }), + mesh: PrimitiveMesh.createRing(engine, 0.5, 0.25, { angleRange: new Vector2(30, 300) }), rotation: front }, { label: "Torus arc", detail: "angleRange: [30, 300]", - mesh: PrimitiveMesh.createTorus(engine, { angleRange: new Vector2(30, 300) }) + mesh: PrimitiveMesh.createTorus(engine, 0.5, 0.1, { angleRange: new Vector2(30, 300) }) }, { label: "Torus cross-section", detail: "tubeRange: [0, 180]", - mesh: PrimitiveMesh.createTorus(engine, { tubeRadius: 0.2, tubeRange: new Vector2(0, 180) }) + mesh: PrimitiveMesh.createTorus(engine, 0.5, 0.2, { tubeRange: new Vector2(0, 180) }) }, { label: "Both torus ranges", detail: "arc 270 / tube 270 degrees", - mesh: PrimitiveMesh.createTorus(engine, { - tubeRadius: 0.2, + mesh: PrimitiveMesh.createTorus(engine, 0.5, 0.2, { angleRange: new Vector2(30, 300), tubeRange: new Vector2(45, 315) }) }, - { label: "Cylinder: both", detail: "caps: both", mesh: PrimitiveMesh.createCylinder(engine, { height: 1.4 }) }, + { label: "Cylinder: both", detail: "caps: both", mesh: PrimitiveMesh.createCylinder(engine, 0.5, 1.4) }, { label: "Cylinder: top", detail: "caps: top", - mesh: PrimitiveMesh.createCylinder(engine, { height: 1.4, caps: PrimitiveMeshCapMode.Top }) + mesh: PrimitiveMesh.createCylinder(engine, 0.5, 1.4, { caps: PrimitiveMeshCapMode.Top }) }, { label: "Cylinder: bottom", detail: "caps: bottom", - mesh: PrimitiveMesh.createCylinder(engine, { height: 1.4, caps: PrimitiveMeshCapMode.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, { height: 1.4, caps: PrimitiveMeshCapMode.None }) + mesh: PrimitiveMesh.createCylinder(engine, 0.5, 1.4, { caps: PrimitiveMeshCapMode.None }) }, { label: "Cylinder sector", detail: "angleRange: [30, 270]", - mesh: PrimitiveMesh.createCylinder(engine, { height: 1.4, angleRange: new Vector2(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, { - bottomRadius: 0.6, - height: 1.4, - angleRange: new Vector2(30, 270) - }) + 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, { height: 1.4 }), + 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, { height: 1.4, cap: false }), + mesh: PrimitiveMesh.createCone(engine, 0.5, 1.4, { cap: false }), rotation: new Vector3(-25, -28, 0) }, { diff --git a/e2e/case/primitive-sphere-sections.ts b/e2e/case/primitive-sphere-sections.ts index fc14807dc0..9ea6e2e934 100644 --- a/e2e/case/primitive-sphere-sections.ts +++ b/e2e/case/primitive-sphere-sections.ts @@ -79,12 +79,7 @@ class SphereSections { 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, { - horizontalRange, - verticalRange, - radius: 1, - subdivisions: 3 - }); + renderer.mesh = PrimitiveMesh.createSphere(engine, 1, { horizontalRange, verticalRange, subdivisions: 3 }); renderer.setMaterial(material); const label = root.createChild(`${name} Label`); label.transform.setPosition(x, y - 1.15, 0); diff --git a/e2e/case/primitive-sphere.ts b/e2e/case/primitive-sphere.ts index 87b5d2f0b0..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.createSphere(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 index 04fa00468d..3d55d8f5fd 100644 --- a/e2e/case/primitive-topology.ts +++ b/e2e/case/primitive-topology.ts @@ -13,56 +13,60 @@ class PrimitiveTopology { { label: "Sphere / level 1", detail: "subdivisions: 1", - mesh: PrimitiveMesh.createSphere(engine, { ...keep, subdivisions: 1 }) + mesh: PrimitiveMesh.createSphere(engine, 0.5, { ...keep, subdivisions: 1 }) }, { label: "Sphere / level 3", detail: "subdivisions: 3", - mesh: PrimitiveMesh.createSphere(engine, { ...keep, subdivisions: 3 }) + mesh: PrimitiveMesh.createSphere(engine, 0.5, { ...keep, subdivisions: 3 }) }, { label: "Cylinder / 6 sides", detail: "radialSegments: 6", - mesh: PrimitiveMesh.createCylinder(engine, { ...keep, 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, { ...keep, radialSegments: 24, heightSegments: 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, { ...keep, radialSegments: 6, heightSegments: 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, { ...keep, widthSegments: 4, heightSegments: 2, depthSegments: 3 }) + mesh: PrimitiveMesh.createCuboid(engine, 1, 1, 1, { + ...keep, + widthSegments: 4, + heightSegments: 2, + depthSegments: 3 + }) }, { label: "Plane / 1 by 6", detail: "horizontal: 1 / vertical: 6", - mesh: PrimitiveMesh.createPlane(engine, { ...keep, horizontalSegments: 1, verticalSegments: 6 }), + mesh: PrimitiveMesh.createPlane(engine, 1, 1, { ...keep, horizontalSegments: 1, verticalSegments: 6 }), rotation: new Vector3(65, -20, 0) }, { label: "Plane / 6 by 1", detail: "horizontal: 6 / vertical: 1", - mesh: PrimitiveMesh.createPlane(engine, { ...keep, horizontalSegments: 6, verticalSegments: 1 }), + mesh: PrimitiveMesh.createPlane(engine, 1, 1, { ...keep, horizontalSegments: 6, verticalSegments: 1 }), rotation: new Vector3(65, -20, 0) }, { label: "Capsule / coarse caps", detail: "radial: 8 / caps: 2 / height: 1", - mesh: PrimitiveMesh.createCapsule(engine, { ...keep, height: 1, radialSegments: 8, capSegments: 2 }) + 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, { + mesh: PrimitiveMesh.createCapsule(engine, 0.5, 1, { ...keep, - height: 1, radialSegments: 16, capSegments: 8, heightSegments: 4 @@ -71,63 +75,63 @@ class PrimitiveTopology { { label: "Tetrahedron subdivision", detail: "segments: 3", - mesh: PrimitiveMesh.createTetrahedron(engine, { ...keep, segments: 3 }) + mesh: PrimitiveMesh.createTetrahedron(engine, 0.5, { ...keep, segments: 3 }) }, { label: "Octahedron subdivision", detail: "segments: 3", - mesh: PrimitiveMesh.createOctahedron(engine, { ...keep, segments: 3 }) + mesh: PrimitiveMesh.createOctahedron(engine, 0.5, { ...keep, segments: 3 }) }, { label: "Icosahedron subdivision", detail: "segments: 3", - mesh: PrimitiveMesh.createIcosahedron(engine, { ...keep, segments: 3 }) + mesh: PrimitiveMesh.createIcosahedron(engine, 0.5, { ...keep, segments: 3 }) }, { label: "Dodecahedron subdivision", detail: "segments: 3", - mesh: PrimitiveMesh.createDodecahedron(engine, { ...keep, segments: 3 }) + mesh: PrimitiveMesh.createDodecahedron(engine, 0.5, { ...keep, segments: 3 }) }, { label: "Sphere / level 2", detail: "subdivisions: 2", - mesh: PrimitiveMesh.createSphere(engine, { ...keep, subdivisions: 2 }) + mesh: PrimitiveMesh.createSphere(engine, 0.5, { ...keep, subdivisions: 2 }) }, { label: "Rounded cuboid / zero", detail: "cornerRadius: 0", - mesh: PrimitiveMesh.createRoundedCuboid(engine, { ...keep, cornerRadius: 0 }) + mesh: PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0, { ...keep }) }, { label: "Rounded cuboid / coarse", detail: "radius: 0.2 / segments: 1", - mesh: PrimitiveMesh.createRoundedCuboid(engine, { ...keep, cornerRadius: 0.2, segments: 1 }) + mesh: PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.2, { ...keep, segments: 1 }) }, { label: "Rounded cuboid / fine", detail: "radius: 0.2 / segments: 4", - mesh: PrimitiveMesh.createRoundedCuboid(engine, { ...keep, cornerRadius: 0.2, segments: 4 }) + mesh: PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.2, { ...keep, segments: 4 }) }, { label: "Torus knot / 2, 3", detail: "p: 2 / q: 3", - mesh: PrimitiveMesh.createTorusKnot(engine, { ...keep, p: 2, q: 3, tubularSegments: 96 }) + mesh: PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2, 3, { ...keep, tubularSegments: 96 }) }, { label: "Torus knot / 3, 2", detail: "p: 3 / q: 2", - mesh: PrimitiveMesh.createTorusKnot(engine, { ...keep, p: 3, q: 2, tubularSegments: 96 }) + mesh: PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 3, 2, { ...keep, tubularSegments: 96 }) }, { label: "Circle / 8 segments", detail: "segments: 8", - mesh: PrimitiveMesh.createCircle(engine, { ...keep, segments: 8 }), + mesh: PrimitiveMesh.createCircle(engine, 0.5, { ...keep, segments: 8 }), rotation: new Vector3() }, { label: "Ring / width subdivisions", detail: "radial: 12 / width: 4", - mesh: PrimitiveMesh.createRing(engine, { ...keep, radialSegments: 12, widthSegments: 4 }), + mesh: PrimitiveMesh.createRing(engine, 0.5, 0.25, { ...keep, radialSegments: 12, widthSegments: 4 }), rotation: new Vector3() }, { @@ -144,7 +148,8 @@ class PrimitiveTopology { mesh: PrimitiveMesh.createTube( engine, [new Vector3(-1, -0.4, 0), new Vector3(0, 0.4, 0.3), new Vector3(1, -0.4, 0)], - { ...keep, radius: 0.2, tubularSegments: 12, radialSegments: 6 } + 0.2, + { ...keep, tubularSegments: 12, radialSegments: 6 } ) }, { @@ -153,7 +158,8 @@ class PrimitiveTopology { mesh: PrimitiveMesh.createExtrusion( engine, [new Vector2(-1, -1), new Vector2(1, -1), new Vector2(1, 1), new Vector2(-1, 1)], - { ...keep, depth: 0.6, steps: 3, bevelSize: 0.15, bevelSegments: 3 } + 0.6, + { ...keep, steps: 3, bevelSize: 0.15, bevelSegments: 3 } ) } ]; 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/shadow-basic.ts b/e2e/case/shadow-basic.ts index 0fda95c255..cea64a22bc 100644 --- a/e2e/case/shadow-basic.ts +++ b/e2e/case/shadow-basic.ts @@ -36,7 +36,7 @@ WebGLEngine.create({ canvas: "canvas" }).then((engine) => { const planeEntity = rootEntity.createChild("plane_node"); const renderer = planeEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createPlane(engine, { width: 10 }); + renderer.mesh = PrimitiveMesh.createPlane(engine, 10, 10); const planeMaterial = new PBRMaterial(engine); renderer.setMaterial(planeMaterial); diff --git a/e2e/case/shadow-transparent.ts b/e2e/case/shadow-transparent.ts index 6e5c0549bc..8b03ecb580 100644 --- a/e2e/case/shadow-transparent.ts +++ b/e2e/case/shadow-transparent.ts @@ -42,7 +42,7 @@ WebGLEngine.create({ const planeEntity = rootEntity.createChild("plane_node"); const renderer = planeEntity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createPlane(engine, { width: 10 }); + renderer.mesh = PrimitiveMesh.createPlane(engine, 10, 10); const planeMaterial = new PBRMaterial(engine); renderer.setMaterial(planeMaterial); diff --git a/e2e/case/texture-R8G8.ts b/e2e/case/texture-R8G8.ts index edbf50c4c3..0bcce16c57 100644 --- a/e2e/case/texture-R8G8.ts +++ b/e2e/case/texture-R8G8.ts @@ -32,7 +32,7 @@ WebGLEngine.create({ canvas: "canvas" }).then((engine) => { planeEntity.transform.setRotation(5, 0, 0); const planeRenderer = planeEntity.addComponent(MeshRenderer); - planeRenderer.mesh = PrimitiveMesh.createPlane(engine, { width: 2 }); + planeRenderer.mesh = PrimitiveMesh.createPlane(engine, 2, 2); planeRenderer.setMaterial(material); const width = 1024; 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-hdr.ts b/e2e/case/texture-hdr.ts index 1ff1ae2f36..2c9531a82b 100644 --- a/e2e/case/texture-hdr.ts +++ b/e2e/case/texture-hdr.ts @@ -37,7 +37,7 @@ WebGLEngine.create({ canvas: "canvas" }).then((engine) => { scene.background.mode = BackgroundMode.Sky; sky.material = skyMaterial; - sky.mesh = PrimitiveMesh.createCuboid(engine); + sky.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); skyMaterial.texture = textureCube; updateForE2E(engine); diff --git a/e2e/case/texture-sRGB-KTX2.ts b/e2e/case/texture-sRGB-KTX2.ts index d0599cc395..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.createSphere(engine); + meshRenderer.mesh = PrimitiveMesh.createSphere(engine, 0.5); meshRenderer.setMaterial(material); updateForE2E(engine); diff --git a/examples/src/gltf-loader.ts b/examples/src/gltf-loader.ts index d0d5039025..40f4fac362 100644 --- a/examples/src/gltf-loader.ts +++ b/examples/src/gltf-loader.ts @@ -201,7 +201,7 @@ class Oasis { this.lightEntity2.transform.setRotation(-30, 180, 0); this.scene.ambientLight.specularIntensity = this.state.envIntensity; this.scene.background.sky.material = this.skyMaterial; - this.scene.background.sky.mesh = PrimitiveMesh.createCuboid(this.engine); + this.scene.background.sky.mesh = PrimitiveMesh.createCuboid(this.engine, 1, 1, 1); this.engine.run(); } diff --git a/examples/src/gpu-instancing-auto-batch.ts b/examples/src/gpu-instancing-auto-batch.ts index f29b6eb070..ce27044161 100644 --- a/examples/src/gpu-instancing-auto-batch.ts +++ b/examples/src/gpu-instancing-auto-batch.ts @@ -157,7 +157,7 @@ WebGLEngine.create({ scene.ambientLight = ambientLight; // Cube resources - const cubeMesh = PrimitiveMesh.createCuboid(engine); + const cubeMesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); const cubeMaterial = new Material(engine, Shader.find("CustomInstanceShader")); const customColorProperty = ShaderProperty.getByName("renderer_CustomColor"); diff --git a/examples/src/gpu-instancing-custom-data.ts b/examples/src/gpu-instancing-custom-data.ts index 94c9100170..52b0ea89a3 100644 --- a/examples/src/gpu-instancing-custom-data.ts +++ b/examples/src/gpu-instancing-custom-data.ts @@ -128,7 +128,7 @@ WebGLEngine.create({ lightEntity.transform.setRotation(-45, -45, 0); lightEntity.addComponent(DirectLight).color = new Color(1, 1, 1, 1); - const mesh = PrimitiveMesh.createCuboid(engine); + const mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); const material = new Material(engine, Shader.find("CustomInstanceShader")); const customColorProperty = ShaderProperty.getByName("renderer_CustomColor"); 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-01-basic-shader.ts b/examples/src/shader-01-basic-shader.ts index 66571ab2a0..f92c1e9cea 100644 --- a/examples/src/shader-01-basic-shader.ts +++ b/examples/src/shader-01-basic-shader.ts @@ -80,7 +80,7 @@ function createQuad(engine: Engine): Entity { const renderer = entity.addComponent(MeshRenderer); // 使用内置的平面网格 - renderer.mesh = PrimitiveMesh.createPlane(engine, { width: 2 }); + renderer.mesh = PrimitiveMesh.createPlane(engine, 2, 2); entity.transform.setRotation(90, 0, 0); diff --git a/examples/src/shader-02-render-state.ts b/examples/src/shader-02-render-state.ts index 0f2451863c..4a7538c064 100644 --- a/examples/src/shader-02-render-state.ts +++ b/examples/src/shader-02-render-state.ts @@ -113,7 +113,7 @@ function createPlane(engine: Engine, name: string, position: Vector3): Entity { entity.transform.setRotation(90, 0, 0); const renderer = entity.addComponent(MeshRenderer); - renderer.mesh = PrimitiveMesh.createPlane(engine, { width: 2 }); + renderer.mesh = PrimitiveMesh.createPlane(engine, 2, 2); return entity; } diff --git a/examples/src/shader-03-ui-script.ts b/examples/src/shader-03-ui-script.ts index ae581ec74f..f379438c16 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, { width: 3, height: 3, horizontalSegments: 20 }); // 增加细分以显示顶点动画 + renderer.mesh = PrimitiveMesh.createPlane(engine, 3, 3, { horizontalSegments: 20 }); // 增加细分以显示顶点动画 renderer.setMaterial(material); // 运行引擎 diff --git a/examples/src/shader-04-multi-pass.ts b/examples/src/shader-04-multi-pass.ts index b2b33d65ae..60544b1fd1 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, { radius: 0.8, subdivisions: 5 }); + renderer.mesh = PrimitiveMesh.createSphere(engine, 0.8, { subdivisions: 5 }); return entity; } diff --git a/packages/core/src/mesh/PrimitiveMesh.ts b/packages/core/src/mesh/PrimitiveMesh.ts index aa523c4792..3f87b0720e 100644 --- a/packages/core/src/mesh/PrimitiveMesh.ts +++ b/packages/core/src/mesh/PrimitiveMesh.ts @@ -178,11 +178,12 @@ export class PrimitiveMesh { /** * Create a sphere or an open spherical section from a subdivided cube. * @param engine - The engine that owns the mesh - * @param options - Shape and mesh creation settings + * @param radius - The radius in local units + * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createSphere(engine: Engine, options: SphereMeshOptions = {}): ModelMesh { - const { radius = 0.5, subdivisions = 3, horizontalRange, verticalRange } = options; + static createSphere(engine: Engine, radius: number, options: SphereMeshOptions = {}): ModelMesh { + const { subdivisions = 3, horizontalRange, verticalRange } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createSphereData, @@ -201,18 +202,20 @@ export class PrimitiveMesh { /** * Create an axis-aligned cuboid centered at the origin. * @param engine - The engine that owns the mesh - * @param options - Shape and mesh creation settings + * @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 createCuboid(engine: Engine, options: CuboidMeshOptions = {}): ModelMesh { - const { - width = 1, - height = width, - depth = width, - widthSegments = 1, - heightSegments = widthSegments, - depthSegments = widthSegments - } = options; + static createCuboid( + engine: Engine, + width: number, + height: number, + depth: number, + options: CuboidMeshOptions = {} + ): ModelMesh { + const { widthSegments = 1, heightSegments = widthSegments, depthSegments = widthSegments } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createCuboidData, @@ -224,11 +227,13 @@ export class PrimitiveMesh { /** * Create a plane in XZ facing +Y, centered at the origin. * @param engine - The engine that owns the mesh - * @param options - Shape and mesh creation settings + * @param width - The full size along X in local units + * @param height - The full size along Z in local units + * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createPlane(engine: Engine, options: PlaneMeshOptions = {}): ModelMesh { - const { width = 1, height = width, horizontalSegments = 1, verticalSegments = horizontalSegments } = options; + static createPlane(engine: Engine, width: number, height: number, options: PlaneMeshOptions = {}): ModelMesh { + const { horizontalSegments = 1, verticalSegments = horizontalSegments } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createPlaneData, @@ -240,18 +245,13 @@ export class PrimitiveMesh { /** * Create a cylinder centered on Y with equal end radii. * @param engine - The engine that owns the mesh - * @param options - Shape and mesh creation settings + * @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 createCylinder(engine: Engine, options: CylinderMeshOptions = {}): ModelMesh { - const { - radius = 0.5, - height = 2, - radialSegments = 20, - heightSegments = 1, - caps = PrimitiveMeshCapMode.Both, - angleRange - } = options; + static createCylinder(engine: Engine, radius: number, height: number, options: CylinderMeshOptions = {}): ModelMesh { + const { radialSegments = 20, heightSegments = 1, caps = PrimitiveMeshCapMode.Both, angleRange } = options; const startAngle = angleRange?.x ?? 0; return PrimitiveMesh._createMesh( engine, @@ -274,19 +274,20 @@ export class PrimitiveMesh { /** * Create a truncated cone centered on Y with independently sized ends. * @param engine - The engine that owns the mesh - * @param options - Shape and mesh creation settings + * @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 createTruncatedCone(engine: Engine, options: TruncatedConeMeshOptions = {}): ModelMesh { - const { - topRadius = 0.25, - bottomRadius = 0.5, - height = 2, - radialSegments = 20, - heightSegments = 1, - caps = PrimitiveMeshCapMode.Both, - angleRange - } = options; + static createTruncatedCone( + engine: Engine, + topRadius: number, + bottomRadius: number, + height: number, + options: TruncatedConeMeshOptions = {} + ): ModelMesh { + const { radialSegments = 20, heightSegments = 1, caps = PrimitiveMeshCapMode.Both, angleRange } = options; const startAngle = angleRange?.x ?? 0; return PrimitiveMesh._createMesh( engine, @@ -309,11 +310,13 @@ export class PrimitiveMesh { /** * Create a cone centered on Y with its tip at the top. * @param engine - The engine that owns the mesh - * @param options - Shape and mesh creation settings + * @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, options: ConeMeshOptions = {}): ModelMesh { - const { radius = 0.5, height = 2, radialSegments = 20, heightSegments = 1, cap = true, angleRange } = options; + static createCone(engine: Engine, radius: number, height: number, options: ConeMeshOptions = {}): ModelMesh { + const { radialSegments = 20, heightSegments = 1, cap = true, angleRange } = options; const startAngle = angleRange?.x ?? 0; return PrimitiveMesh._createMesh( engine, @@ -326,11 +329,13 @@ export class PrimitiveMesh { /** * Create a capsule centered on Y. * @param engine - The engine that owns the mesh - * @param options - Shape and mesh creation settings + * @param radius - The radius of the cylinder and hemispherical ends in local units + * @param height - The straight cylindrical section height in local units; total height is `height + 2 * radius` + * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createCapsule(engine: Engine, options: CapsuleMeshOptions = {}): ModelMesh { - const { radius = 0.5, height = 2, radialSegments = 6, capSegments = radialSegments, heightSegments = 1 } = options; + static createCapsule(engine: Engine, radius: number, height: number, options: CapsuleMeshOptions = {}): ModelMesh { + const { radialSegments = 6, capSegments = radialSegments, heightSegments = 1 } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createCapsuleData, @@ -342,18 +347,13 @@ export class PrimitiveMesh { /** * Create a torus centered in XY around Z. * @param engine - The engine that owns the mesh - * @param options - Shape and mesh creation settings + * @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 createTorus(engine: Engine, options: TorusMeshOptions = {}): ModelMesh { - const { - radius = 0.5, - tubeRadius = 0.1, - tubularSegments = 30, - radialSegments = 30, - angleRange, - tubeRange - } = options; + static createTorus(engine: Engine, radius: number, tubeRadius: number, options: TorusMeshOptions = {}): ModelMesh { + const { tubularSegments = 30, radialSegments = 30, angleRange, tubeRange } = options; const startAngle = angleRange?.x ?? 0; const tubeStartAngle = tubeRange?.x ?? 0; return PrimitiveMesh._createMesh( @@ -376,11 +376,12 @@ export class PrimitiveMesh { /** * Create a filled disk or sector in XY facing +Z. * @param engine - The engine that owns the mesh - * @param options - Shape and mesh creation settings + * @param radius - The radius in local units + * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createCircle(engine: Engine, options: CircleMeshOptions = {}): ModelMesh { - const { radius = 0.5, segments = 32, angleRange } = options; + static createCircle(engine: Engine, radius: number, options: CircleMeshOptions = {}): ModelMesh { + const { segments = 32, angleRange } = options; const startAngle = angleRange?.x ?? 0; return PrimitiveMesh._createMesh( engine, @@ -393,17 +394,18 @@ export class PrimitiveMesh { /** * Create a ring or ring sector in XY facing +Z. * @param engine - The engine that owns the mesh - * @param options - Shape and mesh creation settings + * @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 createRing(engine: Engine, options: RingMeshOptions = {}): ModelMesh { - const { - outerRadius = 0.5, - innerRadius = outerRadius / 2, - radialSegments = 32, - widthSegments = 1, - angleRange - } = options; + static createRing( + engine: Engine, + outerRadius: number, + innerRadius: number, + options: RingMeshOptions = {} + ): ModelMesh { + const { radialSegments = 32, widthSegments = 1, angleRange } = options; const startAngle = angleRange?.x ?? 0; return PrimitiveMesh._createMesh( engine, @@ -416,11 +418,12 @@ export class PrimitiveMesh { /** * Create a regular tetrahedron or its spherical subdivision. * @param engine - The engine that owns the mesh - * @param options - Shape and mesh creation settings + * @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, options: RegularPolyhedronMeshOptions = {}): ModelMesh { - const { radius = 0.5, segments = 1 } = options; + static createTetrahedron(engine: Engine, radius: number, options: RegularPolyhedronMeshOptions = {}): ModelMesh { + const { segments = 1 } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createRegularPolyhedronData, @@ -432,11 +435,12 @@ export class PrimitiveMesh { /** * Create a regular octahedron or its spherical subdivision. * @param engine - The engine that owns the mesh - * @param options - Shape and mesh creation settings + * @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, options: RegularPolyhedronMeshOptions = {}): ModelMesh { - const { radius = 0.5, segments = 1 } = options; + static createOctahedron(engine: Engine, radius: number, options: RegularPolyhedronMeshOptions = {}): ModelMesh { + const { segments = 1 } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createRegularPolyhedronData, @@ -448,11 +452,12 @@ export class PrimitiveMesh { /** * Create a regular icosahedron or its spherical subdivision. * @param engine - The engine that owns the mesh - * @param options - Shape and mesh creation settings + * @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, options: RegularPolyhedronMeshOptions = {}): ModelMesh { - const { radius = 0.5, segments = 1 } = options; + static createIcosahedron(engine: Engine, radius: number, options: RegularPolyhedronMeshOptions = {}): ModelMesh { + const { segments = 1 } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createRegularPolyhedronData, @@ -464,11 +469,12 @@ export class PrimitiveMesh { /** * Create a regular dodecahedron or its spherical subdivision. * @param engine - The engine that owns the mesh - * @param options - Shape and mesh creation settings + * @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, options: RegularPolyhedronMeshOptions = {}): ModelMesh { - const { radius = 0.5, segments = 1 } = options; + static createDodecahedron(engine: Engine, radius: number, options: RegularPolyhedronMeshOptions = {}): ModelMesh { + const { segments = 1 } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createRegularPolyhedronData, @@ -481,7 +487,7 @@ export class PrimitiveMesh { * Revolve a radius-height profile around Y. * @param engine - The engine that owns the mesh * @param profile - The radius-height profile, with at least two points; X is radius and Y is height - * @param options - Shape and mesh creation settings + * @param options - Optional mesh generation settings * @returns The generated mesh */ static createLathe(engine: Engine, profile: readonly Vector2[], options: LatheMeshOptions = {}): ModelMesh { @@ -499,11 +505,17 @@ export class PrimitiveMesh { * Sweep a circular cross-section along a path. * @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 options - Shape and mesh creation settings + * @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[], options: TubeMeshOptions = {}): ModelMesh { - const { radius = 0.5, tubularSegments = 64, radialSegments = 8, closed = false } = options; + static createTube( + engine: Engine, + path: readonly Vector3[], + radius: number, + options: TubeMeshOptions = {} + ): ModelMesh { + const { tubularSegments = 64, radialSegments = 8, closed = false } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createTubeData, @@ -516,7 +528,7 @@ export class PrimitiveMesh { * Triangulate one or more polygons in XY facing +Z. * @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 - Shape and mesh creation settings + * @param options - Optional mesh generation settings * @returns The generated mesh */ static createPolygon( @@ -535,28 +547,30 @@ export class PrimitiveMesh { /** * Extrude polygons along +Z or a spatial path. * @remarks - * Providing `path` selects path extrusion and ignores depth and bevel settings. - * Without a path, extrusion follows +Z and ignores `closed`. + * A path selects path extrusion and ignores bevel settings. + * A numeric depth extrudes along +Z and ignores `closed`. * @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 depthOrPath - The total depth along +Z, including bevels, or the path points with at least two distinct points * @param options - Linear or path extrusion settings * @returns The generated mesh */ static createExtrusion( engine: Engine, shapes: readonly Vector2[] | PolygonShape | readonly PolygonShape[], + depthOrPath: number | readonly Vector3[], options: LinearExtrusionMeshOptions | PathExtrusionMeshOptions = {} ): ModelMesh { const { - depth = 1, - path, steps = 1, closed = false, bevelSize = 0, bevelThickness = bevelSize, bevelOffset = 0, bevelSegments = 3 - }: LinearExtrusionMeshOptions & Partial = options; + }: LinearExtrusionMeshOptions & PathExtrusionMeshOptions = options; + const path = typeof depthOrPath === "number" ? undefined : depthOrPath; + const depth = typeof depthOrPath === "number" ? depthOrPath : 0; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createExtrusionData, @@ -576,13 +590,24 @@ export class PrimitiveMesh { } /** - * Create a closed torus knot. + * Create a closed torus knot. At least one of `p` and `q` must be nonzero. * @param engine - The engine that owns the mesh - * @param options - Shape and mesh creation settings + * @param radius - The base radius of the torus in local units + * @param tubeRadius - The radius of the tube cross-section in local units + * @param p - The signed integer revolution count around the torus axis; negative values reverse the winding + * @param q - The signed integer revolution count through the torus hole; negative values reverse the winding + * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createTorusKnot(engine: Engine, options: TorusKnotMeshOptions = {}): ModelMesh { - const { radius = 0.5, tubeRadius = 0.1, p = 2, q = 3, tubularSegments = 64, radialSegments = 8 } = options; + static createTorusKnot( + engine: Engine, + radius: number, + tubeRadius: number, + p: number, + q: number, + options: TorusKnotMeshOptions = {} + ): ModelMesh { + const { tubularSegments = 64, radialSegments = 8 } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createTorusKnotData, @@ -596,11 +621,22 @@ export class PrimitiveMesh { * @remarks * UVs preserve the cuboid's face orientations and account for rounded edge length. * @param engine - The engine that owns the mesh - * @param options - Shape and mesh creation settings + * @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 createRoundedCuboid(engine: Engine, options: RoundedCuboidMeshOptions = {}): ModelMesh { - const { width = 1, height = width, depth = width, cornerRadius = 0.1, segments = 2 } = options; + static createRoundedCuboid( + engine: Engine, + width: number, + height: number, + depth: number, + cornerRadius: number, + options: RoundedCuboidMeshOptions = {} + ): ModelMesh { + const { segments = 2 } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createRoundedCuboidData, diff --git a/packages/core/src/mesh/PrimitiveMeshOptions.ts b/packages/core/src/mesh/PrimitiveMeshOptions.ts index f30f385741..4350c4e34d 100644 --- a/packages/core/src/mesh/PrimitiveMeshOptions.ts +++ b/packages/core/src/mesh/PrimitiveMeshOptions.ts @@ -1,4 +1,4 @@ -import type { Vector2, Vector3 } from "@galacean/engine-math"; +import type { Vector2 } from "@galacean/engine-math"; import type { PrimitiveMeshCapMode } from "./enums/PrimitiveMeshCapMode"; /** @@ -33,11 +33,6 @@ export interface PolygonShape { * Settings for a sphere or an open spherical section generated from a subdivided cube. */ export interface SphereMeshOptions extends PrimitiveMeshOptions { - /** - * The radius in local units. - * @defaultValue `0.5` - */ - radius?: number; /** * The subdivision level, rounded down and clamped to 1 through 6. * @defaultValue `3` @@ -62,21 +57,6 @@ export interface SphereMeshOptions extends PrimitiveMeshOptions { * Settings for an axis-aligned cuboid centered at the origin. */ export interface CuboidMeshOptions extends PrimitiveMeshOptions { - /** - * The full size along X in local units. - * @defaultValue `1` - */ - width?: number; - /** - * The full size along Y in local units. - * @defaultValue The value of `width`. - */ - height?: number; - /** - * The full size along Z in local units. - * @defaultValue The value of `width`. - */ - depth?: number; /** * The number of subdivisions along X, rounded down with a minimum of 1. * @defaultValue `1` @@ -103,16 +83,6 @@ export interface CuboidMeshOptions extends PrimitiveMeshOptions { * Settings for a plane in XZ facing +Y, centered at the origin. */ export interface PlaneMeshOptions extends PrimitiveMeshOptions { - /** - * The full size along X in local units. - * @defaultValue `1` - */ - width?: number; - /** - * The full size along Z in local units. - * @defaultValue The value of `width`. - */ - height?: number; /** * The number of subdivisions along X, rounded down with a minimum of 1. * @defaultValue `1` @@ -129,16 +99,6 @@ export interface PlaneMeshOptions extends PrimitiveMeshOptions { * Settings for a cylinder centered on Y with equal end radii. */ export interface CylinderMeshOptions extends PrimitiveMeshOptions { - /** - * The radius in local units. - * @defaultValue `0.5` - */ - radius?: number; - /** - * The full size along Y in local units. - * @defaultValue `2` - */ - height?: number; /** * The number of segments around the circumference, rounded down with a minimum of 3. * @defaultValue `20` @@ -171,21 +131,6 @@ export interface CylinderMeshOptions extends PrimitiveMeshOptions { * Settings for a truncated cone centered on Y with independently sized ends. */ export interface TruncatedConeMeshOptions extends PrimitiveMeshOptions { - /** - * The top radius in local units. - * @defaultValue `0.25` - */ - topRadius?: number; - /** - * The bottom radius in local units. - * @defaultValue `0.5` - */ - bottomRadius?: number; - /** - * The full size along Y in local units. - * @defaultValue `2` - */ - height?: number; /** * The number of segments around the circumference, rounded down with a minimum of 3. * @defaultValue `20` @@ -218,16 +163,6 @@ export interface TruncatedConeMeshOptions extends PrimitiveMeshOptions { * Settings for a cone centered on Y with its tip at the top. */ export interface ConeMeshOptions extends PrimitiveMeshOptions { - /** - * The bottom radius in local units. - * @defaultValue `0.5` - */ - radius?: number; - /** - * The full size along Y in local units. - * @defaultValue `2` - */ - height?: number; /** * The number of segments around the circumference, rounded down with a minimum of 3. * @defaultValue `20` @@ -260,16 +195,6 @@ export interface ConeMeshOptions extends PrimitiveMeshOptions { * Settings for a capsule centered on Y. */ export interface CapsuleMeshOptions extends PrimitiveMeshOptions { - /** - * The radius of the cylinder and hemispherical ends in local units. - * @defaultValue `0.5` - */ - radius?: number; - /** - * The straight cylindrical section's height in local units. Total height is `height + 2 * radius`. - * @defaultValue `2` - */ - height?: number; /** * The number of segments around the circumference, rounded down with a minimum of 3. * @defaultValue `6` @@ -291,16 +216,6 @@ export interface CapsuleMeshOptions extends PrimitiveMeshOptions { * Settings for a torus centered in XY around Z. */ export interface TorusMeshOptions extends PrimitiveMeshOptions { - /** - * The distance from the origin to the tube centerline in local units. - * @defaultValue `0.5` - */ - radius?: number; - /** - * The radius of the tube cross-section in local units. - * @defaultValue `0.1` - */ - tubeRadius?: number; /** * The number of segments around the torus, rounded down with a minimum of 1. * @defaultValue `30` @@ -329,11 +244,6 @@ export interface TorusMeshOptions extends PrimitiveMeshOptions { * Settings for a filled disk or sector in XY facing +Z. */ export interface CircleMeshOptions extends PrimitiveMeshOptions { - /** - * The radius in local units. - * @defaultValue `0.5` - */ - radius?: number; /** * The number of segments along the arc, rounded down with a minimum of 3. * @defaultValue `32` @@ -350,16 +260,6 @@ export interface CircleMeshOptions extends PrimitiveMeshOptions { * Settings for a ring or ring sector in XY facing +Z. */ export interface RingMeshOptions extends PrimitiveMeshOptions { - /** - * The outer radius in local units. - * @defaultValue `0.5` - */ - outerRadius?: number; - /** - * The inner radius in local units. - * @defaultValue Half of `outerRadius`. - */ - innerRadius?: number; /** * The number of segments along the arc, rounded down with a minimum of 3. * @defaultValue `32` @@ -381,11 +281,6 @@ export interface RingMeshOptions extends PrimitiveMeshOptions { * Settings shared by tetrahedra, octahedra, icosahedra and dodecahedra. */ export interface RegularPolyhedronMeshOptions extends PrimitiveMeshOptions { - /** - * The distance from the origin to each vertex in local units. - * @defaultValue `0.5` - */ - radius?: number; /** * 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. @@ -415,11 +310,6 @@ export interface LatheMeshOptions extends PrimitiveMeshOptions { * Settings for sweeping a circular cross-section along a polyline. */ export interface TubeMeshOptions extends PrimitiveMeshOptions { - /** - * The radius of the cross-section in local units. - * @defaultValue `0.5` - */ - radius?: number; /** * The number of segments along the resampled path, rounded down with a minimum of 1. * @defaultValue `64` @@ -453,11 +343,6 @@ export interface PolygonMeshOptions extends PrimitiveMeshOptions { * Settings for extruding polygons along +Z. */ export interface LinearExtrusionMeshOptions extends PrimitiveMeshOptions { - /** - * The total extrusion depth in local units, including both bevels. - * @defaultValue `1` - */ - depth?: number; /** * The number of subdivisions along the extrusion, rounded down with a minimum of 1. * @defaultValue `1` @@ -497,10 +382,6 @@ export interface LinearExtrusionMeshOptions extends PrimitiveMeshOptions { * Polygon X and Y coordinates become offsets along the moving cross-section's axes. */ export interface PathExtrusionMeshOptions extends PrimitiveMeshOptions { - /** - * The path points, resampled at equal distances along the polyline. At least two distinct points are required. - */ - path: readonly Vector3[]; /** * 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 `closed` is true. @@ -521,29 +402,9 @@ export interface PathExtrusionMeshOptions extends PrimitiveMeshOptions { } /** - * Settings for a closed torus knot. At least one of `p` and `q` must be nonzero. + * Settings for a closed torus knot. */ export interface TorusKnotMeshOptions extends PrimitiveMeshOptions { - /** - * The base radius of the torus in local units. - * @defaultValue `0.5` - */ - radius?: number; - /** - * The radius of the tube cross-section in local units. - * @defaultValue `0.1` - */ - tubeRadius?: number; - /** - * The signed integer revolution count around the torus axis. Negative values reverse the winding. - * @defaultValue `2` - */ - p?: number; - /** - * The signed integer revolution count through the torus hole. Negative values reverse the winding. - * @defaultValue `3` - */ - q?: number; /** * The number of segments along the knot, rounded down with a minimum of 1. * @defaultValue `64` @@ -560,26 +421,6 @@ export interface TorusKnotMeshOptions extends PrimitiveMeshOptions { * Settings for an axis-aligned cuboid with rounded edges and corners. */ export interface RoundedCuboidMeshOptions extends PrimitiveMeshOptions { - /** - * The full size along X in local units. - * @defaultValue `1` - */ - width?: number; - /** - * The full size along Y in local units. - * @defaultValue The value of `width`. - */ - height?: number; - /** - * The full size along Z in local units. - * @defaultValue The value of `width`. - */ - depth?: number; - /** - * The edge and corner radius in local units, clamped between zero and half the smallest dimension. - * @defaultValue `0.1` - */ - cornerRadius?: number; /** * The rounding subdivision count, rounded down with a minimum of 1. * When `cornerRadius` is positive, each face uses `2 * segments + 1` subdivisions per axis. diff --git a/packages/galacean/README.md b/packages/galacean/README.md index 216cea0a5f..8551c2785b 100644 --- a/packages/galacean/README.md +++ b/packages/galacean/README.md @@ -62,7 +62,7 @@ const meshEntity = rootEntity.createChild("Sphere"); const meshRenderer = meshEntity.addComponent(MeshRenderer); const material = new BlinnPhongMaterial(engine); meshRenderer.setMaterial(material); -meshRenderer.mesh = PrimitiveMesh.createSphere(engine, { radius: 1 }); +meshRenderer.mesh = PrimitiveMesh.createSphere(engine, 1); // Run engine engine.run(); diff --git a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md index af10fe1c48..aa612a61c5 100644 --- a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md +++ b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md @@ -2,32 +2,30 @@ 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). -The table describes meshes created with default options and an entity scale of `(1, 1, 1)`. - -| Primitive | Default extent | Local orientation | -| --------- | ------------------------------------------------ | ---------------------------- | -| Cuboid | width 1, height 1, depth 1 | centered at the origin | -| 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 | +Dimensions are required factory arguments, expressed in local units. The table assumes an entity scale of `(1, 1, 1)`. + +| Primitive | Local extent | Local orientation | +| --------- | ----------------------------------------------------------- | ---------------------------- | +| Cuboid | `width`, `height`, `depth` | centered at the origin | +| Sphere | diameter `2 * radius` | centered at the origin | +| Plane | X size `width`, Z size `height` | lies in XZ and faces +Y | +| Cylinder | radius `radius`, Y size `height` | centered on Y | +| Cone | base radius `radius`, Y size `height` | centered on Y, tip toward +Y | +| Capsule | radius `radius`, total Y size `height + 2 * radius` | centered on Y | +| Torus | outer radius `radius + tubeRadius`, Z size `2 * tubeRadius` | lies in XY around the Z axis | ## Placement consequences - 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. +- A 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. ## Visual and collision geometry -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. +Primitive meshes and collider shapes own independent dimensions. Set collider dimensions from the intended collision geometry; the assigned mesh does not configure them. Collider dimensions are then affected by the Entity's world scale. -Set collider dimensions from the intended collision geometry. Do not infer them from the assigned mesh or assume entity scale repairs a default mismatch. - -Exact option fields and defaults remain declaration-owned. Use this page only for the default spatial semantics that are easy to misremember. +Exact argument meanings, option fields and defaults remain declaration-owned. ## Draw-ready custom mesh @@ -51,19 +49,19 @@ export function createTriangle(engine: Engine, renderer: MeshRenderer): void { ## Procedural generators -Each factory accepts one named options object, with dimensions, subdivision counts and mesh settings in that object. Every shape has a public options type, such as `SphereMeshOptions`; the four regular polyhedra share `RegularPolyhedronMeshOptions`. Query the factory and its options type for fields, units and defaults. +Each factory takes required shape inputs followed by one optional named settings object. Dimensions, radii, contours and paths have no API defaults. Subdivision counts, angular ranges and mesh settings remain optional. Every shape has a public options type, such as `SphereMeshOptions`; the four regular polyhedra share `RegularPolyhedronMeshOptions`. Query the factory and its options type for argument meanings, units and option defaults. -For example, `createSphere(engine, { radius: 1, subdivisions: 3 })` sets radius and subdivision level. `createCuboid(engine, { width: 2 })` creates a cube with all dimensions equal to 2; omitted plane height likewise uses its width. Later plane/cuboid subdivision counts use the first direction by default. +For example, `createSphere(engine, 1, { subdivisions: 3 })` specifies the radius and subdivision level. `createCuboid(engine, 2, 3, 4)` requires all three dimensions. `createPlane(engine, 2, 3)` specifies its X and Z sizes. Later plane/cuboid subdivision counts use the first direction by default. -`createCylinder(engine, { radius, height })` creates equal end radii. Use `createTruncatedCone(engine, { topRadius, bottomRadius, height })` for different radii. Tubes take a required `Vector3` path followed by `TubeMeshOptions`; lathe profiles take a required `Vector2` array followed by `LatheMeshOptions`. +`createCylinder(engine, radius, height)` creates equal end radii. Use `createTruncatedCone(engine, topRadius, bottomRadius, height)` for different radii. Tubes take a required `Vector3` path and radius followed by `TubeMeshOptions`; lathe profiles take a required `Vector2` array followed by `LatheMeshOptions`. -Torus-knot `p` and `q` are signed integer revolution counts, independent of mesh subdivisions. Negative values reverse the corresponding winding direction; zero keeps that angle fixed. +Torus-knot `p` and `q` are required signed integer revolution counts, independent of mesh subdivisions. Negative values reverse the corresponding winding direction; zero keeps that angle fixed. Angles use degrees. Ranges use `Vector2`, with `x` as the start angle and `y` as the end angle, such as `new Vector2(30, 180)`. Spherical sections use `horizontalRange` and `verticalRange` in their options. Cylinder and frustum `caps` use the exported `PrimitiveMeshCapMode` enum: `Both` (default), `Top`, `Bottom`, `None`. Top faces +Y and bottom faces -Y; angular cut boundaries remain open. Cones use a boolean `cap`. Plane is in XZ facing +Y; circles, rings and polygons are in XY facing +Z. Capsule height excludes its hemispheres. -`createSphere(engine, { radius, subdivisions, horizontalRange, verticalRange })` projects a subdivided cube onto a sphere. The subdivision level defaults to 3 and is clamped to 1 through 6. It accepts `horizontalRange` and `verticalRange`. These clip the subdivided surface and leave open boundaries. Horizontal angles start at -X towards +Z, and vertical angles start at +Y. Continuous horizontal intervals such as `new Vector2(350, 370)` cross the seam. Complete spheres and sections use the same subdivision level. +`createSphere(engine, radius, { subdivisions, horizontalRange, verticalRange })` projects a subdivided cube onto a sphere. The subdivision level defaults to 3 and is clamped to 1 through 6. It accepts `horizontalRange` and `verticalRange`. These clip the subdivided surface and leave open boundaries. Horizontal angles start at -X towards +Z, and vertical angles start at +Y. Continuous horizontal intervals such as `new Vector2(350, 370)` cross the seam. Complete spheres and sections use the same subdivision level. -Additional generators include circle, ring, four regular polyhedra, lathe, tube, polygon, extrusion, torus knot and rounded cuboid. Angle ranges belong to options. A ring's omitted `innerRadius` is half its `outerRadius`. Contours and lathe profiles use `Vector2` arrays; paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points outside the mesh API. A simple polygon is a point array; holes use `{ points, holes }`. Extrusion takes `LinearExtrusionMeshOptions` with optional `depth`, or `PathExtrusionMeshOptions` with a required `path`. Each interface declares only its mode's settings. Providing `path` selects path extrusion and ignores depth and bevel settings; without a path, `closed` is ignored. Straight extrusion defaults to no bevel; a positive `bevelSize` enables it, with `bevelThickness` defaulting to the same value. Path extrusion has no bevels. +Additional generators include circle, ring, four regular polyhedra, lathe, tube, polygon, extrusion, torus knot and rounded cuboid. Angle ranges belong to options. Rings require the outer radius first, followed by the inner radius. Contours and lathe profiles use `Vector2` arrays; paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points outside the mesh API. A simple polygon is a point array; holes use `{ points, holes }`. Extrusion takes a required numeric depth or `Vector3` path as its third argument, followed by `LinearExtrusionMeshOptions` or `PathExtrusionMeshOptions`. Each interface declares its mode's optional settings. A path selects path extrusion and ignores bevel settings; a numeric depth extrudes along +Z and ignores `closed`. Straight extrusion defaults to no bevel; a positive `bevelSize` enables it, with `bevelThickness` defaulting to the same value. Path extrusion has no bevels. For straight extrusion, `bevelOffset` shifts the side-wall outline and defaults to `0`. Positive values expand the solid and contract holes; negative values do the reverse. The offset also applies when `bevelSize` is `0`. Bevels are cut into the shifted outline and included in the total `depth`. @@ -75,8 +73,8 @@ Mesh settings share the same options object. `keepData` retains readable CPU att `PrimitiveMeshAsset` is exported from `@galacean/engine` and `@galacean/engine-loader` and covers every `PrimitiveMesh.createX` method. Each asset `type` uses the matching lower-camel name: `sphere`, `cuboid`, `plane`, `cylinder`, `truncatedCone`, `cone`, `capsule`, `torus`, `circle`, `ring`, `tetrahedron`, `octahedron`, `icosahedron`, `dodecahedron`, `lathe`, `tube`, `polygon`, `extrusion`, `torusKnot`, `roundedCuboid`. -JSON keeps the type prefix for geometry inputs and the options object: `{ type: "sphere", sphereOptions: { radius: 1, subdivisions: 3, keepData: true } }`. Each `Options` uses the factory's named configuration fields and omitted defaults. Angular ranges store `Vector2` components as `{ x, y }`, for example `{ type: "circle", circleOptions: { angleRange: { x: 30, y: 180 } } }`. `sphere` uses the subdivided-cube algorithm; `sphereOptions.subdivisions` sets its subdivision level. `cylinderOptions.radius` controls both end radii; unequal radii use `truncatedConeOptions.topRadius` and `truncatedConeOptions.bottomRadius`. +JSON keeps the type prefix for required geometry inputs and the optional settings object: `{ type: "sphere", sphereRadius: 1, sphereOptions: { subdivisions: 3, keepData: true } }`. Each `Options` uses the factory's named configuration fields and omitted defaults. Angular ranges store `Vector2` components as `{ x, y }`, for example `{ type: "circle", circleRadius: 1, circleOptions: { angleRange: { x: 30, y: 180 } } }`. `sphere` uses the subdivided-cube algorithm; `sphereOptions.subdivisions` sets its subdivision level. `cylinderRadius` controls both end radii; unequal radii use `truncatedConeTopRadius` and `truncatedConeBottomRadius`. TypeScript assets use `PrimitiveMeshCapMode` for `caps`; JSON stores its string values `"both"`, `"top"`, `"bottom"`, `"none"`. -Serialized profiles and contours use `{ x, y }`; paths use `{ x, y, z }`. `polygonShapes` and `extrusionShapes` are arrays of `{ points, holes? }`. Straight extrusion uses `extrusionOptions.depth`; path extrusion uses `extrusionOptions.path` and ignores depth and bevel settings. Set `extrusionOptions.closed` to `true` for a closed path without end caps. Editor previews and saved assets must select the same factory and parameters. +Serialized profiles and contours use `{ x, y }`; paths use `{ x, y, z }`. `polygonShapes` and `extrusionShapes` are arrays of `{ points, holes? }`. Straight extrusion requires `extrusionDepth`; path extrusion requires `extrusionPath` and ignores bevel settings. Set `extrusionOptions.closed` to `true` for a closed path without end caps. Editor previews and saved assets must select the same factory and parameters. diff --git a/packages/loader/src/PrimitiveMeshAsset.ts b/packages/loader/src/PrimitiveMeshAsset.ts index dc914ba9bc..d2ee4af51f 100644 --- a/packages/loader/src/PrimitiveMeshAsset.ts +++ b/packages/loader/src/PrimitiveMeshAsset.ts @@ -33,64 +33,160 @@ type SerializedPolygonShape = { }; /** - * Serialized data for every primitive mesh factory, using the same option defaults and constraints. - * Vector inputs store their components as plain JSON objects. + * 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?: SerializedPrimitiveMeshOptions; } | { 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. + */ + planeHeight: number; planeOptions?: PlaneMeshOptions; } | { type: "cylinder"; + /** + * The radius in local units. + */ + cylinderRadius: number; + /** + * The full size along Y in local units. + */ + cylinderHeight: number; cylinderOptions?: SerializedPrimitiveMeshOptions; } | { 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?: SerializedPrimitiveMeshOptions; } | { type: "cone"; + /** + * The bottom radius in local units. + */ + coneRadius: number; + /** + * The full size along Y in local units. + */ + coneHeight: number; coneOptions?: SerializedPrimitiveMeshOptions; } | { 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 `capsuleHeight + 2 * capsuleRadius`. + */ + capsuleHeight: 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?: SerializedPrimitiveMeshOptions; } | { type: "circle"; + /** + * The radius in local units. + */ + circleRadius: number; circleOptions?: SerializedPrimitiveMeshOptions; } | { type: "ring"; + /** + * The outer radius in local units. + */ + ringOuterRadius: number; + /** + * The inner radius in local units. + */ + ringInnerRadius: number; ringOptions?: SerializedPrimitiveMeshOptions; } | { 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; } | { @@ -101,6 +197,10 @@ export type PrimitiveMeshAsset = | { type: "tube"; tubePath: readonly { x: number; y: number; z: number }[]; + /** + * The radius of the cross-section in local units. + */ + tubeRadius: number; tubeOptions?: TubeMeshOptions; } | { @@ -110,16 +210,59 @@ export type PrimitiveMeshAsset = } | { type: "extrusion"; + /** + * The total extrusion depth in local units, including both bevels. + */ + extrusionDepth: number; extrusionShapes: readonly SerializedPolygonShape[]; - extrusionOptions?: - | LinearExtrusionMeshOptions - | (Omit & { path: readonly { x: number; y: number; z: number }[] }); + extrusionOptions?: LinearExtrusionMeshOptions | PathExtrusionMeshOptions; + } + | { + type: "extrusion"; + /** + * The path points in local coordinates. + */ + extrusionPath: readonly { x: number; y: number; z: number }[]; + extrusionShapes: readonly SerializedPolygonShape[]; + extrusionOptions?: LinearExtrusionMeshOptions | PathExtrusionMeshOptions; } | { 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. + */ + torusKnotP: number; + /** + * The signed integer revolution count through the torus hole. + */ + torusKnotQ: 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 004e1e501d..2285751e1f 100644 --- a/packages/loader/src/PrimitiveMeshLoader.ts +++ b/packages/loader/src/PrimitiveMeshLoader.ts @@ -25,33 +25,65 @@ class PrimitiveMeshLoader extends Loader { const { type } = data; switch (type) { case "sphere": - return PrimitiveMesh.createSphere(engine, this._parseRangeOptions(data.sphereOptions)); + return PrimitiveMesh.createSphere(engine, data.sphereRadius, this._parseRangeOptions(data.sphereOptions)); case "cuboid": - return PrimitiveMesh.createCuboid(engine, data.cuboidOptions); + return PrimitiveMesh.createCuboid( + engine, + data.cuboidWidth, + data.cuboidHeight, + data.cuboidDepth, + data.cuboidOptions + ); case "plane": - return PrimitiveMesh.createPlane(engine, data.planeOptions); + return PrimitiveMesh.createPlane(engine, data.planeWidth, data.planeHeight, data.planeOptions); case "cylinder": - return PrimitiveMesh.createCylinder(engine, this._parseRangeOptions(data.cylinderOptions)); + return PrimitiveMesh.createCylinder( + engine, + data.cylinderRadius, + data.cylinderHeight, + this._parseRangeOptions(data.cylinderOptions) + ); case "truncatedCone": - return PrimitiveMesh.createTruncatedCone(engine, this._parseRangeOptions(data.truncatedConeOptions)); + return PrimitiveMesh.createTruncatedCone( + engine, + data.truncatedConeTopRadius, + data.truncatedConeBottomRadius, + data.truncatedConeHeight, + this._parseRangeOptions(data.truncatedConeOptions) + ); case "cone": - return PrimitiveMesh.createCone(engine, this._parseRangeOptions(data.coneOptions)); + return PrimitiveMesh.createCone( + engine, + data.coneRadius, + data.coneHeight, + this._parseRangeOptions(data.coneOptions) + ); case "capsule": - return PrimitiveMesh.createCapsule(engine, data.capsuleOptions); + return PrimitiveMesh.createCapsule(engine, data.capsuleRadius, data.capsuleHeight, data.capsuleOptions); case "torus": - return PrimitiveMesh.createTorus(engine, this._parseRangeOptions(data.torusOptions)); + return PrimitiveMesh.createTorus( + engine, + data.torusRadius, + data.torusTubeRadius, + this._parseRangeOptions(data.torusOptions) + ); case "circle": - return PrimitiveMesh.createCircle(engine, this._parseRangeOptions(data.circleOptions)); + return PrimitiveMesh.createCircle(engine, data.circleRadius, this._parseRangeOptions(data.circleOptions)); case "ring": - return PrimitiveMesh.createRing(engine, this._parseRangeOptions(data.ringOptions)); + return PrimitiveMesh.createRing( + engine, + data.ringOuterRadius, + data.ringInnerRadius, + this._parseRangeOptions(data.ringOptions) + ); case "tetrahedron": - return PrimitiveMesh.createTetrahedron(engine, data.tetrahedronOptions); + return PrimitiveMesh.createTetrahedron(engine, data.tetrahedronRadius, data.tetrahedronOptions); case "octahedron": - return PrimitiveMesh.createOctahedron(engine, data.octahedronOptions); + return PrimitiveMesh.createOctahedron(engine, data.octahedronRadius, data.octahedronOptions); case "icosahedron": - return PrimitiveMesh.createIcosahedron(engine, data.icosahedronOptions); + return PrimitiveMesh.createIcosahedron(engine, data.icosahedronRadius, data.icosahedronOptions); case "dodecahedron": - return PrimitiveMesh.createDodecahedron(engine, data.dodecahedronOptions); + return PrimitiveMesh.createDodecahedron(engine, data.dodecahedronRadius, data.dodecahedronOptions); case "lathe": return PrimitiveMesh.createLathe( engine, @@ -59,22 +91,34 @@ class PrimitiveMeshLoader extends Loader { this._parseRangeOptions(data.latheOptions) ); case "tube": - return PrimitiveMesh.createTube(engine, this._parseVector3s(data.tubePath), data.tubeOptions); + 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 "extrusion": { - const shapes = this._parseShapes(data.extrusionShapes); - const options = data.extrusionOptions; + case "extrusion": return PrimitiveMesh.createExtrusion( engine, - shapes, - options && "path" in options ? { ...options, path: this._parseVector3s(options.path) } : options + this._parseShapes(data.extrusionShapes), + "extrusionPath" in data ? this._parseVector3s(data.extrusionPath) : data.extrusionDepth, + data.extrusionOptions ); - } case "torusKnot": - return PrimitiveMesh.createTorusKnot(engine, data.torusKnotOptions); + return PrimitiveMesh.createTorusKnot( + engine, + data.torusKnotRadius, + data.torusKnotTubeRadius, + data.torusKnotP, + data.torusKnotQ, + data.torusKnotOptions + ); case "roundedCuboid": - return PrimitiveMesh.createRoundedCuboid(engine, data.roundedCuboidOptions); + 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}`); diff --git a/tests/package-consumer/PrimitiveMeshApi.test.ts b/tests/package-consumer/PrimitiveMeshApi.test.ts index 46ae5c221e..f660a96b6d 100644 --- a/tests/package-consumer/PrimitiveMeshApi.test.ts +++ b/tests/package-consumer/PrimitiveMeshApi.test.ts @@ -55,6 +55,21 @@ it.each(["PrimitiveMeshApi", "PrimitiveMeshAsset"])("type-checks %s and rejects 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( examples.flatMap((call) => { const options = call.arguments[optionsIndex]; @@ -66,8 +81,14 @@ it.each(["PrimitiveMeshApi", "PrimitiveMeshAsset"])("type-checks %s and rejects : []; }) ); - for (const field of optionsType.getProperties()) { - expect(documentedFields.has(field.name), `Missing option example: ${factory.name}.${field.name}`).toBe(true); + 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 + ); + } } } diff --git a/tests/package-consumer/fixtures/PrimitiveMeshApi.ts b/tests/package-consumer/fixtures/PrimitiveMeshApi.ts index 40e3557257..9cef9d0f79 100644 --- a/tests/package-consumer/fixtures/PrimitiveMeshApi.ts +++ b/tests/package-consumer/fixtures/PrimitiveMeshApi.ts @@ -38,32 +38,20 @@ const path: readonly Vector3[] = [new Vector3(0, 0, 0), new Vector3(0, 1, 1), ne const commonOptions = { keepData: true } satisfies PrimitiveMeshOptions; const sphereOptions = { - radius: 1, subdivisions: 4, horizontalRange: new Vector2(350, 370), verticalRange: new Vector2(30, 150), keepData: true } satisfies SphereMeshOptions; const cuboidOptions = { - width: 2, - height: 3, - depth: 4, widthSegments: 2, heightSegments: 3, depthSegments: 4, separateMaterials: true, keepData: true } satisfies CuboidMeshOptions; -const planeOptions = { - width: 10, - height: 5, - horizontalSegments: 4, - verticalSegments: 2, - keepData: true -} satisfies PlaneMeshOptions; +const planeOptions = { horizontalSegments: 4, verticalSegments: 2, keepData: true } satisfies PlaneMeshOptions; const cylinderOptions = { - radius: 1, - height: 2, radialSegments: 32, heightSegments: 4, caps: PrimitiveMeshCapMode.Bottom, @@ -72,9 +60,6 @@ const cylinderOptions = { keepData: true } satisfies CylinderMeshOptions; const truncatedConeOptions = { - topRadius: 0.5, - bottomRadius: 1, - height: 2, radialSegments: 32, heightSegments: 4, caps: PrimitiveMeshCapMode.None, @@ -83,8 +68,6 @@ const truncatedConeOptions = { keepData: true } satisfies TruncatedConeMeshOptions; const coneOptions = { - radius: 1, - height: 2, radialSegments: 32, heightSegments: 4, cap: false, @@ -93,48 +76,30 @@ const coneOptions = { keepData: true } satisfies ConeMeshOptions; const capsuleOptions = { - radius: 0.5, - height: 2, radialSegments: 12, capSegments: 6, heightSegments: 3, keepData: true } satisfies CapsuleMeshOptions; const torusOptions = { - radius: 1, - tubeRadius: 0.2, tubularSegments: 64, radialSegments: 16, angleRange: new Vector2(0, 270), tubeRange: new Vector2(0, 180), keepData: true } satisfies TorusMeshOptions; -const circleOptions = { - radius: 1, - segments: 32, - angleRange: new Vector2(0, 180), - keepData: true -} satisfies CircleMeshOptions; +const circleOptions = { segments: 32, angleRange: new Vector2(0, 180), keepData: true } satisfies CircleMeshOptions; const ringOptions = { - outerRadius: 1, - innerRadius: 0.5, radialSegments: 32, widthSegments: 4, angleRange: new Vector2(0, 270), keepData: true } satisfies RingMeshOptions; -const regularPolyhedronOptions = { radius: 1, segments: 2, keepData: true } satisfies RegularPolyhedronMeshOptions; +const regularPolyhedronOptions = { segments: 2, keepData: true } satisfies RegularPolyhedronMeshOptions; const latheOptions = { segments: 32, angleRange: new Vector2(0, 270), keepData: true } satisfies LatheMeshOptions; -const tubeOptions = { - radius: 0.1, - tubularSegments: 64, - radialSegments: 8, - closed: true, - keepData: true -} satisfies TubeMeshOptions; +const tubeOptions = { tubularSegments: 64, radialSegments: 8, closed: true, keepData: true } satisfies TubeMeshOptions; const polygonOptions = { separateMaterials: true, keepData: true } satisfies PolygonMeshOptions; const linearExtrusionOptions = { - depth: 2, steps: 4, bevelSize: 0.1, bevelThickness: 0.2, @@ -143,158 +108,207 @@ const linearExtrusionOptions = { separateMaterials: true, keepData: true } satisfies LinearExtrusionMeshOptions; +const torusKnotOptions = { tubularSegments: 64, radialSegments: 12, keepData: true } satisfies TorusKnotMeshOptions; +const roundedCuboidOptions = { + segments: 4, + separateMaterials: true, + keepData: true +} satisfies RoundedCuboidMeshOptions; const pathExtrusionOptions = { - path, steps: 32, closed: true, separateMaterials: true, keepData: true } satisfies PathExtrusionMeshOptions; const extrusionOptions: LinearExtrusionMeshOptions | PathExtrusionMeshOptions = pathExtrusionOptions; -const torusKnotOptions = { - radius: 1, - tubeRadius: 0.2, - p: 2, - q: 3, - tubularSegments: 64, - radialSegments: 12, - keepData: true -} satisfies TorusKnotMeshOptions; -const roundedCuboidOptions = { - width: 2, - height: 3, - depth: 4, - cornerRadius: 0.2, - segments: 4, - separateMaterials: true, - keepData: true -} satisfies RoundedCuboidMeshOptions; -// Every factory lists its default call and a configuration containing all supported fields +// Every factory lists its required inputs and a configuration containing all optional fields const meshes: ModelMesh[] = [ - PrimitiveMesh.createSphere(engine), - PrimitiveMesh.createSphere(engine, sphereOptions), - PrimitiveMesh.createCuboid(engine), - PrimitiveMesh.createCuboid(engine, cuboidOptions), - PrimitiveMesh.createPlane(engine), - PrimitiveMesh.createPlane(engine, planeOptions), - PrimitiveMesh.createCylinder(engine), - PrimitiveMesh.createCylinder(engine, cylinderOptions), - PrimitiveMesh.createTruncatedCone(engine), - PrimitiveMesh.createTruncatedCone(engine, truncatedConeOptions), - PrimitiveMesh.createCone(engine), - PrimitiveMesh.createCone(engine, coneOptions), - PrimitiveMesh.createCapsule(engine), - PrimitiveMesh.createCapsule(engine, capsuleOptions), - PrimitiveMesh.createTorus(engine), - PrimitiveMesh.createTorus(engine, torusOptions), - PrimitiveMesh.createCircle(engine), - PrimitiveMesh.createCircle(engine, circleOptions), - PrimitiveMesh.createRing(engine), - PrimitiveMesh.createRing(engine, ringOptions), - PrimitiveMesh.createTetrahedron(engine), - PrimitiveMesh.createTetrahedron(engine, regularPolyhedronOptions), - PrimitiveMesh.createOctahedron(engine), - PrimitiveMesh.createOctahedron(engine, regularPolyhedronOptions), - PrimitiveMesh.createIcosahedron(engine), - PrimitiveMesh.createIcosahedron(engine, regularPolyhedronOptions), - PrimitiveMesh.createDodecahedron(engine), - PrimitiveMesh.createDodecahedron(engine, regularPolyhedronOptions), + 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.createLathe(engine, profile), PrimitiveMesh.createLathe(engine, profile, latheOptions), - PrimitiveMesh.createTube(engine, path), - PrimitiveMesh.createTube(engine, path, tubeOptions), + PrimitiveMesh.createTube(engine, path, 0.5), + PrimitiveMesh.createTube(engine, path, 0.1, tubeOptions), PrimitiveMesh.createPolygon(engine, contour), PrimitiveMesh.createPolygon(engine, contour, polygonOptions), + PrimitiveMesh.createExtrusion(engine, contour, 1), + PrimitiveMesh.createExtrusion(engine, contour, 2, linearExtrusionOptions), + 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.createExtrusion(engine, polygon, 2), + PrimitiveMesh.createExtrusion(engine, polygon, 2, linearExtrusionOptions), PrimitiveMesh.createPolygon(engine, polygons), PrimitiveMesh.createPolygon(engine, polygons, polygonOptions), - PrimitiveMesh.createExtrusion(engine, contour), - PrimitiveMesh.createExtrusion(engine, contour, linearExtrusionOptions), - PrimitiveMesh.createExtrusion(engine, polygon), - PrimitiveMesh.createExtrusion(engine, polygon, linearExtrusionOptions), - PrimitiveMesh.createExtrusion(engine, polygons), - PrimitiveMesh.createExtrusion(engine, polygons, linearExtrusionOptions), - PrimitiveMesh.createExtrusion(engine, contour, pathExtrusionOptions), - PrimitiveMesh.createExtrusion(engine, polygon, pathExtrusionOptions), - PrimitiveMesh.createExtrusion(engine, polygons, pathExtrusionOptions), - PrimitiveMesh.createExtrusion(engine, polygons, extrusionOptions), - PrimitiveMesh.createTorusKnot(engine), - PrimitiveMesh.createTorusKnot(engine, torusKnotOptions), - PrimitiveMesh.createRoundedCuboid(engine), - PrimitiveMesh.createRoundedCuboid(engine, roundedCuboidOptions), - - // Partial configuration and common settings remain convenient - PrimitiveMesh.createSphere(engine, commonOptions), - PrimitiveMesh.createSphere(engine, { radius: 1 }), - PrimitiveMesh.createSphere(engine, { subdivisions: 4 }), - PrimitiveMesh.createRing(engine, { outerRadius: 1 }), - PrimitiveMesh.createCuboid(engine, { width: 2 }), - PrimitiveMesh.createCylinder(engine, { caps: PrimitiveMeshCapMode.Both }), - PrimitiveMesh.createCylinder(engine, { caps: PrimitiveMeshCapMode.Top }), - PrimitiveMesh.createExtrusion(engine, polygon, { path }) + PrimitiveMesh.createExtrusion(engine, polygons, 2), + PrimitiveMesh.createExtrusion(engine, polygons, 2, linearExtrusionOptions), + PrimitiveMesh.createExtrusion(engine, contour, path), + PrimitiveMesh.createExtrusion(engine, contour, path, pathExtrusionOptions), + PrimitiveMesh.createExtrusion(engine, polygon, path), + PrimitiveMesh.createExtrusion(engine, polygon, path, pathExtrusionOptions), + PrimitiveMesh.createExtrusion(engine, polygons, path), + PrimitiveMesh.createExtrusion(engine, polygons, path, pathExtrusionOptions), + PrimitiveMesh.createExtrusion(engine, polygons, path, extrusionOptions), + PrimitiveMesh.createSphere(engine, 1, commonOptions), + PrimitiveMesh.createSphere(engine, 1, { subdivisions: 4 }), + PrimitiveMesh.createCylinder(engine, 0.5, 2, { caps: PrimitiveMeshCapMode.Both }), + PrimitiveMesh.createCylinder(engine, 0.5, 2, { caps: PrimitiveMeshCapMode.Top }) ]; void meshes; -// @ts-expect-error Numeric positional overloads are not part of the API -PrimitiveMesh.createSphere(engine, 1); -// @ts-expect-error Sphere options are an object -PrimitiveMesh.createSphere(engine, false); +// @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 Lathe requires every core shape input +PrimitiveMesh.createLathe(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.createExtrusion(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.createExtrusion(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, { separateMaterials: true }); +PrimitiveMesh.createSphere(engine, 1, { separateMaterials: true }); // @ts-expect-error Planes do not define material groups -PrimitiveMesh.createPlane(engine, { separateMaterials: true }); +PrimitiveMesh.createPlane(engine, 1, 1, { separateMaterials: true }); // @ts-expect-error Tori do not define material groups -PrimitiveMesh.createTorus(engine, { separateMaterials: true }); +PrimitiveMesh.createTorus(engine, 1, 0.2, { separateMaterials: true }); // @ts-expect-error Tubes do not define material groups -PrimitiveMesh.createTube(engine, path, { separateMaterials: true }); +PrimitiveMesh.createTube(engine, path, 0.1, { separateMaterials: 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, { horizontalSegments: 32 }); +PrimitiveMesh.createSphere(engine, 1, { horizontalSegments: 32 }); // @ts-expect-error Angular ranges use Vector2 rather than arrays -PrimitiveMesh.createCircle(engine, { angleRange: [0, 180] }); +PrimitiveMesh.createCircle(engine, 1, { angleRange: [0, 180] }); // @ts-expect-error Runtime ranges require Vector2 instances -PrimitiveMesh.createSphere(engine, { horizontalRange: { x: 0, y: 180 } }); +PrimitiveMesh.createSphere(engine, 1, { horizontalRange: { x: 0, y: 180 } }); // @ts-expect-error A cylinder cap selection must describe a supported combination -PrimitiveMesh.createCylinder(engine, { caps: "left" }); +PrimitiveMesh.createCylinder(engine, 0.5, 2, { caps: "left" }); // @ts-expect-error Cap modes use the exported enum rather than raw strings -PrimitiveMesh.createCylinder(engine, { caps: "top" }); +PrimitiveMesh.createCylinder(engine, 0.5, 2, { caps: "top" }); // @ts-expect-error Truncated cones use the same cap-mode enum -PrimitiveMesh.createTruncatedCone(engine, { caps: "none" }); -// Extra fields from the other mode follow normal structural compatibility -PrimitiveMesh.createExtrusion(engine, polygon, { path, bevelSize: 0.1 }); -PrimitiveMesh.createExtrusion(engine, polygon, { path, bevelOffset: 0.1 }); -PrimitiveMesh.createExtrusion(engine, polygon, { depth: 2, closed: true }); -// @ts-expect-error Bevel offsets use numeric local units -PrimitiveMesh.createExtrusion(engine, polygon, { bevelOffset: "0.1" }); - -const mixedExtrusion = { path, depth: 2 }; -PrimitiveMesh.createExtrusion(engine, polygon, mixedExtrusion); -const beveledPath = { path, bevelSize: 0.1 }; -PrimitiveMesh.createExtrusion(engine, polygon, beveledPath); +PrimitiveMesh.createTruncatedCone(engine, 0.25, 0.5, 2, { caps: "none" }); -// @ts-expect-error Explicit linear settings do not declare a path -const invalidLinearOptions: LinearExtrusionMeshOptions = { path }; +// Fields from the inactive mode follow normal structural compatibility +PrimitiveMesh.createExtrusion(engine, polygon, path, { bevelSize: 0.1 }); +PrimitiveMesh.createExtrusion(engine, polygon, path, { bevelOffset: 0.1 }); +PrimitiveMesh.createExtrusion(engine, polygon, 2, { closed: true }); +// @ts-expect-error Bevel offsets use numeric local units +PrimitiveMesh.createExtrusion(engine, polygon, 2, { bevelOffset: "0.1" }); +// @ts-expect-error Explicit linear settings do not declare path closure +const invalidLinearOptions: LinearExtrusionMeshOptions = { closed: true }; // @ts-expect-error Explicit path settings do not declare bevels -const invalidPathOptions: PathExtrusionMeshOptions = { path, bevelSize: 0.1 }; +const invalidPathOptions: PathExtrusionMeshOptions = { bevelSize: 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); +PrimitiveMesh.createTube(engine, samplePath, 0.1); // @ts-expect-error Extrusion paths accept point arrays -PrimitiveMesh.createExtrusion(engine, polygon, { path: samplePath }); -// @ts-expect-error A lathe requires a profile -PrimitiveMesh.createLathe(engine); -// @ts-expect-error A tube requires a path -PrimitiveMesh.createTube(engine); -// @ts-expect-error A polygon requires contours -PrimitiveMesh.createPolygon(engine); +PrimitiveMesh.createExtrusion(engine, polygon, samplePath); const serializedContour = [ { x: 0, y: 0 }, @@ -312,4 +326,6 @@ 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); +PrimitiveMesh.createTube(engine, serializedPath, 0.1); +// @ts-expect-error Path extrusion points use Vector3 instances +PrimitiveMesh.createExtrusion(engine, polygon, serializedPath); diff --git a/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts index c95daba611..c93799931e 100644 --- a/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts +++ b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts @@ -11,19 +11,20 @@ const everyAssetHasAFactory: Exclude e const sphere: PrimitiveMeshAsset = { type: "sphere", - sphereOptions: { verticalRange: { x: 0, y: 90 }, keepData: true, radius: 1, subdivisions: 3 } + sphereRadius: 1, + sphereOptions: { verticalRange: { x: 0, y: 90 }, keepData: true, subdivisions: 3 } }; const exportedFromEngine: EnginePrimitiveMeshAsset = sphere; const sphereSection: PrimitiveMeshAsset = { type: "sphere", - sphereOptions: { horizontalRange: { x: 350, y: 370 }, verticalRange: { x: 30, y: 150 }, radius: 1, subdivisions: 3 } + sphereRadius: 1, + sphereOptions: { horizontalRange: { x: 350, y: 370 }, verticalRange: { x: 30, y: 150 }, subdivisions: 3 } }; const ungroupedSphere: PrimitiveMeshAsset = { type: "sphere", - sphereOptions: { - // @ts-expect-error Sphere assets do not define material groups - separateMaterials: true - } + sphereRadius: 0.5, + // @ts-expect-error Sphere assets do not define material groups + sphereOptions: { separateMaterials: true } }; const path = [ { x: 0, y: 0, z: 0 }, @@ -39,68 +40,103 @@ const shapes = [ } ] as const; -const tube: PrimitiveMeshAsset = { type: "tube", tubePath: path, tubeOptions: { closed: true } }; +const tube: PrimitiveMeshAsset = { type: "tube", tubeRadius: 0.5, tubePath: path, tubeOptions: { closed: true } }; const polygon: PrimitiveMeshAsset = { type: "polygon", polygonShapes: shapes }; const extrusion: PrimitiveMeshAsset = { type: "extrusion", + extrusionDepth: 2, extrusionShapes: shapes, - extrusionOptions: { bevelSize: 0.1, bevelOffset: 0.2, separateMaterials: true, depth: 2 } + extrusionOptions: { bevelSize: 0.1, bevelOffset: 0.2, separateMaterials: true } }; const pathExtrusion: PrimitiveMeshAsset = { type: "extrusion", + extrusionPath: path, extrusionShapes: shapes, - extrusionOptions: { closed: true, path: path } + extrusionOptions: { closed: true } +}; +const torusKnot: PrimitiveMeshAsset = { + type: "torusKnot", + torusKnotRadius: 0.5, + torusKnotTubeRadius: 0.1, + torusKnotP: -2, + torusKnotQ: -3 }; -const torusKnot: PrimitiveMeshAsset = { type: "torusKnot", torusKnotOptions: { p: -2, q: -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" }; +const missingPath: PrimitiveMeshAsset = { type: "tube", tubeRadius: 0.5 }; // @ts-expect-error Asset paths contain coordinates, not callbacks -const callbackPath: PrimitiveMeshAsset = { type: "tube", tubePath: (t: number) => t }; +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: "extrusion", - extrusionShapes: shapes, - extrusionOptions: { depth: 2, path: path } + extrusionDepth: 2, + extrusionPath: path, + extrusionShapes: shapes }; const beveledPath: PrimitiveMeshAsset = { type: "extrusion", + extrusionPath: path, extrusionShapes: shapes, - extrusionOptions: { bevelSize: 1, path: path } + extrusionOptions: { bevelSize: 1 } }; const offsetPath: PrimitiveMeshAsset = { type: "extrusion", + extrusionPath: path, extrusionShapes: shapes, - extrusionOptions: { bevelOffset: 0.1, path: path } + extrusionOptions: { bevelOffset: 0.1 } }; const closedDepth: PrimitiveMeshAsset = { type: "extrusion", + extrusionDepth: 2, extrusionShapes: shapes, - extrusionOptions: { closed: true, depth: 2 } + extrusionOptions: { closed: 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 Shape options cannot be applied to another primitive -const wrongOptions: PrimitiveMeshAsset = { type: "sphere", sphereOptions: { caps: PrimitiveMeshCapMode.Both } }; -// @ts-expect-error TypeScript assets use the cap-mode enum -const stringCap: PrimitiveMeshAsset = { type: "cylinder", cylinderOptions: { caps: "top" } }; // @ts-expect-error Serialized angular ranges use coordinate objects rather than arrays -const wrongRange: PrimitiveMeshAsset = { type: "circle", circleOptions: { angleRange: [0, 180] } }; -// @ts-expect-error Spheres use one subdivision level rather than independent segment counts -const segmentedSphere: PrimitiveMeshAsset = { type: "sphere", sphereOptions: { horizontalSegments: 32 } }; +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" }; -// @ts-expect-error End radii belong to truncatedCone -const endRadiiAsCylinder: PrimitiveMeshAsset = { type: "cylinder", cylinderOptions: { radiusTop: 1 } }; +const endRadiiAsCylinder: PrimitiveMeshAsset = { + type: "cylinder", + cylinderRadius: 0.5, + cylinderHeight: 2, + // @ts-expect-error End radii belong to truncatedCone + cylinderOptions: { radiusTop: 1 } +}; void [ everyFactoryHasAnAsset, @@ -130,3 +166,13 @@ void [ 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: "extrusion", extrusionShapes: 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/DeviceLost.test.ts b/tests/src/core/DeviceLost.test.ts index 7b013845a6..9a44fc0256 100644 --- a/tests/src/core/DeviceLost.test.ts +++ b/tests/src/core/DeviceLost.test.ts @@ -41,7 +41,7 @@ describe("Device lost test", function () { const meshRenderer = meshEntity.addComponent(MeshRenderer); const material = new BlinnPhongMaterial(engine); meshRenderer.setMaterial(material); - meshRenderer.mesh = PrimitiveMesh.createSphere(engine, { radius: 1 }); + meshRenderer.mesh = PrimitiveMesh.createSphere(engine, 1); engine.update(); diff --git a/tests/src/core/Light.test.ts b/tests/src/core/Light.test.ts index d9dd93a487..e70a7e7173 100644 --- a/tests/src/core/Light.test.ts +++ b/tests/src/core/Light.test.ts @@ -244,7 +244,7 @@ describe("Light test", function () { const skyMaterial = new SkyBoxMaterial(engine); scene.background.mode = BackgroundMode.Sky; sky.material = skyMaterial; - sky.mesh = PrimitiveMesh.createCuboid(engine); + sky.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); ambientLightA = await engine.resourceManager.load({ type: AssetType.AmbientLight, diff --git a/tests/src/core/MeshRenderer.test.ts b/tests/src/core/MeshRenderer.test.ts index 7a4fd6bec7..5fe9b5a9db 100644 --- a/tests/src/core/MeshRenderer.test.ts +++ b/tests/src/core/MeshRenderer.test.ts @@ -38,7 +38,7 @@ describe("MeshRenderer", async function () { it("mesh", () => { // Test set mesh and get mesh work correctly. const mr = cubeEntity.getComponent(MeshRenderer); - const cubeMesh2 = PrimitiveMesh.createCuboid(engine); + const cubeMesh2 = PrimitiveMesh.createCuboid(engine, 1, 1, 1); mr.mesh = cubeMesh2; expect(mr.mesh).to.be.equal(cubeMesh2); expect(cubeMesh2.refCount).to.be.equal(1); @@ -47,7 +47,7 @@ describe("MeshRenderer", async function () { mr.mesh = cubeMesh2; expect(cubeMesh2.refCount).to.be.equal(1); - cubeMesh = PrimitiveMesh.createCuboid(engine, { width: 2 }); + cubeMesh = PrimitiveMesh.createCuboid(engine, 2, 2, 2); mr.mesh = cubeMesh; expect(mr.mesh).to.equal(cubeMesh); expect(cubeMesh2.refCount).to.be.equal(0); diff --git a/tests/src/core/Shader.test.ts b/tests/src/core/Shader.test.ts index 2c91353fc4..4c459924e5 100644 --- a/tests/src/core/Shader.test.ts +++ b/tests/src/core/Shader.test.ts @@ -156,7 +156,7 @@ describe("Shader", () => { const meshRenderer = meshEntity.addComponent(MeshRenderer); const material = new BlinnPhongMaterial(engine); meshRenderer.setMaterial(material); - meshRenderer.mesh = PrimitiveMesh.createSphere(engine, { radius: 1 }); + meshRenderer.mesh = PrimitiveMesh.createSphere(engine, 1); // Call update will compile shader internally engine.update(); @@ -198,7 +198,7 @@ describe("Shader", () => { const meshEntity = scene.createRootEntity("mesh"); const mr = meshEntity.addComponent(MeshRenderer); - mr.mesh = PrimitiveMesh.createCuboid(engine); + mr.mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1); mr.setMaterial(new Material(engine, shader)); // Test that shader compile variant successfully, if use shaderCompiler. 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 5c71220502..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); + 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 f387dfc8ac..1947b1cabf 100644 --- a/tests/src/core/mesh/BlendShapeManager.test.ts +++ b/tests/src/core/mesh/BlendShapeManager.test.ts @@ -217,11 +217,8 @@ describe("BlendShapeManager", () => { ] ); blendShapeWeights0_7.addFrame(frame); - const modelMeshWebgl2 = PrimitiveMesh.createCuboid(engineWebGL2, { + const modelMeshWebgl2 = PrimitiveMesh.createCuboid(engineWebGL2, 1, 1, 1, { keepData: true, - width: 1, - height: 1, - depth: 1, widthSegments: 1, heightSegments: 1, depthSegments: 1 @@ -284,7 +281,7 @@ describe("BlendShapeManager", () => { const skinnedMREntity2 = rootEntity2.createChild("skinnedMR"); const meshRendererWebgl1 = skinnedMREntity2.addComponent(SkinnedMeshRenderer); - const modelMeshWebgl1 = PrimitiveMesh.createCuboid(engineWebGL1, { width: 0.5 }); + const modelMeshWebgl1 = PrimitiveMesh.createCuboid(engineWebGL1, 0.5, 0.5, 0.5); modelMeshWebgl1.addBlendShape(blendShapeWeights0_5); modelMeshWebgl1.addBlendShape(blendShapeWeights0_7); modelMeshWebgl1.addBlendShape(blendShapeWeights0_7); @@ -302,7 +299,7 @@ describe("BlendShapeManager", () => { }); it("_addBlendShape and _clearBlendShapes", () => { - const modelMesh = PrimitiveMesh.createPlane(engineWebGL2); + const modelMesh = PrimitiveMesh.createPlane(engineWebGL2, 1, 1); modelMesh.addBlendShape(new BlendShape("BlendShape1")); modelMesh.addBlendShape(new BlendShape("BlendShape2")); expect(modelMesh.blendShapeCount).to.be.equal(2); @@ -318,7 +315,7 @@ describe("BlendShapeManager", () => { }); it("_update", () => { - const modelMesh = PrimitiveMesh.createPlane(engineWebGL2); + 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)]); @@ -328,7 +325,7 @@ describe("BlendShapeManager", () => { modelMesh.uploadData(true); }).to.throw("BlendShape frame deltaPositions length must same with mesh vertexCount"); - const modelMesh2 = PrimitiveMesh.createPlane(engineWebGL2); + const modelMesh2 = PrimitiveMesh.createPlane(engineWebGL2, 1, 1); blendShape.frames[0].deltaPositions = [ new Vector3(1, 0, 0), new Vector3(0, 1, 1), @@ -338,7 +335,7 @@ describe("BlendShapeManager", () => { modelMesh2.addBlendShape(blendShape); modelMesh2.uploadData(true); - const modelMesh3 = PrimitiveMesh.createCuboid(engineWebGL2); + const modelMesh3 = PrimitiveMesh.createCuboid(engineWebGL2, 1, 1, 1); modelMesh3.addBlendShape(blendShape); // Test that _update throw error if use released blendShape. expect(() => { diff --git a/tests/src/core/mesh/PrimitiveMesh.test.ts b/tests/src/core/mesh/PrimitiveMesh.test.ts index a43b909251..10f8052931 100644 --- a/tests/src/core/mesh/PrimitiveMesh.test.ts +++ b/tests/src/core/mesh/PrimitiveMesh.test.ts @@ -21,11 +21,7 @@ describe("PrimitiveMesh", () => { it("createSphere", () => { const radius = 2.333; const subdivisions = 3.2; - const sphereMesh = PrimitiveMesh.createSphere(engine, { - keepData: true, - radius, - subdivisions - }); + const sphereMesh = PrimitiveMesh.createSphere(engine, radius, { keepData: true, subdivisions }); expect(sphereMesh.vertexCount).equal(417); expect(sphereMesh.vertexElements.length).equal(4); @@ -40,11 +36,8 @@ describe("PrimitiveMesh", () => { const width = 2.3; const height = 3.2; const depth = 4.5; - const cuboidMesh = PrimitiveMesh.createCuboid(engine, { + const cuboidMesh = PrimitiveMesh.createCuboid(engine, width, height, depth, { keepData: true, - width, - height, - depth, widthSegments: 1, heightSegments: 1, depthSegments: 1 @@ -67,11 +60,8 @@ describe("PrimitiveMesh", () => { const heightSegments = 1.00001; const floorRadialSegments = Math.floor(radialSegments); const floorHeightSegments = Math.floor(heightSegments); - const truncatedConeMesh = PrimitiveMesh.createTruncatedCone(engine, { + const truncatedConeMesh = PrimitiveMesh.createTruncatedCone(engine, radiusTop, radiusBottom, height, { keepData: true, - topRadius: radiusTop, - bottomRadius: radiusBottom, - height, radialSegments, heightSegments }); @@ -98,11 +88,9 @@ describe("PrimitiveMesh", () => { const floorRadialSegments = Math.floor(radialSegments); const floorTubularSegments = Math.floor(tubularSegments); const arc = 180; - const torusMesh = PrimitiveMesh.createTorus(engine, { + const torusMesh = PrimitiveMesh.createTorus(engine, radius, tubeRadius, { keepData: true, angleRange: new Vector2(0, 0 + arc), - radius, - tubeRadius, tubularSegments, radialSegments }); @@ -124,10 +112,8 @@ describe("PrimitiveMesh", () => { const vSegments = 9.0001; const floorHSegments = Math.floor(hSegments); const floorVSegments = Math.floor(vSegments); - const planeMesh = PrimitiveMesh.createPlane(engine, { + const planeMesh = PrimitiveMesh.createPlane(engine, width, height, { keepData: true, - width, - height, horizontalSegments: hSegments, verticalSegments: vSegments }); @@ -148,10 +134,8 @@ describe("PrimitiveMesh", () => { const heightSegments = 1.00001; const floorRadialSegments = Math.floor(radialSegments); const floorHeightSegments = Math.floor(heightSegments); - const coneMesh = PrimitiveMesh.createCone(engine, { + const coneMesh = PrimitiveMesh.createCone(engine, radius, height, { keepData: true, - radius, - height, radialSegments, heightSegments }); @@ -171,10 +155,8 @@ describe("PrimitiveMesh", () => { const heightSegments = 30.0001; const floorRadialSegments = Math.floor(radialSegments); const floorHeightSegments = Math.floor(heightSegments); - const capsuleMesh = PrimitiveMesh.createCapsule(engine, { + const capsuleMesh = PrimitiveMesh.createCapsule(engine, radius, height, { keepData: true, - radius, - height, radialSegments, capSegments: radialSegments, heightSegments @@ -197,10 +179,8 @@ describe("PrimitiveMesh", () => { const count = segments + 1; if (engine["_hardwareRenderer"].canIUse(GLCapabilityType.elementIndexUint)) { - const mesh = PrimitiveMesh.createPlane(engine, { + const mesh = PrimitiveMesh.createPlane(engine, radius * 2, radius * 2, { keepData: true, - width: radius * 2, - height: radius * 2, horizontalSegments: segments, verticalSegments: segments }); @@ -212,10 +192,8 @@ describe("PrimitiveMesh", () => { expect(mesh.vertexBufferBindings.length).equal(2); } else { expect(() => - PrimitiveMesh.createPlane(engine, { + PrimitiveMesh.createPlane(engine, radius * 2, radius * 2, { keepData: true, - width: radius * 2, - height: radius * 2, horizontalSegments: segments, verticalSegments: segments }) diff --git a/tests/src/core/mesh/ProceduralMesh.test.ts b/tests/src/core/mesh/ProceduralMesh.test.ts index 4924070472..70a851656e 100644 --- a/tests/src/core/mesh/ProceduralMesh.test.ts +++ b/tests/src/core/mesh/ProceduralMesh.test.ts @@ -29,15 +29,12 @@ const polygon = { 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, { keepData: true, radius: 2, subdivisions: 2 })], + ["sphere", () => PrimitiveMesh.createSphere(engine, 2, { keepData: true, subdivisions: 2 })], [ "cuboid", () => - PrimitiveMesh.createCuboid(engine, { + PrimitiveMesh.createCuboid(engine, 1, 1, 1, { keepData: true, - width: 1, - height: 1, - depth: 1, widthSegments: 3, heightSegments: 2, depthSegments: 2 @@ -45,45 +42,19 @@ const creators: [string, () => ModelMesh][] = [ ], [ "plane", - () => - PrimitiveMesh.createPlane(engine, { - keepData: true, - width: 1, - height: 1, - horizontalSegments: 3, - verticalSegments: 2 - }) + () => PrimitiveMesh.createPlane(engine, 1, 1, { keepData: true, horizontalSegments: 3, verticalSegments: 2 }) ], [ "cylinder", () => - PrimitiveMesh.createTruncatedCone(engine, { - keepData: true, - topRadius: 0.25, - bottomRadius: 1, - height: 2, - radialSegments: 12, - heightSegments: 1 - }) - ], - [ - "cone", - () => - PrimitiveMesh.createCone(engine, { - keepData: true, - radius: 0.5, - height: 2, - radialSegments: 12, - heightSegments: 1 - }) + PrimitiveMesh.createTruncatedCone(engine, 0.25, 1, 2, { keepData: true, radialSegments: 12, heightSegments: 1 }) ], + ["cone", () => PrimitiveMesh.createCone(engine, 0.5, 2, { keepData: true, radialSegments: 12, heightSegments: 1 })], [ "capsule", () => - PrimitiveMesh.createCapsule(engine, { + PrimitiveMesh.createCapsule(engine, 0.5, 2, { keepData: true, - radius: 0.5, - height: 2, radialSegments: 12, capSegments: 4, heightSegments: 1 @@ -92,36 +63,31 @@ const creators: [string, () => ModelMesh][] = [ [ "torus", () => - PrimitiveMesh.createTorus(engine, { + PrimitiveMesh.createTorus(engine, 0.5, 0.1, { keepData: true, angleRange: new Vector2(0, 360), - radius: 0.5, - tubeRadius: 0.1, tubularSegments: 16, radialSegments: 8 }) ], [ "circle", - () => - PrimitiveMesh.createCircle(engine, { keepData: true, angleRange: new Vector2(0, 180), radius: 0.5, segments: 12 }) + () => PrimitiveMesh.createCircle(engine, 0.5, { keepData: true, angleRange: new Vector2(0, 180), segments: 12 }) ], [ "ring", () => - PrimitiveMesh.createRing(engine, { + PrimitiveMesh.createRing(engine, 0.5, 0.25, { keepData: true, angleRange: new Vector2(0, 360), - outerRadius: 0.5, - innerRadius: 0.25, radialSegments: 12, widthSegments: 2 }) ], - ["tetrahedron", () => PrimitiveMesh.createTetrahedron(engine, { keepData: true, radius: 0.5, segments: 1 })], - ["octahedron", () => PrimitiveMesh.createOctahedron(engine, { keepData: true, radius: 0.5, segments: 1 })], - ["icosahedron", () => PrimitiveMesh.createIcosahedron(engine, { keepData: true, radius: 0.5, segments: 2 })], - ["dodecahedron", () => PrimitiveMesh.createDodecahedron(engine, { keepData: true, radius: 0.5, segments: 1 })], + ["tetrahedron", () => PrimitiveMesh.createTetrahedron(engine, 0.5, { keepData: true, segments: 1 })], + ["octahedron", () => PrimitiveMesh.createOctahedron(engine, 0.5, { keepData: true, segments: 1 })], + ["icosahedron", () => PrimitiveMesh.createIcosahedron(engine, 0.5, { keepData: true, segments: 2 })], + ["dodecahedron", () => PrimitiveMesh.createDodecahedron(engine, 0.5, { keepData: true, segments: 1 })], [ "lathe", () => @@ -133,23 +99,16 @@ const creators: [string, () => ModelMesh][] = [ ], [ "tube", - () => - PrimitiveMesh.createTube(engine, path, { keepData: true, radius: 0.5, tubularSegments: 12, radialSegments: 8 }) + () => PrimitiveMesh.createTube(engine, path, 0.5, { keepData: true, tubularSegments: 12, radialSegments: 8 }) ], ["polygon", () => PrimitiveMesh.createPolygon(engine, polygon, { keepData: true })], - ["extrusion", () => PrimitiveMesh.createExtrusion(engine, polygon, { keepData: true, depth: 2, steps: 1 })], + ["extrusion", () => PrimitiveMesh.createExtrusion(engine, polygon, 2, { keepData: true, steps: 1 })], [ "extrusion", () => - PrimitiveMesh.createExtrusion(engine, polygon, { - keepData: true, - bevelSize: 0.1, - bevelOffset: 0.2, - depth: 1, - steps: 1 - }) + PrimitiveMesh.createExtrusion(engine, polygon, 1, { keepData: true, bevelSize: 0.1, bevelOffset: 0.2, steps: 1 }) ], - ["extrusion", () => PrimitiveMesh.createExtrusion(engine, polygon, { keepData: true, path, steps: 5 })], + ["extrusion", () => PrimitiveMesh.createExtrusion(engine, polygon, path, { keepData: true, steps: 5 })], [ "extrusion", () => @@ -165,47 +124,25 @@ const creators: [string, () => ModelMesh][] = [ new Vector2(0, 2) ] }, - { keepData: true, bevelSize: 0.05, bevelThickness: 0.1, bevelOffset: -0.05, depth: 1, steps: 1 } + 1, + { keepData: true, bevelSize: 0.05, bevelThickness: 0.1, bevelOffset: -0.05, steps: 1 } ) ], [ "torusKnot", () => - PrimitiveMesh.createTorusKnot(engine, { - keepData: true, - radius: 0.5, - tubeRadius: 0.1, - p: 2, - q: 3, - tubularSegments: 32, - radialSegments: 8 - }) + PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2, 3, { keepData: true, tubularSegments: 32, radialSegments: 8 }) ], [ "torusKnot", () => - PrimitiveMesh.createTorusKnot(engine, { + PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, -2, -3, { keepData: true, - radius: 0.5, - tubeRadius: 0.1, - p: -2, - q: -3, tubularSegments: 32, radialSegments: 8 }) ], - [ - "roundedCuboid", - () => - PrimitiveMesh.createRoundedCuboid(engine, { - keepData: true, - width: 1, - height: 1, - depth: 1, - cornerRadius: 0.15, - segments: 3 - }) - ] + ["roundedCuboid", () => PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.15, { keepData: true, segments: 3 })] ]; describe("primitive mesh defaults", () => { @@ -214,18 +151,15 @@ describe("primitive mesh defaults", () => { const cases: [string, () => ModelMesh, () => ModelMesh][] = [ [ "sphere", - () => PrimitiveMesh.createSphere(engine, { ...options, radius: 1 }), - () => PrimitiveMesh.createSphere(engine, { ...options, radius: 1, subdivisions: 3 }) + () => PrimitiveMesh.createSphere(engine, 1, { ...options }), + () => PrimitiveMesh.createSphere(engine, 1, { ...options, subdivisions: 3 }) ], [ "cuboid", - () => PrimitiveMesh.createCuboid(engine, { ...options, width: 2, height: 3, depth: 4, widthSegments: 3 }), + () => PrimitiveMesh.createCuboid(engine, 2, 3, 4, { ...options, widthSegments: 3 }), () => - PrimitiveMesh.createCuboid(engine, { + PrimitiveMesh.createCuboid(engine, 2, 3, 4, { ...options, - width: 2, - height: 3, - depth: 4, widthSegments: 3, heightSegments: 3, depthSegments: 3 @@ -233,55 +167,30 @@ describe("primitive mesh defaults", () => { ], [ "plane", - () => PrimitiveMesh.createPlane(engine, { ...options, width: 2, height: 3, horizontalSegments: 2 }), - () => - PrimitiveMesh.createPlane(engine, { - ...options, - width: 2, - height: 3, - horizontalSegments: 2, - verticalSegments: 2 - }) + () => PrimitiveMesh.createPlane(engine, 2, 3, { ...options, horizontalSegments: 2 }), + () => PrimitiveMesh.createPlane(engine, 2, 3, { ...options, horizontalSegments: 2, verticalSegments: 2 }) ], [ "cylinder", - () => PrimitiveMesh.createCylinder(engine, { ...options, radius: 1, height: 2 }), - () => - PrimitiveMesh.createCylinder(engine, { - ...options, - radius: 1, - height: 2, - radialSegments: 20, - heightSegments: 1 - }) + () => PrimitiveMesh.createCylinder(engine, 1, 2, { ...options }), + () => PrimitiveMesh.createCylinder(engine, 1, 2, { ...options, radialSegments: 20, heightSegments: 1 }) ], [ "truncated cone", - () => PrimitiveMesh.createTruncatedCone(engine, { ...options, topRadius: 0.25, bottomRadius: 1, height: 2 }), - () => - PrimitiveMesh.createTruncatedCone(engine, { - ...options, - topRadius: 0.25, - bottomRadius: 1, - height: 2, - radialSegments: 20, - heightSegments: 1 - }) + () => PrimitiveMesh.createTruncatedCone(engine, 0.25, 1, 2, { ...options }), + () => PrimitiveMesh.createTruncatedCone(engine, 0.25, 1, 2, { ...options, radialSegments: 20, heightSegments: 1 }) ], [ "cone", - () => PrimitiveMesh.createCone(engine, { ...options, radius: 1, height: 2 }), - () => - PrimitiveMesh.createCone(engine, { ...options, radius: 1, height: 2, radialSegments: 20, heightSegments: 1 }) + () => PrimitiveMesh.createCone(engine, 1, 2, { ...options }), + () => PrimitiveMesh.createCone(engine, 1, 2, { ...options, radialSegments: 20, heightSegments: 1 }) ], [ "capsule", - () => PrimitiveMesh.createCapsule(engine, { ...options, radius: 1, height: 2, radialSegments: 12 }), + () => PrimitiveMesh.createCapsule(engine, 1, 2, { ...options, radialSegments: 12 }), () => - PrimitiveMesh.createCapsule(engine, { + PrimitiveMesh.createCapsule(engine, 1, 2, { ...options, - radius: 1, - height: 2, radialSegments: 12, capSegments: 12, heightSegments: 1 @@ -289,52 +198,38 @@ describe("primitive mesh defaults", () => { ], [ "torus", - () => PrimitiveMesh.createTorus(engine, { ...options, radius: 1, tubeRadius: 0.2 }), - () => - PrimitiveMesh.createTorus(engine, { - ...options, - radius: 1, - tubeRadius: 0.2, - tubularSegments: 30, - radialSegments: 30 - }) + () => PrimitiveMesh.createTorus(engine, 1, 0.2, { ...options }), + () => PrimitiveMesh.createTorus(engine, 1, 0.2, { ...options, tubularSegments: 30, radialSegments: 30 }) ], [ "circle", - () => PrimitiveMesh.createCircle(engine, { ...options, radius: 1 }), - () => PrimitiveMesh.createCircle(engine, { ...options, radius: 1, segments: 32 }) + () => PrimitiveMesh.createCircle(engine, 1, { ...options }), + () => PrimitiveMesh.createCircle(engine, 1, { ...options, segments: 32 }) ], [ "ring", - () => PrimitiveMesh.createRing(engine, { ...options, outerRadius: 1, innerRadius: 0.5 }), - () => - PrimitiveMesh.createRing(engine, { - ...options, - outerRadius: 1, - innerRadius: 0.5, - radialSegments: 32, - widthSegments: 1 - }) + () => PrimitiveMesh.createRing(engine, 1, 0.5, { ...options }), + () => PrimitiveMesh.createRing(engine, 1, 0.5, { ...options, radialSegments: 32, widthSegments: 1 }) ], [ "tetrahedron", - () => PrimitiveMesh.createTetrahedron(engine, { ...options, radius: 1 }), - () => PrimitiveMesh.createTetrahedron(engine, { ...options, radius: 1, segments: 1 }) + () => PrimitiveMesh.createTetrahedron(engine, 1, { ...options }), + () => PrimitiveMesh.createTetrahedron(engine, 1, { ...options, segments: 1 }) ], [ "octahedron", - () => PrimitiveMesh.createOctahedron(engine, { ...options, radius: 1 }), - () => PrimitiveMesh.createOctahedron(engine, { ...options, radius: 1, segments: 1 }) + () => PrimitiveMesh.createOctahedron(engine, 1, { ...options }), + () => PrimitiveMesh.createOctahedron(engine, 1, { ...options, segments: 1 }) ], [ "icosahedron", - () => PrimitiveMesh.createIcosahedron(engine, { ...options, radius: 1 }), - () => PrimitiveMesh.createIcosahedron(engine, { ...options, radius: 1, segments: 1 }) + () => PrimitiveMesh.createIcosahedron(engine, 1, { ...options }), + () => PrimitiveMesh.createIcosahedron(engine, 1, { ...options, segments: 1 }) ], [ "dodecahedron", - () => PrimitiveMesh.createDodecahedron(engine, { ...options, radius: 1 }), - () => PrimitiveMesh.createDodecahedron(engine, { ...options, radius: 1, segments: 1 }) + () => PrimitiveMesh.createDodecahedron(engine, 1, { ...options }), + () => PrimitiveMesh.createDodecahedron(engine, 1, { ...options, segments: 1 }) ], [ "lathe", @@ -343,45 +238,28 @@ describe("primitive mesh defaults", () => { ], [ "tube", - () => PrimitiveMesh.createTube(engine, path, { ...options, radius: 0.2 }), - () => PrimitiveMesh.createTube(engine, path, { ...options, radius: 0.2, tubularSegments: 64, radialSegments: 8 }) + () => PrimitiveMesh.createTube(engine, path, 0.2, { ...options }), + () => PrimitiveMesh.createTube(engine, path, 0.2, { ...options, tubularSegments: 64, radialSegments: 8 }) ], [ "depth extrusion", - () => PrimitiveMesh.createExtrusion(engine, polygon, { ...options, depth: 2 }), - () => PrimitiveMesh.createExtrusion(engine, polygon, { ...options, depth: 2, steps: 1 }) + () => PrimitiveMesh.createExtrusion(engine, polygon, 2, { ...options }), + () => PrimitiveMesh.createExtrusion(engine, polygon, 2, { ...options, steps: 1 }) ], [ "path extrusion", - () => PrimitiveMesh.createExtrusion(engine, polygon, { ...options, path }), - () => PrimitiveMesh.createExtrusion(engine, polygon, { ...options, path, steps: 1 }) + () => PrimitiveMesh.createExtrusion(engine, polygon, path, { ...options }), + () => PrimitiveMesh.createExtrusion(engine, polygon, path, { ...options, steps: 1 }) ], [ "torus knot", - () => PrimitiveMesh.createTorusKnot(engine, { ...options, radius: 1, tubeRadius: 0.2, p: 2, q: 3 }), - () => - PrimitiveMesh.createTorusKnot(engine, { - ...options, - radius: 1, - tubeRadius: 0.2, - p: 2, - q: 3, - tubularSegments: 64, - radialSegments: 8 - }) + () => PrimitiveMesh.createTorusKnot(engine, 1, 0.2, 2, 3, { ...options }), + () => PrimitiveMesh.createTorusKnot(engine, 1, 0.2, 2, 3, { ...options, tubularSegments: 64, radialSegments: 8 }) ], [ "rounded cuboid", - () => PrimitiveMesh.createRoundedCuboid(engine, { ...options, width: 2, height: 3, depth: 4, cornerRadius: 0.2 }), - () => - PrimitiveMesh.createRoundedCuboid(engine, { - ...options, - width: 2, - height: 3, - depth: 4, - cornerRadius: 0.2, - segments: 2 - }) + () => PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0.2, { ...options }), + () => PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0.2, { ...options, segments: 2 }) ] ]; @@ -403,8 +281,8 @@ describe("primitive mesh defaults", () => { }); it.each([0.5, 1])("derives a valid ring from outer radius %s", (radius) => { - const mesh = PrimitiveMesh.createRing(engine, { ...options, outerRadius: radius }); - const defaultMesh = PrimitiveMesh.createRing(engine, { outerRadius: 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()!; @@ -425,11 +303,11 @@ describe("primitive mesh defaults", () => { }); describe("procedural mesh geometry", () => { - it("uses uniform size and subdivision defaults for partial options", () => { - const cube = PrimitiveMesh.createCuboid(engine, { width: 2 }); - const plane = PrimitiveMesh.createPlane(engine, { width: 3 }); - const sphere = PrimitiveMesh.createSphere(engine, { radius: 1 }); - const detailedSphere = PrimitiveMesh.createSphere(engine, { radius: 1, subdivisions: 4 }); + 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, { subdivisions: 4 }); try { expect(cube.bounds.min).toMatchObject({ x: -1, y: -1, z: -1 }); expect(cube.bounds.max).toMatchObject({ x: 1, y: 1, z: 1 }); @@ -445,13 +323,11 @@ describe("procedural mesh geometry", () => { }); it("distinguishes cylinders from frustums and selects end caps independently", () => { - const cylinder = PrimitiveMesh.createCylinder(engine, { radius: 1, height: 3 }); - const frustum = PrimitiveMesh.createTruncatedCone(engine, { topRadius: 0.5, bottomRadius: 1.5, height: 4 }); - const topOnly = PrimitiveMesh.createCylinder(engine, { + 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, keepData: true, - radius: 1, - height: 3, radialSegments: 8, heightSegments: 1 }); @@ -487,11 +363,9 @@ describe("procedural mesh geometry", () => { }); it("honors offset angular ranges for torus sections", () => { - const mesh = PrimitiveMesh.createTorus(engine, { + const mesh = PrimitiveMesh.createTorus(engine, 1, 0.25, { keepData: true, angleRange: new Vector2(90, 180), - radius: 1, - tubeRadius: 0.25, tubularSegments: 8, radialSegments: 6 }); @@ -513,12 +387,8 @@ describe("procedural mesh geometry", () => { { p: 1, q: 0, expected: new Vector3((3 * Math.sqrt(3)) / 2, 1.5, 0) } ])("preserves torus knot windings p=$p, q=$q during creation and restoration", ({ p, q, expected }) => { const radialSegments = 8; - const mesh = PrimitiveMesh.createTorusKnot(engine, { + const mesh = PrimitiveMesh.createTorusKnot(engine, 2, 0.2, p, q, { keepData: true, - radius: 2, - tubeRadius: 0.2, - p, - q, tubularSegments: 48, radialSegments }); @@ -548,10 +418,8 @@ describe("procedural mesh geometry", () => { ])( "centers capsule pole UVs with $radialSegments radial segments", ({ radialSegments, capSegments, heightSegments }) => { - const mesh = PrimitiveMesh.createCapsule(engine, { + const mesh = PrimitiveMesh.createCapsule(engine, 1, 2, { keepData: true, - radius: 1, - height: 2, radialSegments, capSegments, heightSegments @@ -636,13 +504,9 @@ describe("procedural mesh geometry", () => { 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, { + const mesh = PrimitiveMesh.createRoundedCuboid(engine, sizes.x, sizes.y, sizes.z, radius, { keepData: true, separateMaterials: true, - width: sizes.x, - height: sizes.y, - depth: sizes.z, - cornerRadius: radius, segments }); const faces = [ @@ -688,63 +552,18 @@ describe("procedural mesh geometry", () => { it("handles rounded cuboid radius and segment limits without changing the cuboid fallback", () => { const options = { keepData: true, separateMaterials: true }; const meshes = [ - PrimitiveMesh.createCuboid(engine, { + PrimitiveMesh.createCuboid(engine, 2, 3, 4, { ...options, - width: 2, - height: 3, - depth: 4, widthSegments: 1, heightSegments: 1, depthSegments: 1 }), - PrimitiveMesh.createRoundedCuboid(engine, { - ...options, - width: 2, - height: 3, - depth: 4, - cornerRadius: 0, - segments: 4 - }), - PrimitiveMesh.createRoundedCuboid(engine, { - ...options, - width: 2, - height: 3, - depth: 4, - cornerRadius: -1, - segments: 4 - }), - PrimitiveMesh.createRoundedCuboid(engine, { - ...options, - width: 2, - height: 3, - depth: 4, - cornerRadius: 1, - segments: 3 - }), - PrimitiveMesh.createRoundedCuboid(engine, { - ...options, - width: 2, - height: 3, - depth: 4, - cornerRadius: 8, - segments: 3 - }), - PrimitiveMesh.createRoundedCuboid(engine, { - ...options, - width: 2, - height: 3, - depth: 4, - cornerRadius: 0.2, - segments: 0 - }), - PrimitiveMesh.createRoundedCuboid(engine, { - ...options, - width: 2, - height: 3, - depth: 4, - cornerRadius: 0.2, - segments: 1 - }) + PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0, { ...options, segments: 4 }), + PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, -1, { ...options, segments: 4 }), + PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 1, { ...options, segments: 3 }), + PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 8, { ...options, segments: 3 }), + PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0.2, { ...options, segments: 0 }), + PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0.2, { ...options, segments: 1 }) ]; try { for (const [a, b] of [ @@ -767,12 +586,8 @@ describe("procedural mesh geometry", () => { { 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, { + const mesh = PrimitiveMesh.createRoundedCuboid(engine, width, height, depth, radius, { keepData: true, - width, - height, - depth, - cornerRadius: radius, segments: 4 }); try { @@ -802,7 +617,7 @@ describe("procedural mesh geometry", () => { }); it.each([false, true])("controls all generated vertex data through keepData=%s", (keepData) => { - const mesh = PrimitiveMesh.createSphere(engine, { keepData, radius: 0.5, subdivisions: 1 }); + const mesh = PrimitiveMesh.createSphere(engine, 0.5, { keepData, subdivisions: 1 }); try { for (const binding of mesh.vertexBufferBindings) { expect(binding!.buffer.readable).toBe(keepData); @@ -866,7 +681,7 @@ describe("procedural mesh geometry", () => { }); it("keeps sphere tangents perpendicular at non-unit radii", () => { - const mesh = PrimitiveMesh.createSphere(engine, { keepData: true, radius: 2, subdivisions: 3 }); + const mesh = PrimitiveMesh.createSphere(engine, 2, { keepData: true, subdivisions: 3 }); try { expect(mesh.vertexCount).toBe(417); expect(mesh.getIndices()!.length / 3).toBe(768); @@ -883,10 +698,9 @@ describe("procedural mesh geometry", () => { }); it("supports a northern hemisphere", () => { - const mesh = PrimitiveMesh.createSphere(engine, { + const mesh = PrimitiveMesh.createSphere(engine, 0.5, { keepData: true, verticalRange: new Vector2(0, 90), - radius: 0.5, subdivisions: 2 }); try { @@ -905,11 +719,10 @@ describe("procedural mesh geometry", () => { { 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, { + const mesh = PrimitiveMesh.createSphere(engine, radius, { keepData: true, horizontalRange: new Vector2(horizontal[0], horizontal[1]), verticalRange: new Vector2(vertical[0], vertical[1]), - radius, subdivisions: 3 }); try { @@ -980,11 +793,10 @@ describe("procedural mesh geometry", () => { }); it("rotates complete spheres without changing topology", () => { - const original = PrimitiveMesh.createSphere(engine, { keepData: true, radius: 1, subdivisions: 2 }); - const rotated = PrimitiveMesh.createSphere(engine, { + const original = PrimitiveMesh.createSphere(engine, 1, { keepData: true, subdivisions: 2 }); + const rotated = PrimitiveMesh.createSphere(engine, 1, { keepData: true, horizontalRange: new Vector2(90, 450), - radius: 1, subdivisions: 2 }); try { @@ -1005,7 +817,7 @@ describe("procedural mesh geometry", () => { it("captures sphere ranges for device restoration", () => { const horizontalRange = new Vector2(20, 290); const verticalRange = new Vector2(30, 150); - const mesh = PrimitiveMesh.createSphere(engine, { horizontalRange, verticalRange, radius: 1, subdivisions: 3 }); + const mesh = PrimitiveMesh.createSphere(engine, 1, { horizontalRange, verticalRange, subdivisions: 3 }); try { const buffer = mesh.vertexBufferBindings[0]!.buffer; const original = MeshTestUtils.readBuffer(buffer); @@ -1020,26 +832,19 @@ describe("procedural mesh geometry", () => { }); it("omits cylinder caps and makes material groups opt-in", () => { - const open = PrimitiveMesh.createCylinder(engine, { + const open = PrimitiveMesh.createCylinder(engine, 0.5, 2, { keepData: true, caps: PrimitiveMeshCapMode.None, - radius: 0.5, - height: 2, radialSegments: 8, heightSegments: 1 }); - const grouped = PrimitiveMesh.createCylinder(engine, { + const grouped = PrimitiveMesh.createCylinder(engine, 0.5, 2, { separateMaterials: true, - radius: 0.5, - height: 2, radialSegments: 8, heightSegments: 1 }); - const cube = PrimitiveMesh.createCuboid(engine, { + const cube = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { separateMaterials: true, - width: 1, - height: 1, - depth: 1, widthSegments: 1, heightSegments: 1, depthSegments: 1 @@ -1057,12 +862,9 @@ describe("procedural mesh geometry", () => { }); it("orders cuboid material slots by face direction", () => { - const mesh = PrimitiveMesh.createCuboid(engine, { + const mesh = PrimitiveMesh.createCuboid(engine, 1, 2, 3, { keepData: true, separateMaterials: true, - width: 1, - height: 2, - depth: 3, widthSegments: 1, heightSegments: 1, depthSegments: 1 @@ -1087,11 +889,9 @@ describe("procedural mesh geometry", () => { { name: "cylinder with both caps", create: () => - PrimitiveMesh.createCylinder(engine, { + PrimitiveMesh.createCylinder(engine, 1, 2, { keepData: true, separateMaterials: true, - radius: 1, - height: 2, radialSegments: 8, heightSegments: 1 }), @@ -1100,12 +900,10 @@ describe("procedural mesh geometry", () => { { name: "cylinder with only its top cap", create: () => - PrimitiveMesh.createCylinder(engine, { + PrimitiveMesh.createCylinder(engine, 1, 2, { keepData: true, separateMaterials: true, caps: PrimitiveMeshCapMode.Top, - radius: 1, - height: 2, radialSegments: 8, heightSegments: 1 }), @@ -1114,12 +912,10 @@ describe("procedural mesh geometry", () => { { name: "cylinder with only its bottom cap", create: () => - PrimitiveMesh.createCylinder(engine, { + PrimitiveMesh.createCylinder(engine, 1, 2, { keepData: true, separateMaterials: true, caps: PrimitiveMeshCapMode.Bottom, - radius: 1, - height: 2, radialSegments: 8, heightSegments: 1 }), @@ -1128,12 +924,10 @@ describe("procedural mesh geometry", () => { { name: "cylinder without caps", create: () => - PrimitiveMesh.createCylinder(engine, { + PrimitiveMesh.createCylinder(engine, 1, 2, { keepData: true, separateMaterials: true, caps: PrimitiveMeshCapMode.None, - radius: 1, - height: 2, radialSegments: 8, heightSegments: 1 }), @@ -1142,12 +936,9 @@ describe("procedural mesh geometry", () => { { name: "truncated cone with a zero top radius", create: () => - PrimitiveMesh.createTruncatedCone(engine, { + PrimitiveMesh.createTruncatedCone(engine, 0, 1, 2, { keepData: true, separateMaterials: true, - topRadius: 0, - bottomRadius: 1, - height: 2, radialSegments: 8, heightSegments: 1 }), @@ -1156,12 +947,9 @@ describe("procedural mesh geometry", () => { { name: "truncated cone with a zero bottom radius", create: () => - PrimitiveMesh.createTruncatedCone(engine, { + PrimitiveMesh.createTruncatedCone(engine, 1, 0, 2, { keepData: true, separateMaterials: true, - topRadius: 1, - bottomRadius: 0, - height: 2, radialSegments: 8, heightSegments: 1 }), @@ -1170,11 +958,9 @@ describe("procedural mesh geometry", () => { { name: "cone with its bottom cap", create: () => - PrimitiveMesh.createCone(engine, { + PrimitiveMesh.createCone(engine, 1, 2, { keepData: true, separateMaterials: true, - radius: 1, - height: 2, radialSegments: 8, heightSegments: 1 }), @@ -1183,12 +969,10 @@ describe("procedural mesh geometry", () => { { name: "cone without its bottom cap", create: () => - PrimitiveMesh.createCone(engine, { + PrimitiveMesh.createCone(engine, 1, 2, { keepData: true, separateMaterials: true, cap: false, - radius: 1, - height: 2, radialSegments: 8, heightSegments: 1 }), @@ -1228,10 +1012,9 @@ describe("procedural mesh geometry", () => { 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.createExtrusion(engine, shapes, { + const mesh = PrimitiveMesh.createExtrusion(engine, shapes, 2, { keepData: true, separateMaterials: true, - depth: 2, steps: 1 }); try { @@ -1252,7 +1035,7 @@ describe("procedural mesh geometry", () => { it.each([0.2, -0.2])("offsets extrusion walls and bevels by %s and restores their geometry", (bevelOffset) => { const options = { keepData: true, separateMaterials: true, bevelSize: 0.1, bevelThickness: 0.2, bevelOffset }; - const mesh = PrimitiveMesh.createExtrusion(engine, polygon, { ...options, depth: 2, steps: 2 }); + const mesh = PrimitiveMesh.createExtrusion(engine, polygon, 2, { ...options, steps: 2 }); try { const outer = 2 + bevelOffset; const hole = 1 - bevelOffset; @@ -1290,7 +1073,7 @@ describe("procedural mesh geometry", () => { }); it.each([0.2, -0.2])("offsets extrusion contours by %s without adding bevels", (bevelOffset) => { - const mesh = PrimitiveMesh.createExtrusion(engine, polygon, { keepData: true, bevelOffset, depth: 2, steps: 1 }); + const mesh = PrimitiveMesh.createExtrusion(engine, polygon, 2, { keepData: true, bevelOffset, steps: 1 }); try { const positions = mesh.getPositions()!; expect(positions.every(({ z }) => z === 0 || z === 2)).toBe(true); @@ -1432,7 +1215,7 @@ describe("procedural mesh geometry", () => { it("preserves multiple holes in extrusion caps and restored buffers", () => { const { points, holes, area } = triangulationCases[1]; - const mesh = PrimitiveMesh.createExtrusion(engine, { points, holes }, { keepData: true, depth: 3, steps: 1 }); + const mesh = PrimitiveMesh.createExtrusion(engine, { points, holes }, 3, { keepData: true, steps: 1 }); try { const positions = mesh.getPositions()!; const indices = Array.from(mesh.getIndices()!); @@ -1464,9 +1247,8 @@ describe("procedural mesh geometry", () => { it("restores captured geometry after caller-owned inputs and buffers change", () => { const points = [new Vector3(0, 0, 0), new Vector3(0, 1, 1), new Vector3(1, 2, 2)]; - const mesh = PrimitiveMesh.createTube(engine, points, { + const mesh = PrimitiveMesh.createTube(engine, points, 0.5, { keepData: true, - radius: 0.5, tubularSegments: 8, radialSegments: 8 }); @@ -1487,21 +1269,16 @@ describe("procedural mesh geometry", () => { }); it.each([ - { type: "tube", keepData: false }, - { type: "tube", keepData: true }, - { type: "extrusion", keepData: false }, - { type: "extrusion", keepData: true } + { type: "tube", tubeRadius: 0.5, keepData: false }, + { type: "tube", tubeRadius: 0.5, keepData: true }, + { type: "extrusion", extrusionDepth: 1, keepData: false }, + { type: "extrusion", extrusionDepth: 1, keepData: true } ])("copies $type path points for device restoration with keepData=$keepData", ({ type, keepData }) => { const points = path.map((point) => point.clone()); const mesh = type === "tube" - ? PrimitiveMesh.createTube(engine, points, { - keepData, - radius: 0.5, - tubularSegments: 12, - radialSegments: 8 - }) - : PrimitiveMesh.createExtrusion(engine, polygon, { keepData, path: points, steps: 12 }); + ? PrimitiveMesh.createTube(engine, points, 0.5, { keepData, tubularSegments: 12, radialSegments: 8 }) + : PrimitiveMesh.createExtrusion(engine, polygon, points, { keepData, steps: 12 }); try { const buffers = mesh.vertexBufferBindings.map((binding) => binding!.buffer); buffers.push(mesh._primitive.indexBufferBinding!._buffer); @@ -1519,7 +1296,7 @@ describe("procedural mesh geometry", () => { }); it("restores primitive buffers after the default cache release", () => { - const mesh = PrimitiveMesh.createSphere(engine); + const mesh = PrimitiveMesh.createSphere(engine, 0.5); try { const restorer = (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId]; const buffer = mesh.vertexBufferBindings[0]!.buffer; @@ -1536,8 +1313,8 @@ describe("procedural mesh geometry", () => { it("restores spheres independently after interleaved creation", () => { const meshes = [ - PrimitiveMesh.createSphere(engine, { keepData: true, radius: 0.5, subdivisions: 2 }), - PrimitiveMesh.createSphere(engine, { keepData: true, radius: 2, subdivisions: 4 }) + PrimitiveMesh.createSphere(engine, 0.5, { keepData: true, subdivisions: 2 }), + PrimitiveMesh.createSphere(engine, 2, { keepData: true, subdivisions: 4 }) ]; const originals = meshes.map((mesh) => ({ vertices: mesh.vertexBufferBindings[0]!.buffer.data!.slice(), @@ -1560,10 +1337,8 @@ describe("procedural mesh geometry", () => { }); it("uses 32-bit indices for subdivided meshes beyond 65535 vertices", () => { - const mesh = PrimitiveMesh.createPlane(engine, { + const mesh = PrimitiveMesh.createPlane(engine, 1, 1, { keepData: true, - width: 1, - height: 1, horizontalSegments: 256, verticalSegments: 256 }); @@ -1576,10 +1351,9 @@ describe("procedural mesh geometry", () => { }); 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, { + const mesh = PrimitiveMesh.createTube(engine, path, 0.5, { keepData: true, closed: true, - radius: 0.5, tubularSegments: segments, radialSegments: 8 }); @@ -1601,12 +1375,8 @@ describe("procedural mesh geometry", () => { }); it.each([1, 2])("keeps torus-knot cross-sections with %s longitudinal segments", (segments) => { - const mesh = PrimitiveMesh.createTorusKnot(engine, { + const mesh = PrimitiveMesh.createTorusKnot(engine, 1, 0.2, 2, 3, { keepData: true, - radius: 1, - tubeRadius: 0.2, - p: 2, - q: 3, tubularSegments: segments, radialSegments: 8 }); @@ -1627,9 +1397,7 @@ describe("procedural mesh geometry", () => { }); it("rejects a torus knot without either winding", () => { - expect(() => PrimitiveMesh.createTorusKnot(engine, { radius: 1, tubeRadius: 0.2, p: 0, q: 0 })).toThrow( - "at least one nonzero 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", () => { @@ -1638,10 +1406,9 @@ describe("procedural mesh geometry", () => { 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, { + const mesh = PrimitiveMesh.createTube(engine, points, 0.5, { keepData: true, closed: true, - radius: 0.5, tubularSegments: 40, radialSegments }); @@ -1666,10 +1433,9 @@ describe("procedural mesh geometry", () => { 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 = { keepData: true, closed: true }; - const mesh = PrimitiveMesh.createExtrusion(engine, profile, { ...options, path: points, steps: 32 }); - const repeated = PrimitiveMesh.createExtrusion(engine, profile, { + const mesh = PrimitiveMesh.createExtrusion(engine, profile, points, { ...options, steps: 32 }); + const repeated = PrimitiveMesh.createExtrusion(engine, profile, [...points, points[0].clone()], { ...options, - path: [...points, points[0].clone()], steps: 32 }); try { @@ -1715,11 +1481,10 @@ describe("procedural mesh geometry", () => { { 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.createExtrusion(engine, shapes, { + const mesh = PrimitiveMesh.createExtrusion(engine, shapes, points, { keepData: true, separateMaterials: true, closed: true, - path: points, steps: 16 }); try { @@ -1735,18 +1500,17 @@ describe("procedural mesh geometry", () => { }); it("ignores settings from the inactive extrusion mode", () => { - const linearOptions = { keepData: true, depth: 2, steps: 2, bevelSize: 0.1, separateMaterials: true }; - const pathOptions = { keepData: true, path, steps: 5, separateMaterials: true }; + const linearOptions = { keepData: true, steps: 2, bevelSize: 0.1, separateMaterials: true }; + const pathOptions = { keepData: true, steps: 5, separateMaterials: true }; const pairs = [ [ - PrimitiveMesh.createExtrusion(engine, polygon, linearOptions), - PrimitiveMesh.createExtrusion(engine, polygon, { ...linearOptions, closed: true }) + PrimitiveMesh.createExtrusion(engine, polygon, 2, linearOptions), + PrimitiveMesh.createExtrusion(engine, polygon, 2, { ...linearOptions, closed: true }) ], [ - PrimitiveMesh.createExtrusion(engine, polygon, pathOptions), - PrimitiveMesh.createExtrusion(engine, polygon, { + PrimitiveMesh.createExtrusion(engine, polygon, path, pathOptions), + PrimitiveMesh.createExtrusion(engine, polygon, path, { ...pathOptions, - depth: 7, bevelSize: 0.25, bevelThickness: 0.4, bevelOffset: 0.5, @@ -1776,7 +1540,7 @@ describe("procedural mesh geometry", () => { it("uses at least three steps 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.createExtrusion(engine, profile, { keepData: true, closed: true, path: points }); + const mesh = PrimitiveMesh.createExtrusion(engine, profile, points, { keepData: true, closed: true }); try { const positions = mesh.getPositions()!; const indices = mesh.getIndices()!; @@ -1797,9 +1561,8 @@ describe("procedural mesh geometry", () => { 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)], { + const mesh = PrimitiveMesh.createTube(engine, [new Vector3(), new Vector3(1, 0, 0), new Vector3(1, 3, 0)], 0.5, { keepData: true, - radius: 0.5, tubularSegments: 4, radialSegments }); @@ -1829,7 +1592,7 @@ describe("procedural mesh geometry", () => { "keeps %s UVs within the shortest longitudinal interval", (create) => { for (const segments of [1, 2, 3]) { - const mesh = PrimitiveMesh[create](engine, { radius: 1, segments, keepData: true }); + const mesh = PrimitiveMesh[create](engine, 1, { segments, keepData: true }); try { const uvs = mesh.getUVs()!; const indices = mesh.getIndices()!; @@ -1878,13 +1641,10 @@ describe("procedural mesh geometry", () => { it("preserves edited primitive data and material groups after device restoration", async () => { const restoredEngine = await WebGLEngine.create({ canvas: document.createElement("canvas") }); - const released = PrimitiveMesh.createSphere(restoredEngine, { radius: 1, subdivisions: 1 }); - const mesh = PrimitiveMesh.createCuboid(restoredEngine, { + const released = PrimitiveMesh.createSphere(restoredEngine, 1, { subdivisions: 1 }); + const mesh = PrimitiveMesh.createCuboid(restoredEngine, 1, 1, 1, { keepData: true, separateMaterials: true, - width: 1, - height: 1, - depth: 1, widthSegments: 1, heightSegments: 1, depthSegments: 1 @@ -1937,10 +1697,8 @@ describe("procedural mesh geometry", () => { }); it("restores released tangents from edited primitive UVs", () => { - const mesh = PrimitiveMesh.createPlane(engine, { + const mesh = PrimitiveMesh.createPlane(engine, 2, 3, { keepData: true, - width: 2, - height: 3, horizontalSegments: 1, verticalSegments: 1 }); @@ -1962,10 +1720,8 @@ describe("procedural mesh geometry", () => { }); it.each([1, 1e-8])("normalizes tangents for a plane of size %s", (size) => { - const mesh = PrimitiveMesh.createPlane(engine, { + const mesh = PrimitiveMesh.createPlane(engine, size, size, { keepData: true, - width: size, - height: size, horizontalSegments: 1, verticalSegments: 1 }); @@ -1996,7 +1752,7 @@ describe("procedural mesh geometry", () => { }); it.each([false, true])("preserves tangent data when adding a vertex channel after reading: %s", (readTangents) => { - const mesh = PrimitiveMesh.createSphere(engine, { keepData: true, subdivisions: 2 }); + const mesh = PrimitiveMesh.createSphere(engine, 0.5, { keepData: true, subdivisions: 2 }); try { const original = MeshTestUtils.readBuffer(mesh.vertexBufferBindings[1]!.buffer); if (readTangents) { @@ -2023,7 +1779,7 @@ describe("procedural mesh geometry", () => { }); it("releases primitive tangent data through the ModelMesh buffer lifecycle", () => { - const mesh = PrimitiveMesh.createPlane(engine, { keepData: true }); + const mesh = PrimitiveMesh.createPlane(engine, 1, 1, { keepData: true }); try { const tangentBuffer = mesh.vertexBufferBindings[1]!.buffer; expect(tangentBuffer.readable).toBe(true); @@ -2057,7 +1813,7 @@ describe("procedural mesh geometry", () => { const angle = (i * Math.PI * 2) / 256; return new Vector2(Math.cos(angle), Math.sin(angle)); }); - const mesh = PrimitiveMesh.createExtrusion(engine, contour, { keepData: true, steps: 43 }); + const mesh = PrimitiveMesh.createExtrusion(engine, contour, 1, { keepData: true, steps: 43 }); try { const indices = mesh.getIndices()!; expect(mesh.vertexCount).toBeGreaterThan(65535); @@ -2081,7 +1837,8 @@ describe("procedural mesh geometry", () => { new Vector2(0, 0) ] }, - { keepData: true, bevelSize: 0.1, depth: 1, steps: 1 } + 1, + { keepData: true, bevelSize: 0.1, steps: 1 } ); try { expect(mesh.getPositions()!.every((p) => [p.x, p.y, p.z].every(Number.isFinite))).toBe(true); 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 6de03c9d39..7a5f512f0f 100644 --- a/tests/src/core/physics/ColliderLayer.test.ts +++ b/tests/src/core/physics/ColliderLayer.test.ts @@ -101,11 +101,8 @@ describe("Collider layer initialization", () => { source.addShape(shape); expect(attach.mock.calls.length).toBe(1); - const mesh = PrimitiveMesh.createCuboid(engine, { + const mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { keepData: true, - width: 1, - height: 1, - depth: 1, widthSegments: 1, heightSegments: 1, depthSegments: 1 diff --git a/tests/src/core/physics/MeshColliderLayer.test.ts b/tests/src/core/physics/MeshColliderLayer.test.ts index a9133f793f..df30258516 100644 --- a/tests/src/core/physics/MeshColliderLayer.test.ts +++ b/tests/src/core/physics/MeshColliderLayer.test.ts @@ -25,11 +25,8 @@ 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, { + mesh = PrimitiveMesh.createCuboid(engine, 10, 1, 10, { keepData: true, - width: 10, - height: 1, - depth: 10, widthSegments: 1, heightSegments: 1, depthSegments: 1 diff --git a/tests/src/loader/PrimitiveMeshLoader.test.ts b/tests/src/loader/PrimitiveMeshLoader.test.ts index fd2cadbe05..cd17e843a2 100644 --- a/tests/src/loader/PrimitiveMeshLoader.test.ts +++ b/tests/src/loader/PrimitiveMeshLoader.test.ts @@ -64,35 +64,91 @@ const groupedOptions = { keepData: true, separateMaterials: true }; describe("PrimitiveMeshLoader", () => { const defaults = { - sphere: { data: { type: "sphere" }, create: () => PrimitiveMesh.createSphere(engine) }, - cuboid: { data: { type: "cuboid" }, create: () => PrimitiveMesh.createCuboid(engine) }, - plane: { data: { type: "plane" }, create: () => PrimitiveMesh.createPlane(engine) }, - cylinder: { data: { type: "cylinder" }, create: () => PrimitiveMesh.createCylinder(engine) }, - truncatedCone: { data: { type: "truncatedCone" }, create: () => PrimitiveMesh.createTruncatedCone(engine) }, - cone: { data: { type: "cone" }, create: () => PrimitiveMesh.createCone(engine) }, - capsule: { data: { type: "capsule" }, create: () => PrimitiveMesh.createCapsule(engine) }, - torus: { data: { type: "torus" }, create: () => PrimitiveMesh.createTorus(engine) }, - circle: { data: { type: "circle" }, create: () => PrimitiveMesh.createCircle(engine) }, - ring: { data: { type: "ring" }, create: () => PrimitiveMesh.createRing(engine) }, - tetrahedron: { data: { type: "tetrahedron" }, create: () => PrimitiveMesh.createTetrahedron(engine) }, - octahedron: { data: { type: "octahedron" }, create: () => PrimitiveMesh.createOctahedron(engine) }, - icosahedron: { data: { type: "icosahedron" }, create: () => PrimitiveMesh.createIcosahedron(engine) }, - dodecahedron: { data: { type: "dodecahedron" }, create: () => PrimitiveMesh.createDodecahedron(engine) }, + 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, planeHeight: 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, capsuleHeight: 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) + }, lathe: { data: { type: "lathe", latheProfile: profile }, create: () => PrimitiveMesh.createLathe(engine, profileVectors) }, - tube: { data: { type: "tube", tubePath: path }, create: () => PrimitiveMesh.createTube(engine, pathVectors) }, + 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) }, extrusion: { - data: { type: "extrusion", extrusionShapes: shapes }, - create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors) + data: { type: "extrusion", extrusionDepth: 1, extrusionShapes: shapes }, + create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors, 1) }, - torusKnot: { data: { type: "torusKnot" }, create: () => PrimitiveMesh.createTorusKnot(engine) }, - roundedCuboid: { data: { type: "roundedCuboid" }, create: () => PrimitiveMesh.createRoundedCuboid(engine) } + torusKnot: { + data: { type: "torusKnot", torusKnotRadius: 0.5, torusKnotTubeRadius: 0.1, torusKnotP: 2, torusKnotQ: 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 }[] = [ @@ -100,46 +156,44 @@ describe("PrimitiveMeshLoader", () => { name: "sphere ranges and subdivision level", data: { type: "sphere", + sphereRadius: 2, sphereOptions: { ...options, horizontalRange: { x: 20, y: 260 }, verticalRange: { x: 30, y: 150 }, - radius: 2, subdivisions: 3 } }, create: () => - PrimitiveMesh.createSphere(engine, { + PrimitiveMesh.createSphere(engine, 2, { ...options, horizontalRange: new Vector2(20, 260), verticalRange: new Vector2(30, 150), - radius: 2, subdivisions: 3 }) }, { name: "sphere", - data: { type: "sphere", sphereOptions: { ...options, radius: 1.5, subdivisions: 2 } }, - create: () => PrimitiveMesh.createSphere(engine, { ...options, radius: 1.5, subdivisions: 2 }) + data: { type: "sphere", sphereRadius: 1.5, sphereOptions: { ...options, subdivisions: 2 } }, + create: () => PrimitiveMesh.createSphere(engine, 1.5, { ...options, subdivisions: 2 }) }, { name: "sphere angular ranges", data: { type: "sphere", + sphereRadius: 2, sphereOptions: { ...options, horizontalRange: { x: 350, y: 370 }, verticalRange: { x: 30, y: 150 }, - radius: 2, subdivisions: 3 } }, create: () => - PrimitiveMesh.createSphere(engine, { + PrimitiveMesh.createSphere(engine, 2, { ...options, horizontalRange: new Vector2(350, 370), verticalRange: new Vector2(30, 150), - radius: 2, subdivisions: 3 }) }, @@ -147,22 +201,14 @@ describe("PrimitiveMeshLoader", () => { name: "cuboid dimensions and segment counts", data: { type: "cuboid", - cuboidOptions: { - ...groupedOptions, - width: 2, - height: 3, - depth: 4, - widthSegments: 2, - heightSegments: 3, - depthSegments: 4 - } + cuboidWidth: 2, + cuboidHeight: 3, + cuboidDepth: 4, + cuboidOptions: { ...groupedOptions, widthSegments: 2, heightSegments: 3, depthSegments: 4 } }, create: () => - PrimitiveMesh.createCuboid(engine, { + PrimitiveMesh.createCuboid(engine, 2, 3, 4, { ...groupedOptions, - width: 2, - height: 3, - depth: 4, widthSegments: 2, heightSegments: 3, depthSegments: 4 @@ -172,38 +218,31 @@ describe("PrimitiveMeshLoader", () => { name: "plane dimensions and segment counts", data: { type: "plane", - planeOptions: { ...options, width: 3, height: 5, horizontalSegments: 2, verticalSegments: 4 } + planeWidth: 3, + planeHeight: 5, + planeOptions: { ...options, horizontalSegments: 2, verticalSegments: 4 } }, - create: () => - PrimitiveMesh.createPlane(engine, { - ...options, - width: 3, - height: 5, - horizontalSegments: 2, - verticalSegments: 4 - }) + create: () => PrimitiveMesh.createPlane(engine, 3, 5, { ...options, horizontalSegments: 2, verticalSegments: 4 }) }, { name: "cylinder caps and range", data: { type: "cylinder", + cylinderRadius: 0.75, + cylinderHeight: 3, cylinderOptions: { ...groupedOptions, caps: PrimitiveMeshCapMode.Bottom, angleRange: { x: 20, y: 270 }, - radius: 0.75, - height: 3, radialSegments: 12, heightSegments: 2 } }, create: () => - PrimitiveMesh.createCylinder(engine, { + PrimitiveMesh.createCylinder(engine, 0.75, 3, { ...groupedOptions, caps: PrimitiveMeshCapMode.Bottom, angleRange: new Vector2(20, 270), - radius: 0.75, - height: 3, radialSegments: 12, heightSegments: 2 }) @@ -212,25 +251,22 @@ describe("PrimitiveMeshLoader", () => { 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 }, - topRadius: 0.25, - bottomRadius: 1, - height: 3, radialSegments: 12, heightSegments: 2 } }, create: () => - PrimitiveMesh.createTruncatedCone(engine, { + PrimitiveMesh.createTruncatedCone(engine, 0.25, 1, 3, { ...groupedOptions, caps: PrimitiveMeshCapMode.Top, angleRange: new Vector2(30, 250), - topRadius: 0.25, - bottomRadius: 1, - height: 3, radialSegments: 12, heightSegments: 2 }) @@ -239,23 +275,21 @@ describe("PrimitiveMeshLoader", () => { name: "cone cap and range", data: { type: "cone", + coneRadius: 0.75, + coneHeight: 3, coneOptions: { ...groupedOptions, cap: false, angleRange: { x: 20, y: 270 }, - radius: 0.75, - height: 3, radialSegments: 12, heightSegments: 2 } }, create: () => - PrimitiveMesh.createCone(engine, { + PrimitiveMesh.createCone(engine, 0.75, 3, { ...groupedOptions, cap: false, angleRange: new Vector2(20, 270), - radius: 0.75, - height: 3, radialSegments: 12, heightSegments: 2 }) @@ -264,13 +298,13 @@ describe("PrimitiveMeshLoader", () => { name: "capsule independent segment counts", data: { type: "capsule", - capsuleOptions: { ...options, radius: 0.75, height: 3, radialSegments: 12, capSegments: 5, heightSegments: 2 } + capsuleRadius: 0.75, + capsuleHeight: 3, + capsuleOptions: { ...options, radialSegments: 12, capSegments: 5, heightSegments: 2 } }, create: () => - PrimitiveMesh.createCapsule(engine, { + PrimitiveMesh.createCapsule(engine, 0.75, 3, { ...options, - radius: 0.75, - height: 3, radialSegments: 12, capSegments: 5, heightSegments: 2 @@ -280,80 +314,75 @@ describe("PrimitiveMeshLoader", () => { name: "torus major and tube ranges", data: { type: "torus", + torusRadius: 2, + torusTubeRadius: 0.25, torusOptions: { ...options, tubeRange: { x: 45, y: 300 }, angleRange: { x: 20, y: 200 }, - radius: 2, - tubeRadius: 0.25, tubularSegments: 12, radialSegments: 8 } }, create: () => - PrimitiveMesh.createTorus(engine, { + PrimitiveMesh.createTorus(engine, 2, 0.25, { ...options, tubeRange: new Vector2(45, 300), angleRange: new Vector2(20, 200), - radius: 2, - tubeRadius: 0.25, tubularSegments: 12, radialSegments: 8 }) }, { name: "circle sector", - data: { type: "circle", circleOptions: { ...options, angleRange: { x: 30, y: 240 }, radius: 2, segments: 12 } }, + data: { + type: "circle", + circleRadius: 2, + circleOptions: { ...options, angleRange: { x: 30, y: 240 }, segments: 12 } + }, create: () => - PrimitiveMesh.createCircle(engine, { ...options, angleRange: new Vector2(30, 240), radius: 2, segments: 12 }) + PrimitiveMesh.createCircle(engine, 2, { ...options, angleRange: new Vector2(30, 240), segments: 12 }) }, { name: "ring sector", data: { type: "ring", - ringOptions: { - ...options, - angleRange: { x: 40, y: 240 }, - innerRadius: 0.5, - outerRadius: 2, - radialSegments: 12, - widthSegments: 3 - } + ringOuterRadius: 2, + ringInnerRadius: 0.5, + ringOptions: { ...options, angleRange: { x: 40, y: 240 }, radialSegments: 12, widthSegments: 3 } }, create: () => - PrimitiveMesh.createRing(engine, { + PrimitiveMesh.createRing(engine, 2, 0.5, { ...options, angleRange: new Vector2(40, 240), - outerRadius: 2, - innerRadius: 0.5, radialSegments: 12, widthSegments: 3 }) }, { name: "ring radius defaults", - data: { type: "ring", ringOptions: { ...options, outerRadius: 2 } }, - create: () => PrimitiveMesh.createRing(engine, { ...options, outerRadius: 2 }) + data: { type: "ring", ringOuterRadius: 2, ringInnerRadius: 1, ringOptions: { ...options } }, + create: () => PrimitiveMesh.createRing(engine, 2, 1, { ...options }) }, { name: "tetrahedron subdivision", - data: { type: "tetrahedron", tetrahedronOptions: { ...options, radius: 2, segments: 3 } }, - create: () => PrimitiveMesh.createTetrahedron(engine, { ...options, radius: 2, segments: 3 }) + data: { type: "tetrahedron", tetrahedronRadius: 2, tetrahedronOptions: { ...options, segments: 3 } }, + create: () => PrimitiveMesh.createTetrahedron(engine, 2, { ...options, segments: 3 }) }, { name: "octahedron subdivision", - data: { type: "octahedron", octahedronOptions: { ...options, radius: 1.5, segments: 2 } }, - create: () => PrimitiveMesh.createOctahedron(engine, { ...options, radius: 1.5, segments: 2 }) + data: { type: "octahedron", octahedronRadius: 1.5, octahedronOptions: { ...options, segments: 2 } }, + create: () => PrimitiveMesh.createOctahedron(engine, 1.5, { ...options, segments: 2 }) }, { name: "icosahedron subdivision", - data: { type: "icosahedron", icosahedronOptions: { ...options, radius: 2, segments: 3 } }, - create: () => PrimitiveMesh.createIcosahedron(engine, { ...options, radius: 2, segments: 3 }) + data: { type: "icosahedron", icosahedronRadius: 2, icosahedronOptions: { ...options, segments: 3 } }, + create: () => PrimitiveMesh.createIcosahedron(engine, 2, { ...options, segments: 3 }) }, { name: "dodecahedron subdivision", - data: { type: "dodecahedron", dodecahedronOptions: { ...options, radius: 1.5, segments: 2 } }, - create: () => PrimitiveMesh.createDodecahedron(engine, { ...options, radius: 1.5, segments: 2 }) + data: { type: "dodecahedron", dodecahedronRadius: 1.5, dodecahedronOptions: { ...options, segments: 2 } }, + create: () => PrimitiveMesh.createDodecahedron(engine, 1.5, { ...options, segments: 2 }) }, { name: "lathe profile and range", @@ -373,14 +402,14 @@ describe("PrimitiveMeshLoader", () => { name: "closed tube path", data: { type: "tube", + tubeRadius: 0.2, tubePath: path, - tubeOptions: { ...options, closed: true, radius: 0.2, tubularSegments: 16, radialSegments: 6 } + tubeOptions: { ...options, closed: true, tubularSegments: 16, radialSegments: 6 } }, create: () => - PrimitiveMesh.createTube(engine, pathVectors, { + PrimitiveMesh.createTube(engine, pathVectors, 0.2, { ...options, closed: true, - radius: 0.2, tubularSegments: 16, radialSegments: 6 }) @@ -394,6 +423,7 @@ describe("PrimitiveMeshLoader", () => { name: "beveled extrusion", data: { type: "extrusion", + extrusionDepth: 2, extrusionShapes: shapes, extrusionOptions: { ...groupedOptions, @@ -401,18 +431,16 @@ describe("PrimitiveMeshLoader", () => { bevelThickness: 0.2, bevelOffset: 0.2, bevelSegments: 2, - depth: 2, steps: 3 } }, create: () => - PrimitiveMesh.createExtrusion(engine, shapeVectors, { + PrimitiveMesh.createExtrusion(engine, shapeVectors, 2, { ...groupedOptions, bevelSize: 0.1, bevelThickness: 0.2, bevelOffset: 0.2, bevelSegments: 2, - depth: 2, steps: 3 }) }, @@ -420,137 +448,112 @@ describe("PrimitiveMeshLoader", () => { name: "inset extrusion without bevels", data: { type: "extrusion", + extrusionDepth: 2, extrusionShapes: shapes, - extrusionOptions: { ...options, bevelOffset: -0.1, depth: 2 } + extrusionOptions: { ...options, bevelOffset: -0.1 } }, - create: () => - PrimitiveMesh.createExtrusion(engine, shapeVectors, { ...options, bevelOffset: -0.1, depth: 2, steps: 1 }) + create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors, 2, { ...options, bevelOffset: -0.1, steps: 1 }) }, { name: "extrusion along a path", data: { type: "extrusion", + extrusionPath: path, extrusionShapes: shapes, - extrusionOptions: { ...groupedOptions, path: path, steps: 6 } + extrusionOptions: { ...groupedOptions, steps: 6 } }, - create: () => - PrimitiveMesh.createExtrusion(engine, shapeVectors, { ...groupedOptions, path: pathVectors, steps: 6 }) + create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors, pathVectors, { ...groupedOptions, steps: 6 }) }, { name: "closed extrusion path", data: { type: "extrusion", + extrusionPath: path, extrusionShapes: shapes, - extrusionOptions: { ...groupedOptions, closed: true, path: path, steps: 12 } + extrusionOptions: { ...groupedOptions, closed: true, steps: 12 } }, create: () => - PrimitiveMesh.createExtrusion(engine, shapeVectors, { - ...groupedOptions, - closed: true, - path: pathVectors, - steps: 12 - }) + PrimitiveMesh.createExtrusion(engine, shapeVectors, pathVectors, { ...groupedOptions, closed: true, steps: 12 }) }, { name: "linear extrusion ignores path-only settings", data: { type: "extrusion", + extrusionDepth: 2, extrusionShapes: shapes, - extrusionOptions: { ...groupedOptions, depth: 2, steps: 2, closed: true } + extrusionOptions: { ...groupedOptions, steps: 2, closed: true } }, - create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors, { ...groupedOptions, depth: 2, steps: 2 }) + create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors, 2, { ...groupedOptions, steps: 2 }) }, { name: "path extrusion ignores linear-only settings", data: { type: "extrusion", + extrusionPath: path, extrusionShapes: shapes, extrusionOptions: { ...groupedOptions, - path, steps: 6, - depth: 7, bevelSize: 0.25, bevelThickness: 0.4, bevelOffset: 0.5, bevelSegments: 8 } }, - create: () => - PrimitiveMesh.createExtrusion(engine, shapeVectors, { ...groupedOptions, path: pathVectors, steps: 6 }) + create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors, pathVectors, { ...groupedOptions, steps: 6 }) }, { name: "torus knot winding", data: { type: "torusKnot", - torusKnotOptions: { ...options, radius: 2, tubeRadius: 0.2, p: 3, q: 4, tubularSegments: 48, radialSegments: 6 } + torusKnotRadius: 2, + torusKnotTubeRadius: 0.2, + torusKnotP: 3, + torusKnotQ: 4, + torusKnotOptions: { ...options, tubularSegments: 48, radialSegments: 6 } }, create: () => - PrimitiveMesh.createTorusKnot(engine, { - ...options, - radius: 2, - tubeRadius: 0.2, - p: 3, - q: 4, - tubularSegments: 48, - radialSegments: 6 - }) + PrimitiveMesh.createTorusKnot(engine, 2, 0.2, 3, 4, { ...options, tubularSegments: 48, radialSegments: 6 }) }, { name: "negative torus knot windings", data: { type: "torusKnot", - torusKnotOptions: { - ...options, - radius: 2, - tubeRadius: 0.2, - p: -2, - q: -3, - tubularSegments: 48, - radialSegments: 8 - } + torusKnotRadius: 2, + torusKnotTubeRadius: 0.2, + torusKnotP: -2, + torusKnotQ: -3, + torusKnotOptions: { ...options, tubularSegments: 48, radialSegments: 8 } }, create: () => - PrimitiveMesh.createTorusKnot(engine, { - ...options, - radius: 2, - tubeRadius: 0.2, - p: -2, - q: -3, - tubularSegments: 48, - radialSegments: 8 - }) + PrimitiveMesh.createTorusKnot(engine, 2, 0.2, -2, -3, { ...options, tubularSegments: 48, radialSegments: 8 }) }, { name: "rounded cuboid", data: { type: "roundedCuboid", - roundedCuboidOptions: { ...groupedOptions, width: 2, height: 3, depth: 4, cornerRadius: 0.2, segments: 3 } + roundedCuboidWidth: 2, + roundedCuboidHeight: 3, + roundedCuboidDepth: 4, + roundedCuboidCornerRadius: 0.2, + roundedCuboidOptions: { ...groupedOptions, segments: 3 } }, - create: () => - PrimitiveMesh.createRoundedCuboid(engine, { - ...groupedOptions, - width: 2, - height: 3, - depth: 4, - cornerRadius: 0.2, - segments: 3 - }) + create: () => PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0.2, { ...groupedOptions, segments: 3 }) }, { name: "cuboid inherited defaults", - data: { type: "cuboid", cuboidOptions: { width: 2, widthSegments: 3 } }, - create: () => PrimitiveMesh.createCuboid(engine, { width: 2, widthSegments: 3 }) + 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", planeOptions: { width: 2, horizontalSegments: 4 } }, - create: () => PrimitiveMesh.createPlane(engine, { width: 2, horizontalSegments: 4 }) + data: { type: "plane", planeWidth: 2, planeHeight: 2, planeOptions: { horizontalSegments: 4 } }, + create: () => PrimitiveMesh.createPlane(engine, 2, 2, { horizontalSegments: 4 }) }, { name: "capsule inherited cap segments", - data: { type: "capsule", capsuleOptions: { radialSegments: 10 } }, - create: () => PrimitiveMesh.createCapsule(engine, { radialSegments: 10 }) + data: { type: "capsule", capsuleRadius: 0.5, capsuleHeight: 2, capsuleOptions: { radialSegments: 10 } }, + create: () => PrimitiveMesh.createCapsule(engine, 0.5, 2, { radialSegments: 10 }) } ]; @@ -596,10 +599,8 @@ describe("PrimitiveMeshLoader", () => { it("converts serialized ranges to Vector2 without modifying the asset", async () => { const data: PrimitiveMeshAsset = { type: "sphere", - sphereOptions: { - horizontalRange: { x: 350, y: 370 }, - verticalRange: { x: 30, y: 150 } - } + sphereRadius: 0.5, + sphereOptions: { horizontalRange: { x: 350, y: 370 }, verticalRange: { x: 30, y: 150 } } }; const serialized = JSON.stringify(data); const request = vi.spyOn(engine.resourceManager, "_request").mockReturnValue(AssetPromise.resolve(data) as any); @@ -607,7 +608,7 @@ describe("PrimitiveMeshLoader", () => { let mesh: ModelMesh | undefined; try { mesh = await engine.resourceManager.load({ url: "vector-ranges.mesh", type: AssetType.PrimitiveMesh }); - const ranges = create.mock.calls[0][1]!; + const ranges = create.mock.calls[0][2]!; expect(ranges.horizontalRange).toBeInstanceOf(Vector2); expect(ranges.verticalRange).toBeInstanceOf(Vector2); expect(ranges.horizontalRange!.toJSON()).toEqual({ x: 350, y: 370 }); @@ -632,8 +633,12 @@ describe("PrimitiveMeshLoader", () => { 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({ type, [optionsKey]: { caps, keepData: true, separateMaterials: true } }) + JSON.stringify({ ...shape, [optionsKey]: { caps, keepData: true, separateMaterials: true } }) ); expect(data[optionsKey].caps).toBe(value); request.mockReturnValue(AssetPromise.resolve(data) as any); diff --git a/tests/src/spine/SpineAlpha.test.ts b/tests/src/spine/SpineAlpha.test.ts index eb6bdc7675..8ac3e00353 100644 --- a/tests/src/spine/SpineAlpha.test.ts +++ b/tests/src/spine/SpineAlpha.test.ts @@ -121,7 +121,7 @@ describe("Spine atlas alpha encoding", () => { renderer.entity.destroy(); const meshRenderer = engine.sceneManager.activeScene.createRootEntity().addComponent(MeshRenderer); - meshRenderer.mesh = PrimitiveMesh.createCuboid(engine, { width: 2, height: 2, depth: 0.1 }); + meshRenderer.mesh = PrimitiveMesh.createCuboid(engine, 2, 2, 0.1); const material = new UnlitMaterial(engine); material.baseColor.set(0, 1, 0, 1); meshRenderer.setMaterial(material); From 807bab5726eb301858be094f527a1cc63740628b Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sat, 14 Nov 2026 21:46:11 +0800 Subject: [PATCH 04/24] refactor(core): clarify primitive parameter names Name dimensions, subdivision directions, angle ranges and winding counts by their geometric meaning. Clarify CPU-data retention and material slots. Update serialized inputs, consumers, documentation and screenshot labels. BREAKING CHANGE: Primitive parameters, options and serialized fields use the descriptive names documented in the updated declarations. --- docs/en/graphics/mesh/primitiveMesh.mdx | 50 +- docs/zh/graphics/mesh/primitiveMesh.mdx | 50 +- e2e/case/material-white-furnace.ts | 2 +- e2e/case/multi-camera-no-clear.ts | 4 +- e2e/case/primitive-all.ts | 33 +- e2e/case/primitive-contours.ts | 28 +- e2e/case/primitive-materials.ts | 41 +- e2e/case/primitive-sections.ts | 12 +- e2e/case/primitive-sphere-sections.ts | 24 +- e2e/case/primitive-topology.ts | 66 +-- .../Primitive_primitive-contours.jpg | 4 +- .../Primitive_primitive-materials.jpg | 4 +- .../Primitive_primitive-sections.jpg | 4 +- .../Primitive_primitive-topology.jpg | 4 +- e2e/primitive-mesh.md | 2 +- examples/src/shader-03-ui-script.ts | 2 +- examples/src/shader-04-multi-pass.ts | 2 +- packages/core/src/mesh/PrimitiveMesh.ts | 232 ++++----- .../core/src/mesh/PrimitiveMeshOptions.ts | 68 +-- .../references/mesh-geometry.md | 26 +- packages/loader/src/PrimitiveMeshAsset.ts | 12 +- packages/loader/src/PrimitiveMeshLoader.ts | 8 +- .../fixtures/PrimitiveMeshApi.ts | 109 ++--- .../fixtures/PrimitiveMeshAsset.ts | 26 +- tests/src/core/mesh/BlendShapeManager.test.ts | 2 +- tests/src/core/mesh/PrimitiveMesh.test.ts | 44 +- tests/src/core/mesh/ProceduralMesh.test.ts | 442 +++++++++--------- tests/src/core/physics/ColliderLayer.test.ts | 2 +- .../core/physics/MeshColliderLayer.test.ts | 2 +- tests/src/loader/PrimitiveMeshLoader.test.ts | 177 +++---- 30 files changed, 781 insertions(+), 701 deletions(-) diff --git a/docs/en/graphics/mesh/primitiveMesh.mdx b/docs/en/graphics/mesh/primitiveMesh.mdx index d189fd7634..8435905751 100644 --- a/docs/en/graphics/mesh/primitiveMesh.mdx +++ b/docs/en/graphics/mesh/primitiveMesh.mdx @@ -136,7 +136,7 @@ Each factory takes its required shape inputs first, followed by an optional name ```ts const unitSphere = PrimitiveMesh.createSphere(engine, 0.5); const sphere = PrimitiveMesh.createSphere(engine, 1); -const smoothSphere = PrimitiveMesh.createSphere(engine, 1, { subdivisions: 4 }); +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); @@ -145,9 +145,9 @@ 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 height 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. +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, `p` and `q` are signed integer revolution counts, independent of mesh subdivisions. Negative values reverse the corresponding winding direction; zero keeps that angle fixed. +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. | Capability | Methods | | --- | --- | @@ -159,14 +159,14 @@ For torus knots, `p` and `q` are signed integer revolution counts, independent o ### Subdivisions, angles and caps -Dimensions are required arguments; subdivision counts remain in the optional settings object. For tubes and tori, `tubularSegments` controls longitudinal subdivisions and `radialSegments` controls the cross-section. Capsule `capSegments` controls each pole-to-equator section independently; its height describes the cylindrical section. +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, cones and lathes rotate around Y starting from +Z; a sphere's vertical angle starts at +Y. ```ts import { PrimitiveMeshCapMode, Vector2 } from "@galacean/engine"; -const hemisphere = PrimitiveMesh.createSphere(engine, 1, { verticalRange: new Vector2(0, 90) }); +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) }); @@ -174,7 +174,7 @@ const halfRing = PrimitiveMesh.createRing(engine, 1, 0.5, { angleRange: new Vect 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 `horizontalRange` and `verticalRange`. 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. +`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 @@ -187,40 +187,44 @@ const outline = [new Vector2(-2, -2), new Vector2(2, -2), new Vector2(2, 2), new 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.createExtrusion(engine, { points: outline, holes: [hole] }, 0.5); -const beveled = PrimitiveMesh.createExtrusion(engine, outline, 0.5, { bevelSize: 0.05, bevelOffset: 0.02, steps: 1 }); +const beveled = PrimitiveMesh.createExtrusion(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, { tubularSegments: 64 }); -const swept = PrimitiveMesh.createExtrusion(engine, outline, path, { steps: 64 }); +const tube = PrimitiveMesh.createTube(engine, path, 0.1, { pathSegments: 64 }); +const swept = PrimitiveMesh.createExtrusion(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 closed = PrimitiveMesh.createExtrusion(engine, outline, loop, { closed: true, steps: 32 }); +const closedPath = PrimitiveMesh.createExtrusion(engine, outline, loop, { closedPath: true, pathSegments: 32 }); ``` -Extrusion requires a third argument: a numeric depth for linear extrusion, or a `Vector3` array for path extrusion. `LinearExtrusionMeshOptions` contains optional bevel settings; `PathExtrusionMeshOptions` contains optional path settings. Each interface declares its mode's settings. A path ignores bevel settings; a numeric depth ignores `closed`. Linear extrusion goes along +Z without bevels unless requested. A positive `bevelSize` enables beveling; `bevelThickness` defaults to the same value. Path extrusion does not generate bevels. Paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points before creating the mesh, as shown above. +Extrusion requires a third argument: a numeric depth for linear extrusion, or a `Vector3` array for path extrusion. `LinearExtrusionMeshOptions` contains optional bevel settings; `PathExtrusionMeshOptions` contains optional path settings. Linear extrusion uses `depthSegments`; path extrusion uses `pathSegments`. Each interface declares its mode's settings. A path ignores bevel settings; a numeric depth ignores `closedPath`. Linear extrusion goes along +Z without bevels unless requested. A positive `bevelWidth` enables beveling; `bevelDepth` defaults to the same value. Path extrusion does not generate bevels. Paths accept `Vector3` arrays and 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, `closed` 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 steps and have no end caps. Open extrusions have two end caps; tubes have no end caps in either mode. +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. -`bevelOffset` 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 `bevelSize` is `0`. Bevels are cut into this outline and included in `depth`, so they do not increase the total depth. +`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. ### Mesh data and materials Mesh settings and subdivision counts belong to the optional settings object: ```ts -const editable = PrimitiveMesh.createSphere(engine, 1, { keepData: true, subdivisions: 3 }); +const editable = PrimitiveMesh.createSphere(engine, 1, { keepCPUData: true, subdivisionLevel: 3 }); const sixMaterials = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { - separateMaterials: true, + separateMaterialSlots: true, widthSegments: 1, heightSegments: 1, depthSegments: 1 }); ``` -`keepData` defaults to false. Set it to true to retain readable CPU vertex attributes. +`keepCPUData` defaults to false. Set it to true to retain readable CPU vertex attributes. -`separateMaterials` 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: +`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 | | --- | --- | @@ -246,7 +250,7 @@ import type { PrimitiveMeshAsset } from "@galacean/engine"; const asset = { type: "sphere", sphereRadius: 1, - sphereOptions: { subdivisions: 3, keepData: true } + sphereOptions: { subdivisionLevel: 3, keepCPUData: true } } satisfies PrimitiveMeshAsset; ``` @@ -256,7 +260,7 @@ Each `type` selects the matching `PrimitiveMesh.createX` method. Type-prefixed f | --- | --- | | `sphere`, `circle` | `Radius` | | `cuboid` | `cuboidWidth`, `cuboidHeight`, `cuboidDepth` | -| `plane` | `planeWidth`, `planeHeight` | +| `plane` | `planeWidth`, `planeDepth` | | `cylinder`, `cone`, `capsule` | `Radius`, `Height` | | `truncatedCone` | `truncatedConeTopRadius`, `truncatedConeBottomRadius`, `truncatedConeHeight` | | `torus` | `torusRadius`, `torusTubeRadius` | @@ -266,10 +270,10 @@ Each `type` selects the matching `PrimitiveMesh.createX` method. Type-prefixed f | `tube` | `tubePath`, `tubeRadius` | | `polygon` | `polygonShapes` | | `extrusion` | `extrusionShapes`, plus `extrusionDepth` or `extrusionPath` | -| `torusKnot` | `torusKnotRadius`, `torusKnotTubeRadius`, `torusKnotP`, `torusKnotQ` | +| `torusKnot` | `torusKnotRadius`, `torusKnotTubeRadius`, `torusKnotAxisTurns`, `torusKnotCrossSectionTurns` | | `roundedCuboid` | `roundedCuboidWidth`, `roundedCuboidHeight`, `roundedCuboidDepth`, `roundedCuboidCornerRadius` | -`sphere` creates a subdivided cube projected onto a sphere; `sphereOptions.subdivisions` controls its subdivision level. `cylinder` has one radius; `truncatedCone` has independent `truncatedConeTopRadius` and `truncatedConeBottomRadius`. +`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`: @@ -295,10 +299,10 @@ Profiles and polygon contours store `{ x, y }` points; paths store `{ x, y, z }` } ], "extrusionDepth": 2, - "extrusionOptions": { "bevelSize": 0.1, "bevelOffset": 0.2, "separateMaterials": true } + "extrusionOptions": { "bevelWidth": 0.1, "contourOffset": 0.2, "separateMaterialSlots": true } } ``` -Path extrusion uses the required `extrusionPath` field instead of `extrusionDepth` and ignores bevel settings. Set `extrusionOptions.closed` to `true` for a closed path without end caps. Save path points as `{ x, y, z }`. +Path extrusion uses the required `extrusionPath` field instead of `extrusionDepth` and ignores bevel settings. Set `extrusionOptions.closedPath` to `true` for a closed path without end caps. Save path points as `{ x, y, z }`. The type-prefixed fields, including `Options`, pass through the Editor's primitive asset bundler. Editor previews should select the same creation method and parameters as the saved asset. diff --git a/docs/zh/graphics/mesh/primitiveMesh.mdx b/docs/zh/graphics/mesh/primitiveMesh.mdx index a081079931..adfb213d6f 100644 --- a/docs/zh/graphics/mesh/primitiveMesh.mdx +++ b/docs/zh/graphics/mesh/primitiveMesh.mdx @@ -136,7 +136,7 @@ renderer.setMaterial(material); ```ts const unitSphere = PrimitiveMesh.createSphere(engine, 0.5); const sphere = PrimitiveMesh.createSphere(engine, 1); -const smoothSphere = PrimitiveMesh.createSphere(engine, 1, { subdivisions: 4 }); +const smoothSphere = PrimitiveMesh.createSphere(engine, 1, { subdivisionLevel: 4 }); const cube = PrimitiveMesh.createCuboid(engine, 2, 2, 2); const box = PrimitiveMesh.createCuboid(engine, 2, 3, 4); @@ -147,11 +147,11 @@ 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` 先接收外半径,再接收内半径,两者都必须指定。 +`createCuboid` 的宽、高、深是三个独立的必填参数;`createPlane` 的宽、深也必须分别指定。平面和长方体的后续分段数默认沿用第一个方向的分段数。球体使用一个细分层级,默认为 3,限制在 1 到 6 之间。`createCylinder` 只有一个半径;上下半径不同的圆台使用 `createTruncatedCone`。`createRing` 先接收外半径,再接收内半径,两者都必须指定。 尺寸必须显式传入;分段和网格设置使用具名字段,可以只指定需要调整的可选项。 -环面结的 `p`、`q` 是有符号整数缠绕次数,与网格分段数无关。负值反转对应方向的缠绕,`0` 表示该方向的角度保持不变。 +环面结的 `axisTurns` 表示绕中心轴的圈数,`crossSectionTurns` 表示绕环面截面的圈数。两者都是有符号整数,与网格分段数无关。负值反转对应方向的缠绕,`0` 表示该方向的角度保持不变。 | 能力 | 创建方法 | | --- | --- | @@ -163,14 +163,14 @@ const mirroredKnot = PrimitiveMesh.createTorusKnot(engine, 1, 0.1, 2, -3); ### 分段、角度和端盖 -`createTube` 与 `createTorus` 的 `tubularSegments` 控制管道方向的分段,`radialSegments` 控制截面的周向分段。胶囊的 `capSegments` 独立控制每个半球从极点到赤道的分段,`height` 仍指圆柱部分的高度。 +管道和环面结用 `pathSegments` 控制沿路径的分段,圆环用 `ringSegments` 控制环向分段,`radialSegments` 控制管截面的周向分段。胶囊的 `capSegments` 控制每个半球从极点到赤道的分段,`cylinderHeight` 表示直筒部分的高度。正多面体用 `edgeSegments`,圆角长方体用 `roundingSegments`。 角度范围统一放在配置对象中。所有角度均使用**度数**,范围使用 `Vector2`,`x` 表示起始角,`y` 表示结束角。跨越 360 度时使用连续角度,例如 `new Vector2(350, 370)`。圆柱、圆锥和旋转体围绕 Y 轴,0 度从 +Z 方向开始;球体的垂直角度从 +Y 极点开始。 ```ts import { PrimitiveMeshCapMode, Vector2 } from "@galacean/engine"; -const hemisphere = PrimitiveMesh.createSphere(engine, 1, { verticalRange: new Vector2(0, 90) }); +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) }); @@ -178,7 +178,7 @@ const halfRing = PrimitiveMesh.createRing(engine, 1, 0.5, { angleRange: new Vect 圆柱和圆台的 `caps` 使用 `PrimitiveMeshCapMode`:`Both`(默认)、`Top`、`Bottom`、`None`。顶盖朝 +Y,底盖朝 -Y,角度裁切产生的侧面切口保持开放。圆锥用布尔值 `cap` 控制底盖。`createCircle`、`createRing` 和多边形位于 XY 平面、正面朝 +Z;地面用的 `createPlane` 位于 XZ 平面、正面朝 +Y。 -`createSphere` 将细分后的立方体投影到球面,支持 `horizontalRange` 和 `verticalRange`。水平角度从 -X 朝 +Z 开始,垂直角度从 +Y 极点开始。裁切保留细分表面,切口不生成端盖;水平范围 `new Vector2(350, 370)` 可跨越接缝。细分层级控制表面及裁切边界的精细程度。 +`createSphere` 将细分后的立方体投影到球面,支持 `horizontalAngleRange` 和 `verticalAngleRange`。水平角度从 -X 朝 +Z 开始,垂直角度从 +Y 极点开始。裁切保留细分表面,切口不生成端盖;水平范围 `new Vector2(350, 370)` 可跨越接缝。细分层级控制表面及裁切边界的精细程度。 ### 轮廓与路径 @@ -192,41 +192,45 @@ const hole = [new Vector2(-1, -1), new Vector2(-1, 1), new Vector2(1, 1), new Ve const face = PrimitiveMesh.createPolygon(engine, { points: outline, holes: [hole] }); const solid = PrimitiveMesh.createExtrusion(engine, { points: outline, holes: [hole] }, 0.5); -const beveled = PrimitiveMesh.createExtrusion(engine, outline, 0.5, { bevelSize: 0.05, bevelOffset: 0.02, steps: 1 }); +const beveled = PrimitiveMesh.createExtrusion(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, { tubularSegments: 64 }); -const swept = PrimitiveMesh.createExtrusion(engine, outline, path, { steps: 64 }); +const tube = PrimitiveMesh.createTube(engine, path, 0.1, { pathSegments: 64 }); +const swept = PrimitiveMesh.createExtrusion(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 closed = PrimitiveMesh.createExtrusion(engine, outline, loop, { closed: true, steps: 32 }); +const closedPath = PrimitiveMesh.createExtrusion(engine, outline, loop, { closedPath: true, pathSegments: 32 }); ``` -拉伸的第三个参数必填:传入数值深度时沿 +Z 直线拉伸,传入 `Vector3` 数组时沿路径挤出。`LinearExtrusionMeshOptions` 包含可选的倒角设置,`PathExtrusionMeshOptions` 包含可选的路径设置。两个接口分别声明各自模式的设置。沿路径挤出时忽略倒角设置;直线拉伸时忽略 `closed`。直线拉伸默认不倒角;`bevelSize > 0` 时开启倒角,`bevelThickness` 默认等于 `bevelSize`。沿路径拉伸不生成倒角。路径接收 `Vector3` 数组,并按折线长度均匀采样。使用曲线时,在外层采样成点数组后传入,如上例所示。 +拉伸的第三个参数必填:传入数值深度时沿 +Z 直线拉伸,传入 `Vector3` 数组时沿路径挤出。`LinearExtrusionMeshOptions` 包含可选的倒角设置,`PathExtrusionMeshOptions` 包含可选的路径设置。直线拉伸用 `depthSegments`,路径拉伸用 `pathSegments`;两个接口分别声明各自模式的设置。沿路径挤出时忽略倒角设置;直线拉伸时忽略 `closedPath`。直线拉伸默认不倒角;`bevelWidth > 0` 时开启倒角,`bevelDepth` 默认等于 `bevelWidth`。沿路径拉伸不生成倒角。路径接收 `Vector3` 数组,并按折线长度均匀采样。使用曲线时,在外层采样成点数组后传入,如上例所示。 -管道和路径挤出的 `closed` 默认关闭;开启后自动连接路径首尾并对齐截面,不必重复首点。闭合挤出至少使用三段,不生成端盖。开放挤出保留两端端盖;管道在两种模式下都不生成端盖。 +管道和路径挤出的 `closedPath` 默认关闭;开启后自动连接路径首尾并对齐截面,不必重复首点。闭合挤出至少使用三段,不生成端盖。开放挤出保留两端端盖;管道在两种模式下都不生成端盖。 -`bevelOffset` 默认是 `0`,用于偏移侧壁轮廓:正值外扩实体并缩小孔洞,负值内缩实体并扩大孔洞。`bevelSize` 为 `0` 时偏移仍然生效。倒角从偏移后的轮廓向内削边,厚度包含在 `depth` 内,不会增加总厚度。 +`contourOffset` 默认是 `0`,用于偏移侧壁轮廓:正值外扩实体并缩小孔洞,负值内缩实体并扩大孔洞。`bevelWidth` 为 `0` 时偏移仍然生效。倒角从偏移后的轮廓向内削边,厚度包含在 `depth` 内,不会增加总厚度。 ### 网格数据和材质 网格设置与分段设置放在同一个可选配置对象中: ```ts -const editable = PrimitiveMesh.createSphere(engine, 1, { keepData: true, subdivisions: 3 }); +const editable = PrimitiveMesh.createSphere(engine, 1, { keepCPUData: true, subdivisionLevel: 3 }); const sixMaterials = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { - separateMaterials: true, + separateMaterialSlots: true, widthSegments: 1, heightSegments: 1, depthSegments: 1 }); ``` -`keepData` 默认关闭,设为 `true` 时保留可读的 CPU 顶点属性。 +`keepCPUData` 默认关闭,设为 `true` 时保留可读的 CPU 顶点属性。 -`separateMaterials` 适用于长方体、圆柱、圆台、圆锥、多边形、挤出和圆角长方体。默认关闭,生成一个 SubMesh;开启后,生成的 SubMesh 按以下顺序对应材质槽: +`separateMaterialSlots` 适用于长方体、圆柱、圆台、圆锥、多边形、挤出和圆角长方体。默认关闭,生成一个 SubMesh;开启后,生成的 SubMesh 按以下顺序对应材质槽: | 几何体 | 材质槽顺序 | | ------------------ | ---------------------------------------------------------------------------- | @@ -252,7 +256,7 @@ import type { PrimitiveMeshAsset } from "@galacean/engine"; const asset = { type: "sphere", sphereRadius: 1, - sphereOptions: { subdivisions: 3, keepData: true } + sphereOptions: { subdivisionLevel: 3, keepCPUData: true } } satisfies PrimitiveMeshAsset; ``` @@ -262,7 +266,7 @@ const asset = { | --- | --- | | `sphere`、`circle` | `Radius` | | `cuboid` | `cuboidWidth`、`cuboidHeight`、`cuboidDepth` | -| `plane` | `planeWidth`、`planeHeight` | +| `plane` | `planeWidth`、`planeDepth` | | `cylinder`、`cone`、`capsule` | `Radius`、`Height` | | `truncatedCone` | `truncatedConeTopRadius`、`truncatedConeBottomRadius`、`truncatedConeHeight` | | `torus` | `torusRadius`、`torusTubeRadius` | @@ -272,10 +276,10 @@ const asset = { | `tube` | `tubePath`、`tubeRadius` | | `polygon` | `polygonShapes` | | `extrusion` | `extrusionShapes`,以及 `extrusionDepth` 或 `extrusionPath` | -| `torusKnot` | `torusKnotRadius`、`torusKnotTubeRadius`、`torusKnotP`、`torusKnotQ` | +| `torusKnot` | `torusKnotRadius`、`torusKnotTubeRadius`、`torusKnotAxisTurns`、`torusKnotCrossSectionTurns` | | `roundedCuboid` | `roundedCuboidWidth`、`roundedCuboidHeight`、`roundedCuboidDepth`、`roundedCuboidCornerRadius` | -`sphere` 创建立方体细分后投影得到的球体,`sphereOptions.subdivisions` 控制细分层级。`cylinder` 使用一个半径;`truncatedCone` 分别使用 `truncatedConeTopRadius` 和 `truncatedConeBottomRadius`。 +`sphere` 创建立方体细分后投影得到的球体,`sphereOptions.subdivisionLevel` 控制细分层级。`cylinder` 使用一个半径;`truncatedCone` 分别使用 `truncatedConeTopRadius` 和 `truncatedConeBottomRadius`。 轮廓和旋转截面保存为 `{ x, y }` 点数组,路径保存为 `{ x, y, z }` 点数组,由 Loader 构造对应向量。多边形与拉伸统一使用形状数组,每个形状包含 `points` 和可选的 `holes`: @@ -301,10 +305,10 @@ const asset = { } ], "extrusionDepth": 2, - "extrusionOptions": { "bevelSize": 0.1, "bevelOffset": 0.2, "separateMaterials": true } + "extrusionOptions": { "bevelWidth": 0.1, "contourOffset": 0.2, "separateMaterialSlots": true } } ``` -沿路径拉伸通过必填的 `extrusionPath` 代替 `extrusionDepth`,并忽略倒角设置。`extrusionOptions.closed` 设为 `true` 时闭合路径且不生成端盖。路径点保存为 `{ x, y, z }`。 +沿路径拉伸通过必填的 `extrusionPath` 代替 `extrusionDepth`,并忽略倒角设置。`extrusionOptions.closedPath` 设为 `true` 时闭合路径且不生成端盖。路径点保存为 `{ x, y, z }`。 以上类型前缀字段及 `Options` 都能经过 Editor 现有的基础网格打包过滤。Editor 预览应使用与保存资产相同的创建方法和参数。 diff --git a/e2e/case/material-white-furnace.ts b/e2e/case/material-white-furnace.ts index e7df9c5da3..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, { subdivisions: 4 }); + 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 51c256a5e9..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, { subdivisions: 3 }); + 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, { subdivisions: 3 }); + 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/primitive-all.ts b/e2e/case/primitive-all.ts index c53c584f21..144a88bf7f 100644 --- a/e2e/case/primitive-all.ts +++ b/e2e/case/primitive-all.ts @@ -86,7 +86,7 @@ class PrimitiveMeshGallery { cuboid: { label: "Cuboid", mesh: PrimitiveMesh.createCuboid(engine, 1, 1, 1, { - separateMaterials: true, + separateMaterialSlots: true, widthSegments: 2, heightSegments: 2, depthSegments: 2 @@ -94,14 +94,14 @@ class PrimitiveMeshGallery { }, plane: { label: "Plane", - mesh: PrimitiveMesh.createPlane(engine, 2, 2, { horizontalSegments: 4, verticalSegments: 4 }), + mesh: PrimitiveMesh.createPlane(engine, 2, 2, { widthSegments: 4, depthSegments: 4 }), rotation: new Vector3(90, 0, 0) }, - sphere: { label: "Sphere", mesh: PrimitiveMesh.createSphere(engine, 1, { subdivisions: 3 }) }, + sphere: { label: "Sphere", mesh: PrimitiveMesh.createSphere(engine, 1, { subdivisionLevel: 3 }) }, cylinder: { label: "Cylinder", mesh: PrimitiveMesh.createCylinder(engine, 0.65, 1.5, { - separateMaterials: true, + separateMaterialSlots: true, radialSegments: 24, heightSegments: 2 }) @@ -109,7 +109,7 @@ class PrimitiveMeshGallery { cone: { label: "Cone", mesh: PrimitiveMesh.createCone(engine, 0.8, 1.8, { - separateMaterials: true, + separateMaterialSlots: true, radialSegments: 24, heightSegments: 2 }) @@ -117,7 +117,7 @@ class PrimitiveMeshGallery { truncatedCone: { label: "Truncated Cone", mesh: PrimitiveMesh.createTruncatedCone(engine, 0.35, 0.8, 1.6, { - separateMaterials: true, + separateMaterialSlots: true, radialSegments: 24, heightSegments: 2 }) @@ -128,11 +128,11 @@ class PrimitiveMeshGallery { }, torus: { label: "Torus", - mesh: PrimitiveMesh.createTorus(engine, 0.75, 0.25, { tubularSegments: 32, radialSegments: 12 }) + 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, { tubularSegments: 96, radialSegments: 10 }) + mesh: PrimitiveMesh.createTorusKnot(engine, 0.65, 0.17, 2, 3, { pathSegments: 96, radialSegments: 10 }) }, circle: { label: "Circle", @@ -141,7 +141,7 @@ class PrimitiveMeshGallery { }, ring: { label: "Ring", - mesh: PrimitiveMesh.createRing(engine, 1, 0.5, { radialSegments: 32, widthSegments: 2 }), + mesh: PrimitiveMesh.createRing(engine, 1, 0.5, { ringSegments: 32, widthSegments: 2 }), rotation: new Vector3() }, tetrahedron: { label: "Tetrahedron", mesh: PrimitiveMesh.createTetrahedron(engine, 1) }, @@ -151,22 +151,25 @@ class PrimitiveMeshGallery { lathe: { label: "Lathe", mesh: PrimitiveMesh.createLathe(engine, profile, { segments: 24 }) }, tube: { label: "Tube", - mesh: PrimitiveMesh.createTube(engine, path, 0.2, { tubularSegments: 48, radialSegments: 10 }) + mesh: PrimitiveMesh.createTube(engine, path, 0.2, { pathSegments: 48, radialSegments: 10 }) }, polygon: { label: "Polygon", mesh: PrimitiveMesh.createPolygon(engine, polygon), rotation: new Vector3() }, extrusion: { label: "Extrusion", mesh: PrimitiveMesh.createExtrusion(engine, polygon, 0.6, { - bevelSize: 0.1, - bevelThickness: 0.1, + bevelWidth: 0.1, + bevelDepth: 0.1, bevelSegments: 3, - separateMaterials: true, - steps: 2 + separateMaterialSlots: true, + depthSegments: 2 }) }, roundedCuboid: { label: "Rounded Cuboid", - mesh: PrimitiveMesh.createRoundedCuboid(engine, 2, 1.6, 1.4, 0.3, { separateMaterials: true, segments: 4 }) + 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)}`); diff --git a/e2e/case/primitive-contours.ts b/e2e/case/primitive-contours.ts index d40a117c47..52efffa1c9 100644 --- a/e2e/case/primitive-contours.ts +++ b/e2e/case/primitive-contours.ts @@ -70,47 +70,47 @@ class PrimitiveContours { }, { label: "Independent bevel depth", - detail: "size: 0.16 / thickness: 0.06", + detail: "bevel width: 0.16 / depth: 0.06", mesh: PrimitiveMesh.createExtrusion(engine, polygon, 0.6, { - bevelSize: 0.16, - bevelThickness: 0.06, + bevelWidth: 0.16, + bevelDepth: 0.06, bevelSegments: 4 }) }, { label: "Expanded contour", detail: "offset: +0.15 / no bevel", - mesh: PrimitiveMesh.createExtrusion(engine, polygon, 0.6, { bevelOffset: 0.15 }) + mesh: PrimitiveMesh.createExtrusion(engine, polygon, 0.6, { contourOffset: 0.15 }) }, { label: "Contracted contour", - detail: "bevelOffset: -0.15", - mesh: PrimitiveMesh.createExtrusion(engine, polygon, 0.6, { bevelOffset: -0.15, bevelSize: 0.08 }) + detail: "contourOffset: -0.15", + mesh: PrimitiveMesh.createExtrusion(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, { tubularSegments: 48, radialSegments: 12 }) + mesh: PrimitiveMesh.createTube(engine, path, 0.15, { pathSegments: 48, radialSegments: 12 }) }, { label: "Closed tube", - detail: "closed: true / seamless join", - mesh: PrimitiveMesh.createTube(engine, loop, 0.15, { tubularSegments: 64, radialSegments: 12, closed: true }) + detail: "closedPath: true / seamless join", + mesh: PrimitiveMesh.createTube(engine, loop, 0.15, { pathSegments: 64, radialSegments: 12, closedPath: true }) }, { label: "Open profile sweep", - detail: "path + steps: 48", - mesh: PrimitiveMesh.createExtrusion(engine, smallProfile, path, { steps: 48 }) + detail: "pathSegments: 48", + mesh: PrimitiveMesh.createExtrusion(engine, smallProfile, path, { pathSegments: 48 }) }, { label: "Closed profile sweep", - detail: "closed: true / no caps", - mesh: PrimitiveMesh.createExtrusion(engine, smallProfile, loop, { steps: 64, closed: true }) + detail: "closedPath: true / no caps", + mesh: PrimitiveMesh.createExtrusion(engine, smallProfile, loop, { pathSegments: 64, closedPath: true }) }, { label: "Hollow profile sweep", detail: "path + inner contour", - mesh: PrimitiveMesh.createExtrusion(engine, smallHoleProfile, path, { steps: 48 }) + mesh: PrimitiveMesh.createExtrusion(engine, smallHoleProfile, path, { pathSegments: 48 }) } ], 4 diff --git a/e2e/case/primitive-materials.ts b/e2e/case/primitive-materials.ts index 91e3b82772..a952e193de 100644 --- a/e2e/case/primitive-materials.ts +++ b/e2e/case/primitive-materials.ts @@ -19,94 +19,101 @@ class PrimitiveMaterials { 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: { subdivisions: 2 } } satisfies PrimitiveMeshAsset; + 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, { subdivisions: 2, keepData: true }); + const retained = PrimitiveMesh.createSphere(engine, 1, { subdivisionLevel: 2, keepCPUData: 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: "separateMaterials: false", + 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, { separateMaterials: true }), + 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, { separateMaterials: true }), + 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, { separateMaterials: true }), + 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, { separateMaterials: true }), + mesh: PrimitiveMesh.createPolygon(engine, polygons, { separateMaterialSlots: true }), slots: 2, rotation: new Vector3() }, { label: "Extrusion / cap and wall", detail: "caps / walls + bevels", - mesh: PrimitiveMesh.createExtrusion(engine, square, 0.6, { bevelSize: 0.12, separateMaterials: true }), + mesh: PrimitiveMesh.createExtrusion(engine, square, 0.6, { bevelWidth: 0.12, separateMaterialSlots: true }), slots: 2 }, { label: "Closed / two profiles", detail: "one wall slot per profile", mesh: PrimitiveMesh.createExtrusion(engine, profiles, loop, { - steps: 64, - closed: true, - separateMaterials: true + 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, { segments: 4, separateMaterials: true }), + mesh: PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.2, { + roundingSegments: 4, + separateMaterialSlots: true + }), slots: 6 }, { label: "Factory / retained data", - detail: "keepData: true / readable", + detail: "CPU data: readable", mesh: retained, slots: 1, appearance: "checker" }, { label: "JSON asset / released data", - detail: "keepData: false / same shape", + detail: "CPU data: released", mesh: loaded, slots: 1, appearance: "checker" }, { label: "Mirrored torus knot", - detail: "p: 2 / q: -3", - mesh: PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2, -3, { tubularSegments: 96 }), + 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, { segments: 6 }), + mesh: PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 2, { roundingSegments: 6 }), slots: 1, appearance: "checker" } diff --git a/e2e/case/primitive-sections.ts b/e2e/case/primitive-sections.ts index 3b20ab3f7a..b2671c52aa 100644 --- a/e2e/case/primitive-sections.ts +++ b/e2e/case/primitive-sections.ts @@ -27,20 +27,20 @@ class PrimitiveSections { }, { label: "Torus arc", - detail: "angleRange: [30, 300]", - mesh: PrimitiveMesh.createTorus(engine, 0.5, 0.1, { angleRange: new Vector2(30, 300) }) + detail: "ringAngleRange: [30, 300]", + mesh: PrimitiveMesh.createTorus(engine, 0.5, 0.1, { ringAngleRange: new Vector2(30, 300) }) }, { label: "Torus cross-section", - detail: "tubeRange: [0, 180]", - mesh: PrimitiveMesh.createTorus(engine, 0.5, 0.2, { tubeRange: new Vector2(0, 180) }) + 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, { - angleRange: new Vector2(30, 300), - tubeRange: new Vector2(45, 315) + ringAngleRange: new Vector2(30, 300), + tubeAngleRange: new Vector2(45, 315) }) }, { label: "Cylinder: both", detail: "caps: both", mesh: PrimitiveMesh.createCylinder(engine, 0.5, 1.4) }, diff --git a/e2e/case/primitive-sphere-sections.ts b/e2e/case/primitive-sphere-sections.ts index 9ea6e2e934..c0ee87bb6e 100644 --- a/e2e/case/primitive-sphere-sections.ts +++ b/e2e/case/primitive-sphere-sections.ts @@ -55,31 +55,35 @@ class SphereSections { material.baseTexture = texture; const cases: { name: string; - horizontalRange?: Vector2; - verticalRange?: Vector2; + horizontalAngleRange?: Vector2; + verticalAngleRange?: Vector2; rotation?: Vector3; }[] = [ { name: "Full sphere" }, - { name: "Hemisphere", verticalRange: new Vector2(0, 90) }, - { name: "Half longitude", horizontalRange: new Vector2(90, 270) }, - { name: "Octant", horizontalRange: new Vector2(90, 180), verticalRange: new Vector2(0, 90) }, - { name: "Latitude band", verticalRange: new Vector2(50, 130) }, + { 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", - horizontalRange: new Vector2(330, 390), - verticalRange: new Vector2(20, 160), + 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, horizontalRange, verticalRange, rotation }, index) => { + 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, { horizontalRange, verticalRange, subdivisions: 3 }); + 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); diff --git a/e2e/case/primitive-topology.ts b/e2e/case/primitive-topology.ts index 3d55d8f5fd..42f688c402 100644 --- a/e2e/case/primitive-topology.ts +++ b/e2e/case/primitive-topology.ts @@ -8,17 +8,17 @@ class PrimitiveTopology { static async create(): Promise { const gallery = await PrimitiveMeshGallery.create(); const { engine } = gallery; - const keep = { keepData: true }; + const keep = { keepCPUData: true }; const examples: PrimitiveMeshExample[] = [ { label: "Sphere / level 1", - detail: "subdivisions: 1", - mesh: PrimitiveMesh.createSphere(engine, 0.5, { ...keep, subdivisions: 1 }) + detail: "subdivisionLevel: 1", + mesh: PrimitiveMesh.createSphere(engine, 0.5, { ...keep, subdivisionLevel: 1 }) }, { label: "Sphere / level 3", - detail: "subdivisions: 3", - mesh: PrimitiveMesh.createSphere(engine, 0.5, { ...keep, subdivisions: 3 }) + detail: "subdivisionLevel: 3", + mesh: PrimitiveMesh.createSphere(engine, 0.5, { ...keep, subdivisionLevel: 3 }) }, { label: "Cylinder / 6 sides", @@ -47,14 +47,14 @@ class PrimitiveTopology { }, { label: "Plane / 1 by 6", - detail: "horizontal: 1 / vertical: 6", - mesh: PrimitiveMesh.createPlane(engine, 1, 1, { ...keep, horizontalSegments: 1, verticalSegments: 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: "horizontal: 6 / vertical: 1", - mesh: PrimitiveMesh.createPlane(engine, 1, 1, { ...keep, horizontalSegments: 6, verticalSegments: 1 }), + detail: "width: 6 / depth: 1", + mesh: PrimitiveMesh.createPlane(engine, 1, 1, { ...keep, widthSegments: 6, depthSegments: 1 }), rotation: new Vector3(65, -20, 0) }, { @@ -74,28 +74,28 @@ class PrimitiveTopology { }, { label: "Tetrahedron subdivision", - detail: "segments: 3", - mesh: PrimitiveMesh.createTetrahedron(engine, 0.5, { ...keep, segments: 3 }) + detail: "edgeSegments: 3", + mesh: PrimitiveMesh.createTetrahedron(engine, 0.5, { ...keep, edgeSegments: 3 }) }, { label: "Octahedron subdivision", - detail: "segments: 3", - mesh: PrimitiveMesh.createOctahedron(engine, 0.5, { ...keep, segments: 3 }) + detail: "edgeSegments: 3", + mesh: PrimitiveMesh.createOctahedron(engine, 0.5, { ...keep, edgeSegments: 3 }) }, { label: "Icosahedron subdivision", - detail: "segments: 3", - mesh: PrimitiveMesh.createIcosahedron(engine, 0.5, { ...keep, segments: 3 }) + detail: "edgeSegments: 3", + mesh: PrimitiveMesh.createIcosahedron(engine, 0.5, { ...keep, edgeSegments: 3 }) }, { label: "Dodecahedron subdivision", - detail: "segments: 3", - mesh: PrimitiveMesh.createDodecahedron(engine, 0.5, { ...keep, segments: 3 }) + detail: "edgeSegments: 3", + mesh: PrimitiveMesh.createDodecahedron(engine, 0.5, { ...keep, edgeSegments: 3 }) }, { label: "Sphere / level 2", - detail: "subdivisions: 2", - mesh: PrimitiveMesh.createSphere(engine, 0.5, { ...keep, subdivisions: 2 }) + detail: "subdivisionLevel: 2", + mesh: PrimitiveMesh.createSphere(engine, 0.5, { ...keep, subdivisionLevel: 2 }) }, { label: "Rounded cuboid / zero", @@ -104,23 +104,23 @@ class PrimitiveTopology { }, { label: "Rounded cuboid / coarse", - detail: "radius: 0.2 / segments: 1", - mesh: PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.2, { ...keep, segments: 1 }) + 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 / segments: 4", - mesh: PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.2, { ...keep, segments: 4 }) + detail: "radius: 0.2 / rounding: 4", + mesh: PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.2, { ...keep, roundingSegments: 4 }) }, { label: "Torus knot / 2, 3", - detail: "p: 2 / q: 3", - mesh: PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2, 3, { ...keep, tubularSegments: 96 }) + detail: "axis: 2 / section: 3", + mesh: PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2, 3, { ...keep, pathSegments: 96 }) }, { label: "Torus knot / 3, 2", - detail: "p: 3 / q: 2", - mesh: PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 3, 2, { ...keep, tubularSegments: 96 }) + detail: "axis: 3 / section: 2", + mesh: PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 3, 2, { ...keep, pathSegments: 96 }) }, { label: "Circle / 8 segments", @@ -130,8 +130,8 @@ class PrimitiveTopology { }, { label: "Ring / width subdivisions", - detail: "radial: 12 / width: 4", - mesh: PrimitiveMesh.createRing(engine, 0.5, 0.25, { ...keep, radialSegments: 12, widthSegments: 4 }), + detail: "ring: 12 / width: 4", + mesh: PrimitiveMesh.createRing(engine, 0.5, 0.25, { ...keep, ringSegments: 12, widthSegments: 4 }), rotation: new Vector3() }, { @@ -144,22 +144,22 @@ class PrimitiveTopology { }, { label: "Tube / path subdivisions", - detail: "tubular: 12 / radial: 6", + 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, tubularSegments: 12, radialSegments: 6 } + { ...keep, pathSegments: 12, radialSegments: 6 } ) }, { label: "Extrusion / bevel layers", - detail: "steps: 3 / bevelSegments: 3", + detail: "segments: depth 3 / bevel 3", mesh: PrimitiveMesh.createExtrusion( engine, [new Vector2(-1, -1), new Vector2(1, -1), new Vector2(1, 1), new Vector2(-1, 1)], 0.6, - { ...keep, steps: 3, bevelSize: 0.15, bevelSegments: 3 } + { ...keep, depthSegments: 3, bevelWidth: 0.15, bevelSegments: 3 } ) } ]; diff --git a/e2e/fixtures/originImage/Primitive_primitive-contours.jpg b/e2e/fixtures/originImage/Primitive_primitive-contours.jpg index 47df90481b..253e0b76f3 100644 --- a/e2e/fixtures/originImage/Primitive_primitive-contours.jpg +++ b/e2e/fixtures/originImage/Primitive_primitive-contours.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1032a48cfa2f180ccf7b48bb58c2254f6e2ef02f1012de69ed08f7c1b8dfd37c -size 694471 +oid sha256:862d9e09f5b65c22f09886ae053e157b8de4088aa50db5eb514184a8503b1646 +size 697295 diff --git a/e2e/fixtures/originImage/Primitive_primitive-materials.jpg b/e2e/fixtures/originImage/Primitive_primitive-materials.jpg index 11ef7cc0f5..ebf2172d7e 100644 --- a/e2e/fixtures/originImage/Primitive_primitive-materials.jpg +++ b/e2e/fixtures/originImage/Primitive_primitive-materials.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0be18490ece2cc50727f2d363128b8299583cca935323d19d8350ebad5f55ece -size 525209 +oid sha256:100ab05dd2b58de830e0b08c42cc6b173569d67d9d66fc1543a9cf2e67cbf18e +size 522098 diff --git a/e2e/fixtures/originImage/Primitive_primitive-sections.jpg b/e2e/fixtures/originImage/Primitive_primitive-sections.jpg index 3cd988edb3..db940f83ca 100644 --- a/e2e/fixtures/originImage/Primitive_primitive-sections.jpg +++ b/e2e/fixtures/originImage/Primitive_primitive-sections.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:5ec71ec0bdc456cb7b1c842a8c637352ebb936682bb184e80212adf0e5c8fd33 -size 627848 +oid sha256:93eb69dd3979e5a7aa49ee5f34128d4f72281ff74bbd47b1e880902b5a6397e1 +size 630715 diff --git a/e2e/fixtures/originImage/Primitive_primitive-topology.jpg b/e2e/fixtures/originImage/Primitive_primitive-topology.jpg index 5297b8cde2..33c2cc1be2 100644 --- a/e2e/fixtures/originImage/Primitive_primitive-topology.jpg +++ b/e2e/fixtures/originImage/Primitive_primitive-topology.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0fa8b7ae7d6b2cd8c6ae1e80ffefc5e2623c7fb185dfd7312191688e0c80670c -size 820215 +oid sha256:76731932960417066b5c7099d25ddf69bccec4e0405084430391318cd7b1d45e +size 825311 diff --git a/e2e/primitive-mesh.md b/e2e/primitive-mesh.md index a123737017..b3a4e52348 100644 --- a/e2e/primitive-mesh.md +++ b/e2e/primitive-mesh.md @@ -9,7 +9,7 @@ The suite contains six galleries with 90 examples. Each screenshot fixes the cam | `primitive-sections` | 15 | Circle/ring sectors, both torus ranges, cylinder cap combinations, cone caps and partial lathes | | `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, `keepData`, JSON asset loading and corner-radius clamping | +| `primitive-materials` | 12 | Material-slot order, multiple shapes, `keepCPUData`, JSON asset loading and corner-radius clamping | Run all six galleries: diff --git a/examples/src/shader-03-ui-script.ts b/examples/src/shader-03-ui-script.ts index f379438c16..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, { horizontalSegments: 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 60544b1fd1..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, { subdivisions: 5 }); + renderer.mesh = PrimitiveMesh.createSphere(engine, 0.8, { subdivisionLevel: 5 }); return entity; } diff --git a/packages/core/src/mesh/PrimitiveMesh.ts b/packages/core/src/mesh/PrimitiveMesh.ts index 3f87b0720e..c65790bb4a 100644 --- a/packages/core/src/mesh/PrimitiveMesh.ts +++ b/packages/core/src/mesh/PrimitiveMesh.ts @@ -183,17 +183,17 @@ export class PrimitiveMesh { * @returns The generated mesh */ static createSphere(engine: Engine, radius: number, options: SphereMeshOptions = {}): ModelMesh { - const { subdivisions = 3, horizontalRange, verticalRange } = options; + const { subdivisionLevel = 3, horizontalAngleRange, verticalAngleRange } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createSphereData, [ radius, - subdivisions, - horizontalRange?.x ?? 0, - horizontalRange?.y ?? 360, - verticalRange?.x ?? 0, - verticalRange?.y ?? 180 + subdivisionLevel, + horizontalAngleRange?.x ?? 0, + horizontalAngleRange?.y ?? 360, + verticalAngleRange?.x ?? 0, + verticalAngleRange?.y ?? 180 ], options ); @@ -228,16 +228,16 @@ export class PrimitiveMesh { * Create a plane in XZ facing +Y, centered at the origin. * @param engine - The engine that owns the mesh * @param width - The full size along X in local units - * @param height - The full size along Z 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, height: number, options: PlaneMeshOptions = {}): ModelMesh { - const { horizontalSegments = 1, verticalSegments = horizontalSegments } = options; + static createPlane(engine: Engine, width: number, depth: number, options: PlaneMeshOptions = {}): ModelMesh { + const { widthSegments = 1, depthSegments = widthSegments } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createPlaneData, - [width, height, horizontalSegments, verticalSegments], + [width, depth, widthSegments, depthSegments], options ); } @@ -330,16 +330,21 @@ export class PrimitiveMesh { * Create a capsule centered on Y. * @param engine - The engine that owns the mesh * @param radius - The radius of the cylinder and hemispherical ends in local units - * @param height - The straight cylindrical section height in local units; total height is `height + 2 * radius` + * @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 createCapsule(engine: Engine, radius: number, height: number, options: CapsuleMeshOptions = {}): ModelMesh { + static createCapsule( + engine: Engine, + radius: number, + cylinderHeight: number, + options: CapsuleMeshOptions = {} + ): ModelMesh { const { radialSegments = 6, capSegments = radialSegments, heightSegments = 1 } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createCapsuleData, - [radius, height, radialSegments, capSegments, heightSegments], + [radius, cylinderHeight, radialSegments, capSegments, heightSegments], options ); } @@ -353,9 +358,9 @@ export class PrimitiveMesh { * @returns The generated mesh */ static createTorus(engine: Engine, radius: number, tubeRadius: number, options: TorusMeshOptions = {}): ModelMesh { - const { tubularSegments = 30, radialSegments = 30, angleRange, tubeRange } = options; - const startAngle = angleRange?.x ?? 0; - const tubeStartAngle = tubeRange?.x ?? 0; + const { ringSegments = 30, radialSegments = 30, ringAngleRange, tubeAngleRange } = options; + const startAngle = ringAngleRange?.x ?? 0; + const tubeStartAngle = tubeAngleRange?.x ?? 0; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createTorusData, @@ -363,10 +368,10 @@ export class PrimitiveMesh { radius, tubeRadius, radialSegments, - tubularSegments, - (angleRange?.y ?? 360) - startAngle, + ringSegments, + (ringAngleRange?.y ?? 360) - startAngle, tubeStartAngle, - (tubeRange?.y ?? 360) - tubeStartAngle, + (tubeAngleRange?.y ?? 360) - tubeStartAngle, startAngle ], options @@ -405,12 +410,12 @@ export class PrimitiveMesh { innerRadius: number, options: RingMeshOptions = {} ): ModelMesh { - const { radialSegments = 32, widthSegments = 1, angleRange } = options; + const { ringSegments = 32, widthSegments = 1, angleRange } = options; const startAngle = angleRange?.x ?? 0; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createRingData, - [innerRadius, outerRadius, radialSegments, widthSegments, startAngle, (angleRange?.y ?? 360) - startAngle], + [innerRadius, outerRadius, ringSegments, widthSegments, startAngle, (angleRange?.y ?? 360) - startAngle], options ); } @@ -423,11 +428,11 @@ export class PrimitiveMesh { * @returns The generated mesh */ static createTetrahedron(engine: Engine, radius: number, options: RegularPolyhedronMeshOptions = {}): ModelMesh { - const { segments = 1 } = options; + const { edgeSegments = 1 } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createRegularPolyhedronData, - ["tetrahedron", radius, segments], + ["tetrahedron", radius, edgeSegments], options ); } @@ -440,11 +445,11 @@ export class PrimitiveMesh { * @returns The generated mesh */ static createOctahedron(engine: Engine, radius: number, options: RegularPolyhedronMeshOptions = {}): ModelMesh { - const { segments = 1 } = options; + const { edgeSegments = 1 } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createRegularPolyhedronData, - ["octahedron", radius, segments], + ["octahedron", radius, edgeSegments], options ); } @@ -457,11 +462,11 @@ export class PrimitiveMesh { * @returns The generated mesh */ static createIcosahedron(engine: Engine, radius: number, options: RegularPolyhedronMeshOptions = {}): ModelMesh { - const { segments = 1 } = options; + const { edgeSegments = 1 } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createRegularPolyhedronData, - ["icosahedron", radius, segments], + ["icosahedron", radius, edgeSegments], options ); } @@ -474,11 +479,11 @@ export class PrimitiveMesh { * @returns The generated mesh */ static createDodecahedron(engine: Engine, radius: number, options: RegularPolyhedronMeshOptions = {}): ModelMesh { - const { segments = 1 } = options; + const { edgeSegments = 1 } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createRegularPolyhedronData, - ["dodecahedron", radius, segments], + ["dodecahedron", radius, edgeSegments], options ); } @@ -515,11 +520,11 @@ export class PrimitiveMesh { radius: number, options: TubeMeshOptions = {} ): ModelMesh { - const { tubularSegments = 64, radialSegments = 8, closed = false } = options; + const { pathSegments = 64, radialSegments = 8, closedPath = false } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createTubeData, - [path, radius, tubularSegments, radialSegments, closed], + [path, radius, pathSegments, radialSegments, closedPath], options ); } @@ -548,7 +553,7 @@ export class PrimitiveMesh { * Extrude polygons along +Z or a spatial path. * @remarks * A path selects path extrusion and ignores bevel settings. - * A numeric depth extrudes along +Z and ignores `closed`. + * A numeric depth extrudes along +Z and ignores `closedPath`. * @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 depthOrPath - The total depth along +Z, including bevels, or the path points with at least two distinct points @@ -562,11 +567,12 @@ export class PrimitiveMesh { options: LinearExtrusionMeshOptions | PathExtrusionMeshOptions = {} ): ModelMesh { const { - steps = 1, - closed = false, - bevelSize = 0, - bevelThickness = bevelSize, - bevelOffset = 0, + depthSegments = 1, + pathSegments = 1, + closedPath = false, + bevelWidth = 0, + bevelDepth = bevelWidth, + contourOffset = 0, bevelSegments = 3 }: LinearExtrusionMeshOptions & PathExtrusionMeshOptions = options; const path = typeof depthOrPath === "number" ? undefined : depthOrPath; @@ -577,12 +583,12 @@ export class PrimitiveMesh { [ PrimitiveMesh._polygons(shapes), depth, - steps, + path ? pathSegments : depthSegments, path, - path ? closed : false, - bevelThickness, - bevelSize, - bevelOffset, + path ? closedPath : false, + bevelDepth, + bevelWidth, + contourOffset, bevelSegments ], options @@ -590,12 +596,12 @@ export class PrimitiveMesh { } /** - * Create a closed torus knot. At least one of `p` and `q` must be nonzero. + * Create a closed torus knot. At least one of `axisTurns` and `crossSectionTurns` must be nonzero. * @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 p - The signed integer revolution count around the torus axis; negative values reverse the winding - * @param q - The signed integer revolution count through the torus hole; negative values reverse the winding + * @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 */ @@ -603,15 +609,15 @@ export class PrimitiveMesh { engine: Engine, radius: number, tubeRadius: number, - p: number, - q: number, + axisTurns: number, + crossSectionTurns: number, options: TorusKnotMeshOptions = {} ): ModelMesh { - const { tubularSegments = 64, radialSegments = 8 } = options; + const { pathSegments = 64, radialSegments = 8 } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createTorusKnotData, - [radius, tubeRadius, tubularSegments, radialSegments, p, q], + [radius, tubeRadius, pathSegments, radialSegments, axisTurns, crossSectionTurns], options ); } @@ -636,27 +642,27 @@ export class PrimitiveMesh { cornerRadius: number, options: RoundedCuboidMeshOptions = {} ): ModelMesh { - const { segments = 2 } = options; + const { roundingSegments = 2 } = options; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createRoundedCuboidData, - [width, height, depth, cornerRadius, segments], + [width, height, depth, cornerRadius, roundingSegments], options ); } private static _createPlaneData( width: number, - height: number, - horizontalSegments: number, - verticalSegments: number + depth: number, + widthSegments: number, + depthSegments: number ): PrimitiveMeshBuilder { - const columns = PrimitiveMesh._getSegmentCount(horizontalSegments); - const rows = PrimitiveMesh._getSegmentCount(verticalSegments); + 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) * height, 0, 1, 0, x / columns, y / rows); + 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++) { @@ -667,7 +673,7 @@ export class PrimitiveMesh { data.addTriangle(a + 1, c, c + 1); } } - data.boundsExtent = new Vector3(width / 2, 0, height / 2); + data.boundsExtent = new Vector3(width / 2, 0, depth / 2); return data; } @@ -893,7 +899,7 @@ export class PrimitiveMesh { private static _createCapsuleData( radius: number, - height: number, + cylinderHeight: number, radialSegments: number, capSegments: number, heightSegments: number @@ -904,7 +910,7 @@ export class PrimitiveMesh { const rows = caps * 2 + vertical; const circle = PrimitiveMesh._createArcSamples(radial, Math.PI); const capLength = (Math.PI * radius) / 2; - const totalLength = capLength * 2 + height; + 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; @@ -915,19 +921,19 @@ export class PrimitiveMesh { const angle = ((y / caps) * Math.PI) / 2; ringRadius = radius * Math.sin(angle); ny = -Math.cos(angle); - py = -height / 2 + radius * ny; + py = -cylinderHeight / 2 + radius * ny; distance = (y / caps) * capLength; } else if (y <= caps + vertical) { ringRadius = radius; ny = 0; - py = -height / 2 + ((y - caps) / vertical) * height; - distance = capLength + ((y - caps) / vertical) * height; + 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 = height / 2 + radius * ny; - distance = capLength + height + ((y - caps - vertical) / caps) * capLength; + 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 @@ -959,7 +965,7 @@ export class PrimitiveMesh { } } } - data.boundsExtent = new Vector3(radius, height / 2 + radius, radius); + data.boundsExtent = new Vector3(radius, cylinderHeight / 2 + radius, radius); return data; } @@ -967,14 +973,14 @@ export class PrimitiveMesh { radius: number, tubeRadius: number, radialSegments: number, - tubularSegments: number, + ringSegments: number, arcDegrees: number, tubeStartAngleDegrees: number, tubeArcDegrees: number, startAngleDegrees: number ): PrimitiveMeshBuilder { const radial = PrimitiveMesh._getSegmentCount(radialSegments, 3); - const tubular = PrimitiveMesh._getSegmentCount(tubularSegments, 1); + const tubular = PrimitiveMesh._getSegmentCount(ringSegments, 1); const arc = MathUtil.degreeToRadian(arcDegrees); const tubeStart = MathUtil.degreeToRadian(tubeStartAngleDegrees); const tubeArc = MathUtil.degreeToRadian(tubeArcDegrees); @@ -1039,12 +1045,12 @@ export class PrimitiveMesh { private static _createRingData( innerRadius: number, outerRadius: number, - radialSegments: number, + ringSegments: number, widthSegments: number, startAngle: number, arcDegrees: number ): PrimitiveMeshBuilder { - const radial = PrimitiveMesh._getSegmentCount(radialSegments, 3); + const radial = PrimitiveMesh._getSegmentCount(ringSegments, 3); const width = PrimitiveMesh._getSegmentCount(widthSegments); const start = MathUtil.degreeToRadian(startAngle); const arc = MathUtil.degreeToRadian(arcDegrees); @@ -1083,13 +1089,13 @@ export class PrimitiveMesh { height: number, depth: number, cornerRadius: number, - edgeSegments: 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(edgeSegments); + 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); @@ -1188,25 +1194,25 @@ export class PrimitiveMesh { private static _createTubeData( path: readonly Vector3[], radius: number, - tubularSegments: number, + pathSegments: number, radialSegments: number, - closed: boolean + closedPath: boolean ): PrimitiveMeshBuilder { const tangents: Vector3[] = []; - const points = MeshPathUtils.sample(path, PrimitiveMesh._getSegmentCount(tubularSegments), closed, tangents); - return PrimitiveMesh._createTubeSurfaceData(points, radius, radialSegments, closed, tangents); + 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, - closed: boolean, + closedPath: boolean, fallbackTangents?: readonly Vector3[] ): PrimitiveMeshBuilder { const count = points.length - 1; const radial = PrimitiveMesh._getSegmentCount(radialSegments, 3); - const frames = MeshPathUtils.computeFrames(points, closed, fallbackTangents); + 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++) { @@ -1245,21 +1251,21 @@ export class PrimitiveMesh { private static _createTorusKnotData( radius: number, tubeRadius: number, - tubularSegments: number, + pathSegments: number, radialSegments: number, - p: number, - q: number + axisTurns: number, + crossSectionTurns: number ): PrimitiveMeshBuilder { - if (p === 0 && q === 0) { + if (axisTurns === 0 && crossSectionTurns === 0) { throw new Error("A torus knot needs at least one nonzero winding."); } - const count = PrimitiveMesh._getSegmentCount(tubularSegments); + 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 = p * angle; - const v = q * angle; + const u = axisTurns * angle; + const v = crossSectionTurns * angle; points.push( new Vector3( (radius * (2 + Math.cos(v)) * Math.cos(u)) / 2, @@ -1267,13 +1273,13 @@ export class PrimitiveMesh { (radius * Math.sin(v)) / 2 ) ); - const radialDerivative = -q * Math.sin(v); - const angularDerivative = p * (2 + Math.cos(v)); + 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), - q * Math.cos(v) + crossSectionTurns * Math.cos(v) ) ); } @@ -1457,22 +1463,22 @@ export class PrimitiveMesh { depth: number, stepCount: number, pathInput: readonly Vector3[] | undefined, - closed: boolean, - bevelThickness: number, - bevelSize: number, - bevelOffset: number, + closedPath: boolean, + bevelDepth: number, + bevelWidth: number, + contourOffset: number, bevelSegmentCount: number ): PrimitiveMeshBuilder { const data = new PrimitiveMeshBuilder(); - const steps = PrimitiveMesh._getSegmentCount(stepCount, closed ? 3 : 1); + const steps = PrimitiveMesh._getSegmentCount(stepCount, closedPath ? 3 : 1); const tangents: Vector3[] = []; - const path = pathInput ? MeshPathUtils.sample(pathInput, steps, closed, tangents) : undefined; - const frames = path ? MeshPathUtils.computeFrames(path, closed, tangents) : undefined; - const bevelEnabled = !path && bevelSize > 0; + 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(bevelThickness, depth / 2) : 0; - const size = bevelEnabled ? bevelSize : 0; - const offset = path ? 0 : bevelOffset; + 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(); @@ -1519,7 +1525,7 @@ export class PrimitiveMesh { ) ); }); - if (!closed) { + if (!closedPath) { const capStart = data.indexCount; cap(0, false); cap(layers.length - 1, true); @@ -1588,7 +1594,7 @@ export class PrimitiveMesh { private static _createSphereData( radius: number, - subdivisions: number, + subdivisionLevel: number, horizontalStart: number, horizontalEnd: number, verticalStart: number, @@ -1598,7 +1604,7 @@ export class PrimitiveMesh { verticalStart = Math.max(0, verticalStart); verticalEnd = Math.min(180, verticalEnd); if (horizontalArc < 360 || verticalStart > 0 || verticalEnd < 180) { - const surface = PrimitiveMesh._createSphereSurfaceData(1, subdivisions); + const surface = PrimitiveMesh._createSphereSurfaceData(1, subdivisionLevel); return PrimitiveMesh._createSphereSectionData( surface, radius, @@ -1609,7 +1615,7 @@ export class PrimitiveMesh { ); } - const data = PrimitiveMesh._createSphereSurfaceData(radius, subdivisions); + const data = PrimitiveMesh._createSphereSurfaceData(radius, subdivisionLevel); if (horizontalStart !== 0) { const angle = MathUtil.degreeToRadian(horizontalStart); const cos = Math.cos(angle); @@ -1804,9 +1810,9 @@ export class PrimitiveMesh { return resultCount; } - private static _createSphereSurfaceData(radius: number, subdivisions: number): PrimitiveMeshBuilder { + private static _createSphereSurfaceData(radius: number, subdivisionLevel: number): PrimitiveMeshBuilder { // Level 7 exceeds the 16-bit vertex index range - const level = MathUtil.clamp(Math.floor(subdivisions), 1, 6); + const level = MathUtil.clamp(Math.floor(subdivisionLevel), 1, 6); const { positions, quads: cells } = SubdivisionUtils.subdivideQuads( PrimitiveMesh._sphereSeedPositions, @@ -1937,7 +1943,7 @@ export class PrimitiveMesh { engine: Engine, generate: (...args: T) => PrimitiveMeshBuilder, args: T, - { keepData = false, separateMaterials = false }: { keepData?: boolean; separateMaterials?: boolean } + { keepCPUData = false, separateMaterialSlots = false }: { keepCPUData?: boolean; separateMaterialSlots?: boolean } ): ModelMesh { for (let i = 0; i < args.length; i++) { args[i] = PrimitiveMesh._copy(args[i]); @@ -1955,14 +1961,20 @@ export class PrimitiveMesh { 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, keepData); + const vertexBuffer = new Buffer( + mesh.engine, + BufferBindFlag.VertexBuffer, + vertices, + BufferUsage.Static, + keepCPUData + ); mesh.setVertexBufferBinding(vertexBuffer, 32, 0); - mesh._initializeTangents(MeshTangentUtils.calculateTangentsFromBuffer(vertices, indices), !keepData); + mesh._initializeTangents(MeshTangentUtils.calculateTangentsFromBuffer(vertices, indices), !keepCPUData); mesh.setIndices(indices); PrimitiveMesh._setBounds(mesh, data); - mesh.uploadData(!keepData); + mesh.uploadData(!keepCPUData); mesh.clearSubMesh(); - if (separateMaterials && data.groups.length) { + if (separateMaterialSlots && data.groups.length) { for (const group of data.groups) { mesh.addSubMesh(group.start, group.count); } diff --git a/packages/core/src/mesh/PrimitiveMeshOptions.ts b/packages/core/src/mesh/PrimitiveMeshOptions.ts index 4350c4e34d..f451884275 100644 --- a/packages/core/src/mesh/PrimitiveMeshOptions.ts +++ b/packages/core/src/mesh/PrimitiveMeshOptions.ts @@ -9,7 +9,7 @@ export interface PrimitiveMeshOptions { * Whether to retain readable CPU copies of vertex attributes and indices after upload. * @defaultValue `false` */ - keepData?: boolean; + keepCPUData?: boolean; } /** @@ -37,20 +37,20 @@ export interface SphereMeshOptions extends PrimitiveMeshOptions { * The subdivision level, rounded down and clamped to 1 through 6. * @defaultValue `3` */ - subdivisions?: number; + 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)` */ - horizontalRange?: Vector2; + 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)` */ - verticalRange?: Vector2; + verticalAngleRange?: Vector2; } /** @@ -76,7 +76,7 @@ export interface CuboidMeshOptions extends PrimitiveMeshOptions { * Whether to create one sub-mesh per face, ordered +Y, -Y, -X, +X, +Z, -Z. * @defaultValue `false` */ - separateMaterials?: boolean; + separateMaterialSlots?: boolean; } /** @@ -87,12 +87,12 @@ export interface PlaneMeshOptions extends PrimitiveMeshOptions { * The number of subdivisions along X, rounded down with a minimum of 1. * @defaultValue `1` */ - horizontalSegments?: number; + widthSegments?: number; /** * The number of subdivisions along Z, rounded down with a minimum of 1. - * @defaultValue The value of `horizontalSegments`. + * @defaultValue The value of `widthSegments`. */ - verticalSegments?: number; + depthSegments?: number; } /** @@ -124,7 +124,7 @@ export interface CylinderMeshOptions extends PrimitiveMeshOptions { * Omitted or zero-radius caps do not occupy slots. * @defaultValue `false` */ - separateMaterials?: boolean; + separateMaterialSlots?: boolean; } /** @@ -156,7 +156,7 @@ export interface TruncatedConeMeshOptions extends PrimitiveMeshOptions { * Omitted or zero-radius caps do not occupy slots. * @defaultValue `false` */ - separateMaterials?: boolean; + separateMaterialSlots?: boolean; } /** @@ -188,7 +188,7 @@ export interface ConeMeshOptions extends PrimitiveMeshOptions { * An omitted or zero-radius bottom cap does not occupy a slot. * @defaultValue `false` */ - separateMaterials?: boolean; + separateMaterialSlots?: boolean; } /** @@ -220,7 +220,7 @@ export interface TorusMeshOptions extends PrimitiveMeshOptions { * The number of segments around the torus, rounded down with a minimum of 1. * @defaultValue `30` */ - tubularSegments?: number; + ringSegments?: number; /** * The number of segments around the tube cross-section, rounded down with a minimum of 3. * @defaultValue `30` @@ -231,13 +231,13 @@ export interface TorusMeshOptions extends PrimitiveMeshOptions { * Cut ends remain open. * @defaultValue `new Vector2(0, 360)` */ - angleRange?: Vector2; + 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)` */ - tubeRange?: Vector2; + tubeAngleRange?: Vector2; } /** @@ -264,7 +264,7 @@ export interface RingMeshOptions extends PrimitiveMeshOptions { * The number of segments along the arc, rounded down with a minimum of 3. * @defaultValue `32` */ - radialSegments?: number; + ringSegments?: number; /** * The number of subdivisions between the inner and outer edges, rounded down with a minimum of 1. * @defaultValue `1` @@ -286,7 +286,7 @@ export interface RegularPolyhedronMeshOptions extends PrimitiveMeshOptions { * Values above 1 project the new vertices onto the sphere and use smooth normals. * @defaultValue `1` */ - segments?: number; + edgeSegments?: number; } /** @@ -314,7 +314,7 @@ export interface TubeMeshOptions extends PrimitiveMeshOptions { * The number of segments along the resampled path, rounded down with a minimum of 1. * @defaultValue `64` */ - tubularSegments?: number; + pathSegments?: number; /** * The number of segments around the cross-section, rounded down with a minimum of 3. * @defaultValue `8` @@ -325,7 +325,7 @@ export interface TubeMeshOptions extends PrimitiveMeshOptions { * Open tubes have no end caps. * @defaultValue `false` */ - closed?: boolean; + closedPath?: boolean; } /** @@ -336,7 +336,7 @@ 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` */ - separateMaterials?: boolean; + separateMaterialSlots?: boolean; } /** @@ -347,23 +347,23 @@ export interface LinearExtrusionMeshOptions extends PrimitiveMeshOptions { * The number of subdivisions along the extrusion, rounded down with a minimum of 1. * @defaultValue `1` */ - steps?: number; + depthSegments?: number; /** * The inset of each end cap relative to the side wall in local units. Zero disables bevels. * @defaultValue `0` */ - bevelSize?: number; + bevelWidth?: number; /** - * The bevel depth at each end in local units, limited to half of `depth`. - * @defaultValue The value of `bevelSize`. + * The bevel depth at each end in local units, limited to half the extrusion depth. + * @defaultValue The value of `bevelWidth`. */ - bevelThickness?: number; + 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` */ - bevelOffset?: number; + contourOffset?: number; /** * The number of subdivisions per bevel, rounded down with a minimum of 1. * @defaultValue `3` @@ -374,7 +374,7 @@ export interface LinearExtrusionMeshOptions extends PrimitiveMeshOptions { * Both end caps share one slot; outer walls, hole walls and bevels share the next. * @defaultValue `false` */ - separateMaterials?: boolean; + separateMaterialSlots?: boolean; } /** @@ -384,21 +384,21 @@ export interface LinearExtrusionMeshOptions extends PrimitiveMeshOptions { export interface PathExtrusionMeshOptions 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 `closed` is true. + * @defaultValue `1`, increased to `3` when `closedPath` is true. */ - steps?: number; + 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` */ - closed?: boolean; + 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` */ - separateMaterials?: boolean; + separateMaterialSlots?: boolean; } /** @@ -409,7 +409,7 @@ export interface TorusKnotMeshOptions extends PrimitiveMeshOptions { * The number of segments along the knot, rounded down with a minimum of 1. * @defaultValue `64` */ - tubularSegments?: number; + pathSegments?: number; /** * The number of segments around the tube cross-section, rounded down with a minimum of 3. * @defaultValue `8` @@ -423,13 +423,13 @@ export interface TorusKnotMeshOptions extends PrimitiveMeshOptions { export interface RoundedCuboidMeshOptions extends PrimitiveMeshOptions { /** * The rounding subdivision count, rounded down with a minimum of 1. - * When `cornerRadius` is positive, each face uses `2 * segments + 1` subdivisions per axis. + * When `cornerRadius` is positive, each face uses `2 * roundingSegments + 1` subdivisions per axis. * @defaultValue `2` */ - segments?: number; + roundingSegments?: number; /** * Whether to create one sub-mesh per face, ordered +Y, -Y, -X, +X, +Z, -Z. * @defaultValue `false` */ - separateMaterials?: boolean; + separateMaterialSlots?: boolean; } diff --git a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md index aa612a61c5..f923af5580 100644 --- a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md +++ b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md @@ -8,17 +8,17 @@ Dimensions are required factory arguments, expressed in local units. The table a | --------- | ----------------------------------------------------------- | ---------------------------- | | Cuboid | `width`, `height`, `depth` | centered at the origin | | Sphere | diameter `2 * radius` | centered at the origin | -| Plane | X size `width`, Z size `height` | lies in XZ and faces +Y | +| Plane | X size `width`, Z size `depth` | lies in XZ and faces +Y | | Cylinder | radius `radius`, Y size `height` | centered on Y | | Cone | base radius `radius`, Y size `height` | centered on Y, tip toward +Y | -| Capsule | radius `radius`, total Y size `height + 2 * radius` | centered on Y | +| Capsule | radius `radius`, total Y size `cylinderHeight + 2 * radius` | centered on Y | | Torus | outer radius `radius + tubeRadius`, Z size `2 * tubeRadius` | lies in XY around the Z axis | ## Placement consequences - A centered primitive rests on a horizontal surface when its center is raised by its scaled half-height. - A 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. +- Capsule `cylinderHeight` 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. ## Visual and collision geometry @@ -51,30 +51,30 @@ export function createTriangle(engine: Engine, renderer: MeshRenderer): void { Each factory takes required shape inputs followed by one optional named settings object. Dimensions, radii, contours and paths have no API defaults. Subdivision counts, angular ranges and mesh settings remain optional. Every shape has a public options type, such as `SphereMeshOptions`; the four regular polyhedra share `RegularPolyhedronMeshOptions`. Query the factory and its options type for argument meanings, units and option defaults. -For example, `createSphere(engine, 1, { subdivisions: 3 })` specifies the radius and subdivision level. `createCuboid(engine, 2, 3, 4)` requires all three dimensions. `createPlane(engine, 2, 3)` specifies its X and Z sizes. Later plane/cuboid subdivision counts use the first direction by default. +For example, `createSphere(engine, 1, { subdivisionLevel: 3 })` specifies the radius and subdivision level. `createCuboid(engine, 2, 3, 4)` requires all three dimensions. `createPlane(engine, 2, 3)` specifies its X and Z sizes. Later plane/cuboid subdivision counts use the first direction by default. `createCylinder(engine, radius, height)` creates equal end radii. Use `createTruncatedCone(engine, topRadius, bottomRadius, height)` for different radii. Tubes take a required `Vector3` path and radius followed by `TubeMeshOptions`; lathe profiles take a required `Vector2` array followed by `LatheMeshOptions`. -Torus-knot `p` and `q` are required signed integer revolution counts, independent of mesh subdivisions. Negative values reverse the corresponding winding direction; zero keeps that angle fixed. +Torus-knot `axisTurns` counts revolutions around the central axis; `crossSectionTurns` counts revolutions around the torus cross-section. Both are required signed integers, independent of mesh subdivisions. Negative values reverse the corresponding winding direction; zero keeps that angle fixed. -Angles use degrees. Ranges use `Vector2`, with `x` as the start angle and `y` as the end angle, such as `new Vector2(30, 180)`. Spherical sections use `horizontalRange` and `verticalRange` in their options. Cylinder and frustum `caps` use the exported `PrimitiveMeshCapMode` enum: `Both` (default), `Top`, `Bottom`, `None`. Top faces +Y and bottom faces -Y; angular cut boundaries remain open. Cones use a boolean `cap`. Plane is in XZ facing +Y; circles, rings and polygons are in XY facing +Z. Capsule height excludes its hemispheres. +Angles use degrees. Ranges use `Vector2`, with `x` as the start angle and `y` as the end angle, such as `new Vector2(30, 180)`. Spherical sections use `horizontalAngleRange` and `verticalAngleRange` in their options. Cylinder and frustum `caps` use the exported `PrimitiveMeshCapMode` enum: `Both` (default), `Top`, `Bottom`, `None`. Top faces +Y and bottom faces -Y; angular cut boundaries remain open. Cones use a boolean `cap`. Plane is in XZ facing +Y; circles, rings and polygons are in XY facing +Z. Capsule `cylinderHeight` excludes its hemispheres. -`createSphere(engine, radius, { subdivisions, horizontalRange, verticalRange })` projects a subdivided cube onto a sphere. The subdivision level defaults to 3 and is clamped to 1 through 6. It accepts `horizontalRange` and `verticalRange`. These clip the subdivided surface and leave open boundaries. Horizontal angles start at -X towards +Z, and vertical angles start at +Y. Continuous horizontal intervals such as `new Vector2(350, 370)` cross the seam. Complete spheres and sections use the same subdivision level. +`createSphere(engine, radius, { subdivisionLevel, horizontalAngleRange, verticalAngleRange })` projects a subdivided cube onto a sphere. The subdivision level defaults to 3 and is clamped to 1 through 6. It accepts `horizontalAngleRange` and `verticalAngleRange`. These clip the subdivided surface and leave open boundaries. Horizontal angles start at -X towards +Z, and vertical angles start at +Y. Continuous horizontal intervals such as `new Vector2(350, 370)` cross the seam. Complete spheres and sections use the same subdivision level. -Additional generators include circle, ring, four regular polyhedra, lathe, tube, polygon, extrusion, torus knot and rounded cuboid. Angle ranges belong to options. Rings require the outer radius first, followed by the inner radius. Contours and lathe profiles use `Vector2` arrays; paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points outside the mesh API. A simple polygon is a point array; holes use `{ points, holes }`. Extrusion takes a required numeric depth or `Vector3` path as its third argument, followed by `LinearExtrusionMeshOptions` or `PathExtrusionMeshOptions`. Each interface declares its mode's optional settings. A path selects path extrusion and ignores bevel settings; a numeric depth extrudes along +Z and ignores `closed`. Straight extrusion defaults to no bevel; a positive `bevelSize` enables it, with `bevelThickness` defaulting to the same value. Path extrusion has no bevels. +Additional generators include circle, ring, four regular polyhedra, lathe, tube, polygon, extrusion, torus knot and rounded cuboid. Angle ranges belong to options. Rings require the outer radius first, followed by the inner radius. Contours and lathe profiles use `Vector2` arrays; paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points outside the mesh API. A simple polygon is a point array; holes use `{ points, holes }`. Extrusion takes a required numeric depth or `Vector3` path as its third argument, followed by `LinearExtrusionMeshOptions` or `PathExtrusionMeshOptions`. Linear extrusion uses `depthSegments`; path extrusion uses `pathSegments`. Each interface declares its mode's optional settings. A path selects path extrusion and ignores bevel settings; a numeric depth extrudes along +Z and ignores `closedPath`. Straight extrusion defaults to no bevel; a positive `bevelWidth` enables it, with `bevelDepth` defaulting to the same value. Path extrusion has no bevels. -For straight extrusion, `bevelOffset` shifts the side-wall outline and defaults to `0`. Positive values expand the solid and contract holes; negative values do the reverse. The offset also applies when `bevelSize` is `0`. Bevels are cut into the shifted outline and included in the total `depth`. +For straight extrusion, `contourOffset` shifts the side-wall outline and defaults to `0`. Positive values expand the solid and contract holes; negative values do the reverse. The offset also applies when `bevelWidth` is `0`. Bevels are cut into the shifted outline and included in the total `depth`. -For tubes and path extrusions, `closed` defaults to `false`. When enabled, the path ends join with matching cross-sections, and the closing point need not be repeated. Closed extrusions use at least three steps and have no end caps. Open extrusions have both end caps; tubes have no end caps in either mode. +For tubes and path extrusions, `closedPath` defaults to `false`. When enabled, the path ends join with matching cross-sections, and the closing point need not be repeated. Closed extrusions use at least three path segments and have no end caps. Open extrusions have both end caps; tubes have no end caps in either mode. -Mesh settings share the same options object. `keepData` retains readable CPU attributes and defaults to false. `separateMaterials` defaults to false and is only available for cuboids, cylinders, truncated cones, cones, polygons, extrusions and rounded cuboids. With it enabled, cuboid slots follow +Y, -Y, -X, +X, +Z, -Z; cylinders use side, top, bottom; cones use side, bottom. Disabled or zero-radius caps do not reserve slots. Polygon slots follow shape order, with holes sharing the outer contour's slot. Each open extrusion shape contributes two consecutive slots: both caps, then all walls and bevels. Closed path extrusions contribute one wall slot per shape. Rebuilding a mesh with different parts requires matching the material array to its new slot order. Input values are captured at creation for deterministic device restoration. +Mesh settings share the same options object. `keepCPUData` retains readable CPU attributes and defaults to false. `separateMaterialSlots` defaults to false and is only available for cuboids, cylinders, truncated cones, cones, polygons, extrusions and rounded cuboids. With it enabled, cuboid slots follow +Y, -Y, -X, +X, +Z, -Z; cylinders use side, top, bottom; cones use side, bottom. Disabled or zero-radius caps do not reserve slots. Polygon slots follow shape order, with holes sharing the outer contour's slot. Each open extrusion shape contributes two consecutive slots: both caps, then all walls and bevels. Closed path extrusions contribute one wall slot per shape. Rebuilding a mesh with different parts requires matching the material array to its new slot order. Input values are captured at creation for deterministic device restoration. ## Serializable primitive assets `PrimitiveMeshAsset` is exported from `@galacean/engine` and `@galacean/engine-loader` and covers every `PrimitiveMesh.createX` method. Each asset `type` uses the matching lower-camel name: `sphere`, `cuboid`, `plane`, `cylinder`, `truncatedCone`, `cone`, `capsule`, `torus`, `circle`, `ring`, `tetrahedron`, `octahedron`, `icosahedron`, `dodecahedron`, `lathe`, `tube`, `polygon`, `extrusion`, `torusKnot`, `roundedCuboid`. -JSON keeps the type prefix for required geometry inputs and the optional settings object: `{ type: "sphere", sphereRadius: 1, sphereOptions: { subdivisions: 3, keepData: true } }`. Each `Options` uses the factory's named configuration fields and omitted defaults. Angular ranges store `Vector2` components as `{ x, y }`, for example `{ type: "circle", circleRadius: 1, circleOptions: { angleRange: { x: 30, y: 180 } } }`. `sphere` uses the subdivided-cube algorithm; `sphereOptions.subdivisions` sets its subdivision level. `cylinderRadius` controls both end radii; unequal radii use `truncatedConeTopRadius` and `truncatedConeBottomRadius`. +JSON keeps the type prefix for required geometry inputs and the optional settings object: `{ type: "sphere", sphereRadius: 1, sphereOptions: { subdivisionLevel: 3, keepCPUData: true } }`. Each `Options` uses the factory's named configuration fields and omitted defaults. Angular ranges store `Vector2` components as `{ x, y }`, for example `{ type: "circle", circleRadius: 1, circleOptions: { angleRange: { x: 30, y: 180 } } }`. `sphere` uses the subdivided-cube algorithm; `sphereOptions.subdivisionLevel` sets its subdivision level. `cylinderRadius` controls both end radii; unequal radii use `truncatedConeTopRadius` and `truncatedConeBottomRadius`. TypeScript assets use `PrimitiveMeshCapMode` for `caps`; JSON stores its string values `"both"`, `"top"`, `"bottom"`, `"none"`. -Serialized profiles and contours use `{ x, y }`; paths use `{ x, y, z }`. `polygonShapes` and `extrusionShapes` are arrays of `{ points, holes? }`. Straight extrusion requires `extrusionDepth`; path extrusion requires `extrusionPath` and ignores bevel settings. Set `extrusionOptions.closed` to `true` for a closed path without end caps. Editor previews and saved assets must select the same factory and parameters. +Serialized profiles and contours use `{ x, y }`; paths use `{ x, y, z }`. `polygonShapes` and `extrusionShapes` are arrays of `{ points, holes? }`. Straight extrusion requires `extrusionDepth`; path extrusion requires `extrusionPath` and ignores bevel settings. Set `extrusionOptions.closedPath` to `true` for a closed path without end caps. Editor previews and saved assets must select the same factory and parameters. diff --git a/packages/loader/src/PrimitiveMeshAsset.ts b/packages/loader/src/PrimitiveMeshAsset.ts index d2ee4af51f..c63b65e7d8 100644 --- a/packages/loader/src/PrimitiveMeshAsset.ts +++ b/packages/loader/src/PrimitiveMeshAsset.ts @@ -70,7 +70,7 @@ export type PrimitiveMeshAsset = /** * The full size along Z in local units. */ - planeHeight: number; + planeDepth: number; planeOptions?: PlaneMeshOptions; } | { @@ -120,9 +120,9 @@ export type PrimitiveMeshAsset = */ capsuleRadius: number; /** - * The straight cylindrical section height in local units; total height is `capsuleHeight + 2 * capsuleRadius`. + * The straight cylindrical section height in local units; total height is `capsuleCylinderHeight + 2 * capsuleRadius`. */ - capsuleHeight: number; + capsuleCylinderHeight: number; capsuleOptions?: CapsuleMeshOptions; } | { @@ -239,11 +239,11 @@ export type PrimitiveMeshAsset = /** * The signed integer revolution count around the torus axis. */ - torusKnotP: number; + torusKnotAxisTurns: number; /** - * The signed integer revolution count through the torus hole. + * The signed integer revolution count around the torus cross-section. */ - torusKnotQ: number; + torusKnotCrossSectionTurns: number; torusKnotOptions?: TorusKnotMeshOptions; } | { diff --git a/packages/loader/src/PrimitiveMeshLoader.ts b/packages/loader/src/PrimitiveMeshLoader.ts index 2285751e1f..4bd65c4398 100644 --- a/packages/loader/src/PrimitiveMeshLoader.ts +++ b/packages/loader/src/PrimitiveMeshLoader.ts @@ -35,7 +35,7 @@ class PrimitiveMeshLoader extends Loader { data.cuboidOptions ); case "plane": - return PrimitiveMesh.createPlane(engine, data.planeWidth, data.planeHeight, data.planeOptions); + return PrimitiveMesh.createPlane(engine, data.planeWidth, data.planeDepth, data.planeOptions); case "cylinder": return PrimitiveMesh.createCylinder( engine, @@ -59,7 +59,7 @@ class PrimitiveMeshLoader extends Loader { this._parseRangeOptions(data.coneOptions) ); case "capsule": - return PrimitiveMesh.createCapsule(engine, data.capsuleRadius, data.capsuleHeight, data.capsuleOptions); + return PrimitiveMesh.createCapsule(engine, data.capsuleRadius, data.capsuleCylinderHeight, data.capsuleOptions); case "torus": return PrimitiveMesh.createTorus( engine, @@ -106,8 +106,8 @@ class PrimitiveMeshLoader extends Loader { engine, data.torusKnotRadius, data.torusKnotTubeRadius, - data.torusKnotP, - data.torusKnotQ, + data.torusKnotAxisTurns, + data.torusKnotCrossSectionTurns, data.torusKnotOptions ); case "roundedCuboid": diff --git a/tests/package-consumer/fixtures/PrimitiveMeshApi.ts b/tests/package-consumer/fixtures/PrimitiveMeshApi.ts index 9cef9d0f79..437093c6ba 100644 --- a/tests/package-consumer/fixtures/PrimitiveMeshApi.ts +++ b/tests/package-consumer/fixtures/PrimitiveMeshApi.ts @@ -36,89 +36,94 @@ 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 = { keepData: true } satisfies PrimitiveMeshOptions; +const commonOptions = { keepCPUData: true } satisfies PrimitiveMeshOptions; const sphereOptions = { - subdivisions: 4, - horizontalRange: new Vector2(350, 370), - verticalRange: new Vector2(30, 150), - keepData: true + subdivisionLevel: 4, + horizontalAngleRange: new Vector2(350, 370), + verticalAngleRange: new Vector2(30, 150), + keepCPUData: true } satisfies SphereMeshOptions; const cuboidOptions = { widthSegments: 2, heightSegments: 3, depthSegments: 4, - separateMaterials: true, - keepData: true + separateMaterialSlots: true, + keepCPUData: true } satisfies CuboidMeshOptions; -const planeOptions = { horizontalSegments: 4, verticalSegments: 2, keepData: true } satisfies PlaneMeshOptions; +const planeOptions = { widthSegments: 4, depthSegments: 2, keepCPUData: true } satisfies PlaneMeshOptions; const cylinderOptions = { radialSegments: 32, heightSegments: 4, caps: PrimitiveMeshCapMode.Bottom, angleRange: new Vector2(0, 270), - separateMaterials: true, - keepData: true + separateMaterialSlots: true, + keepCPUData: true } satisfies CylinderMeshOptions; const truncatedConeOptions = { radialSegments: 32, heightSegments: 4, caps: PrimitiveMeshCapMode.None, angleRange: new Vector2(0, 270), - separateMaterials: true, - keepData: true + separateMaterialSlots: true, + keepCPUData: true } satisfies TruncatedConeMeshOptions; const coneOptions = { radialSegments: 32, heightSegments: 4, cap: false, angleRange: new Vector2(0, 270), - separateMaterials: true, - keepData: true + separateMaterialSlots: true, + keepCPUData: true } satisfies ConeMeshOptions; const capsuleOptions = { radialSegments: 12, capSegments: 6, heightSegments: 3, - keepData: true + keepCPUData: true } satisfies CapsuleMeshOptions; const torusOptions = { - tubularSegments: 64, + ringSegments: 64, radialSegments: 16, - angleRange: new Vector2(0, 270), - tubeRange: new Vector2(0, 180), - keepData: true + ringAngleRange: new Vector2(0, 270), + tubeAngleRange: new Vector2(0, 180), + keepCPUData: true } satisfies TorusMeshOptions; -const circleOptions = { segments: 32, angleRange: new Vector2(0, 180), keepData: true } satisfies CircleMeshOptions; +const circleOptions = { segments: 32, angleRange: new Vector2(0, 180), keepCPUData: true } satisfies CircleMeshOptions; const ringOptions = { - radialSegments: 32, + ringSegments: 32, widthSegments: 4, angleRange: new Vector2(0, 270), - keepData: true + keepCPUData: true } satisfies RingMeshOptions; -const regularPolyhedronOptions = { segments: 2, keepData: true } satisfies RegularPolyhedronMeshOptions; -const latheOptions = { segments: 32, angleRange: new Vector2(0, 270), keepData: true } satisfies LatheMeshOptions; -const tubeOptions = { tubularSegments: 64, radialSegments: 8, closed: true, keepData: true } satisfies TubeMeshOptions; -const polygonOptions = { separateMaterials: true, keepData: true } satisfies PolygonMeshOptions; +const regularPolyhedronOptions = { edgeSegments: 2, keepCPUData: true } satisfies RegularPolyhedronMeshOptions; +const latheOptions = { segments: 32, angleRange: new Vector2(0, 270), keepCPUData: true } satisfies LatheMeshOptions; +const tubeOptions = { + pathSegments: 64, + radialSegments: 8, + closedPath: true, + keepCPUData: true +} satisfies TubeMeshOptions; +const polygonOptions = { separateMaterialSlots: true, keepCPUData: true } satisfies PolygonMeshOptions; const linearExtrusionOptions = { - steps: 4, - bevelSize: 0.1, - bevelThickness: 0.2, - bevelOffset: 0.1, + depthSegments: 4, + bevelWidth: 0.1, + bevelDepth: 0.2, + contourOffset: 0.1, bevelSegments: 3, - separateMaterials: true, - keepData: true + separateMaterialSlots: true, + keepCPUData: true } satisfies LinearExtrusionMeshOptions; -const torusKnotOptions = { tubularSegments: 64, radialSegments: 12, keepData: true } satisfies TorusKnotMeshOptions; +const torusKnotOptions = { pathSegments: 64, radialSegments: 12, keepCPUData: true } satisfies TorusKnotMeshOptions; const roundedCuboidOptions = { - segments: 4, - separateMaterials: true, - keepData: true + roundingSegments: 4, + separateMaterialSlots: true, + keepCPUData: true } satisfies RoundedCuboidMeshOptions; const pathExtrusionOptions = { - steps: 32, - closed: true, - separateMaterials: true, - keepData: true + pathSegments: 32, + closedPath: true, + separateMaterialSlots: true, + keepCPUData: true } satisfies PathExtrusionMeshOptions; const extrusionOptions: LinearExtrusionMeshOptions | PathExtrusionMeshOptions = pathExtrusionOptions; @@ -180,7 +185,7 @@ const meshes: ModelMesh[] = [ PrimitiveMesh.createExtrusion(engine, polygons, path, pathExtrusionOptions), PrimitiveMesh.createExtrusion(engine, polygons, path, extrusionOptions), PrimitiveMesh.createSphere(engine, 1, commonOptions), - PrimitiveMesh.createSphere(engine, 1, { subdivisions: 4 }), + PrimitiveMesh.createSphere(engine, 1, { subdivisionLevel: 4 }), PrimitiveMesh.createCylinder(engine, 0.5, 2, { caps: PrimitiveMeshCapMode.Both }), PrimitiveMesh.createCylinder(engine, 0.5, 2, { caps: PrimitiveMeshCapMode.Top }) ]; @@ -267,13 +272,13 @@ 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, { separateMaterials: true }); +PrimitiveMesh.createSphere(engine, 1, { separateMaterialSlots: true }); // @ts-expect-error Planes do not define material groups -PrimitiveMesh.createPlane(engine, 1, 1, { separateMaterials: true }); +PrimitiveMesh.createPlane(engine, 1, 1, { separateMaterialSlots: true }); // @ts-expect-error Tori do not define material groups -PrimitiveMesh.createTorus(engine, 1, 0.2, { separateMaterials: true }); +PrimitiveMesh.createTorus(engine, 1, 0.2, { separateMaterialSlots: true }); // @ts-expect-error Tubes do not define material groups -PrimitiveMesh.createTube(engine, path, 0.1, { separateMaterials: true }); +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 @@ -283,7 +288,7 @@ 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, { horizontalRange: { x: 0, y: 180 } }); +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 @@ -292,15 +297,15 @@ PrimitiveMesh.createCylinder(engine, 0.5, 2, { caps: "top" }); PrimitiveMesh.createTruncatedCone(engine, 0.25, 0.5, 2, { caps: "none" }); // Fields from the inactive mode follow normal structural compatibility -PrimitiveMesh.createExtrusion(engine, polygon, path, { bevelSize: 0.1 }); -PrimitiveMesh.createExtrusion(engine, polygon, path, { bevelOffset: 0.1 }); -PrimitiveMesh.createExtrusion(engine, polygon, 2, { closed: true }); +PrimitiveMesh.createExtrusion(engine, polygon, path, { bevelWidth: 0.1 }); +PrimitiveMesh.createExtrusion(engine, polygon, path, { contourOffset: 0.1 }); +PrimitiveMesh.createExtrusion(engine, polygon, 2, { closedPath: true }); // @ts-expect-error Bevel offsets use numeric local units -PrimitiveMesh.createExtrusion(engine, polygon, 2, { bevelOffset: "0.1" }); +PrimitiveMesh.createExtrusion(engine, polygon, 2, { contourOffset: "0.1" }); // @ts-expect-error Explicit linear settings do not declare path closure -const invalidLinearOptions: LinearExtrusionMeshOptions = { closed: true }; +const invalidLinearOptions: LinearExtrusionMeshOptions = { closedPath: true }; // @ts-expect-error Explicit path settings do not declare bevels -const invalidPathOptions: PathExtrusionMeshOptions = { bevelSize: 0.1 }; +const invalidPathOptions: PathExtrusionMeshOptions = { bevelWidth: 0.1 }; const samplePath = (t: number, out: Vector3): void => { out.set(t, t * t, 0); diff --git a/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts index c93799931e..288ba1d879 100644 --- a/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts +++ b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts @@ -12,19 +12,23 @@ const everyAssetHasAFactory: Exclude e const sphere: PrimitiveMeshAsset = { type: "sphere", sphereRadius: 1, - sphereOptions: { verticalRange: { x: 0, y: 90 }, keepData: true, subdivisions: 3 } + sphereOptions: { verticalAngleRange: { x: 0, y: 90 }, keepCPUData: true, subdivisionLevel: 3 } }; const exportedFromEngine: EnginePrimitiveMeshAsset = sphere; const sphereSection: PrimitiveMeshAsset = { type: "sphere", sphereRadius: 1, - sphereOptions: { horizontalRange: { x: 350, y: 370 }, verticalRange: { x: 30, y: 150 }, subdivisions: 3 } + 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: { separateMaterials: true } + sphereOptions: { separateMaterialSlots: true } }; const path = [ { x: 0, y: 0, z: 0 }, @@ -40,26 +44,26 @@ const shapes = [ } ] as const; -const tube: PrimitiveMeshAsset = { type: "tube", tubeRadius: 0.5, tubePath: path, tubeOptions: { closed: true } }; +const tube: PrimitiveMeshAsset = { type: "tube", tubeRadius: 0.5, tubePath: path, tubeOptions: { closedPath: true } }; const polygon: PrimitiveMeshAsset = { type: "polygon", polygonShapes: shapes }; const extrusion: PrimitiveMeshAsset = { type: "extrusion", extrusionDepth: 2, extrusionShapes: shapes, - extrusionOptions: { bevelSize: 0.1, bevelOffset: 0.2, separateMaterials: true } + extrusionOptions: { bevelWidth: 0.1, contourOffset: 0.2, separateMaterialSlots: true } }; const pathExtrusion: PrimitiveMeshAsset = { type: "extrusion", extrusionPath: path, extrusionShapes: shapes, - extrusionOptions: { closed: true } + extrusionOptions: { closedPath: true } }; const torusKnot: PrimitiveMeshAsset = { type: "torusKnot", torusKnotRadius: 0.5, torusKnotTubeRadius: 0.1, - torusKnotP: -2, - torusKnotQ: -3 + torusKnotAxisTurns: -2, + torusKnotCrossSectionTurns: -3 }; const cylinder: PrimitiveMeshAsset = { type: "cylinder", @@ -93,19 +97,19 @@ const beveledPath: PrimitiveMeshAsset = { type: "extrusion", extrusionPath: path, extrusionShapes: shapes, - extrusionOptions: { bevelSize: 1 } + extrusionOptions: { bevelWidth: 1 } }; const offsetPath: PrimitiveMeshAsset = { type: "extrusion", extrusionPath: path, extrusionShapes: shapes, - extrusionOptions: { bevelOffset: 0.1 } + extrusionOptions: { contourOffset: 0.1 } }; const closedDepth: PrimitiveMeshAsset = { type: "extrusion", extrusionDepth: 2, extrusionShapes: shapes, - extrusionOptions: { closed: true } + extrusionOptions: { closedPath: true } }; const wrongOptions: PrimitiveMeshAsset = { type: "sphere", diff --git a/tests/src/core/mesh/BlendShapeManager.test.ts b/tests/src/core/mesh/BlendShapeManager.test.ts index 1947b1cabf..eb7ed0a589 100644 --- a/tests/src/core/mesh/BlendShapeManager.test.ts +++ b/tests/src/core/mesh/BlendShapeManager.test.ts @@ -218,7 +218,7 @@ describe("BlendShapeManager", () => { ); blendShapeWeights0_7.addFrame(frame); const modelMeshWebgl2 = PrimitiveMesh.createCuboid(engineWebGL2, 1, 1, 1, { - keepData: true, + keepCPUData: true, widthSegments: 1, heightSegments: 1, depthSegments: 1 diff --git a/tests/src/core/mesh/PrimitiveMesh.test.ts b/tests/src/core/mesh/PrimitiveMesh.test.ts index 10f8052931..53049eb839 100644 --- a/tests/src/core/mesh/PrimitiveMesh.test.ts +++ b/tests/src/core/mesh/PrimitiveMesh.test.ts @@ -20,8 +20,8 @@ describe("PrimitiveMesh", () => { it("createSphere", () => { const radius = 2.333; - const subdivisions = 3.2; - const sphereMesh = PrimitiveMesh.createSphere(engine, radius, { keepData: true, subdivisions }); + const subdivisionLevel = 3.2; + const sphereMesh = PrimitiveMesh.createSphere(engine, radius, { keepCPUData: true, subdivisionLevel }); expect(sphereMesh.vertexCount).equal(417); expect(sphereMesh.vertexElements.length).equal(4); @@ -37,7 +37,7 @@ describe("PrimitiveMesh", () => { const height = 3.2; const depth = 4.5; const cuboidMesh = PrimitiveMesh.createCuboid(engine, width, height, depth, { - keepData: true, + keepCPUData: true, widthSegments: 1, heightSegments: 1, depthSegments: 1 @@ -61,7 +61,7 @@ describe("PrimitiveMesh", () => { const floorRadialSegments = Math.floor(radialSegments); const floorHeightSegments = Math.floor(heightSegments); const truncatedConeMesh = PrimitiveMesh.createTruncatedCone(engine, radiusTop, radiusBottom, height, { - keepData: true, + keepCPUData: true, radialSegments, heightSegments }); @@ -84,23 +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, { - keepData: true, - angleRange: new Vector2(0, 0 + arc), - tubularSegments, + keepCPUData: 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); }); @@ -113,9 +113,9 @@ describe("PrimitiveMesh", () => { const floorHSegments = Math.floor(hSegments); const floorVSegments = Math.floor(vSegments); const planeMesh = PrimitiveMesh.createPlane(engine, width, height, { - keepData: true, - horizontalSegments: hSegments, - verticalSegments: vSegments + keepCPUData: true, + widthSegments: hSegments, + depthSegments: vSegments }); expect(planeMesh.vertexCount).equal((floorHSegments + 1) * (floorVSegments + 1)); @@ -135,7 +135,7 @@ describe("PrimitiveMesh", () => { const floorRadialSegments = Math.floor(radialSegments); const floorHeightSegments = Math.floor(heightSegments); const coneMesh = PrimitiveMesh.createCone(engine, radius, height, { - keepData: true, + keepCPUData: true, radialSegments, heightSegments }); @@ -156,7 +156,7 @@ describe("PrimitiveMesh", () => { const floorRadialSegments = Math.floor(radialSegments); const floorHeightSegments = Math.floor(heightSegments); const capsuleMesh = PrimitiveMesh.createCapsule(engine, radius, height, { - keepData: true, + keepCPUData: true, radialSegments, capSegments: radialSegments, heightSegments @@ -180,9 +180,9 @@ describe("PrimitiveMesh", () => { if (engine["_hardwareRenderer"].canIUse(GLCapabilityType.elementIndexUint)) { const mesh = PrimitiveMesh.createPlane(engine, radius * 2, radius * 2, { - keepData: true, - horizontalSegments: segments, - verticalSegments: segments + keepCPUData: true, + widthSegments: segments, + depthSegments: segments }); expect(mesh.vertexCount).equal(count * count); expect(mesh.vertexElements.length).equal(4); @@ -193,9 +193,9 @@ describe("PrimitiveMesh", () => { } else { expect(() => PrimitiveMesh.createPlane(engine, radius * 2, radius * 2, { - keepData: true, - horizontalSegments: segments, - verticalSegments: segments + keepCPUData: true, + widthSegments: segments, + depthSegments: segments }) ).throw("The vertex count is out of range."); } diff --git a/tests/src/core/mesh/ProceduralMesh.test.ts b/tests/src/core/mesh/ProceduralMesh.test.ts index 70a851656e..935ac4b862 100644 --- a/tests/src/core/mesh/ProceduralMesh.test.ts +++ b/tests/src/core/mesh/ProceduralMesh.test.ts @@ -29,32 +29,36 @@ const polygon = { 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, { keepData: true, subdivisions: 2 })], + ["sphere", () => PrimitiveMesh.createSphere(engine, 2, { keepCPUData: true, subdivisionLevel: 2 })], [ "cuboid", () => PrimitiveMesh.createCuboid(engine, 1, 1, 1, { - keepData: true, + keepCPUData: true, widthSegments: 3, heightSegments: 2, depthSegments: 2 }) ], - [ - "plane", - () => PrimitiveMesh.createPlane(engine, 1, 1, { keepData: true, horizontalSegments: 3, verticalSegments: 2 }) - ], + ["plane", () => PrimitiveMesh.createPlane(engine, 1, 1, { keepCPUData: true, widthSegments: 3, depthSegments: 2 })], [ "cylinder", () => - PrimitiveMesh.createTruncatedCone(engine, 0.25, 1, 2, { keepData: true, radialSegments: 12, heightSegments: 1 }) + PrimitiveMesh.createTruncatedCone(engine, 0.25, 1, 2, { + keepCPUData: true, + radialSegments: 12, + heightSegments: 1 + }) + ], + [ + "cone", + () => PrimitiveMesh.createCone(engine, 0.5, 2, { keepCPUData: true, radialSegments: 12, heightSegments: 1 }) ], - ["cone", () => PrimitiveMesh.createCone(engine, 0.5, 2, { keepData: true, radialSegments: 12, heightSegments: 1 })], [ "capsule", () => PrimitiveMesh.createCapsule(engine, 0.5, 2, { - keepData: true, + keepCPUData: true, radialSegments: 12, capSegments: 4, heightSegments: 1 @@ -64,51 +68,56 @@ const creators: [string, () => ModelMesh][] = [ "torus", () => PrimitiveMesh.createTorus(engine, 0.5, 0.1, { - keepData: true, - angleRange: new Vector2(0, 360), - tubularSegments: 16, + keepCPUData: true, + ringAngleRange: new Vector2(0, 360), + ringSegments: 16, radialSegments: 8 }) ], [ "circle", - () => PrimitiveMesh.createCircle(engine, 0.5, { keepData: true, angleRange: new Vector2(0, 180), segments: 12 }) + () => PrimitiveMesh.createCircle(engine, 0.5, { keepCPUData: true, angleRange: new Vector2(0, 180), segments: 12 }) ], [ "ring", () => PrimitiveMesh.createRing(engine, 0.5, 0.25, { - keepData: true, + keepCPUData: true, angleRange: new Vector2(0, 360), - radialSegments: 12, + ringSegments: 12, widthSegments: 2 }) ], - ["tetrahedron", () => PrimitiveMesh.createTetrahedron(engine, 0.5, { keepData: true, segments: 1 })], - ["octahedron", () => PrimitiveMesh.createOctahedron(engine, 0.5, { keepData: true, segments: 1 })], - ["icosahedron", () => PrimitiveMesh.createIcosahedron(engine, 0.5, { keepData: true, segments: 2 })], - ["dodecahedron", () => PrimitiveMesh.createDodecahedron(engine, 0.5, { keepData: true, segments: 1 })], + ["tetrahedron", () => PrimitiveMesh.createTetrahedron(engine, 0.5, { keepCPUData: true, edgeSegments: 1 })], + ["octahedron", () => PrimitiveMesh.createOctahedron(engine, 0.5, { keepCPUData: true, edgeSegments: 1 })], + ["icosahedron", () => PrimitiveMesh.createIcosahedron(engine, 0.5, { keepCPUData: true, edgeSegments: 2 })], + ["dodecahedron", () => PrimitiveMesh.createDodecahedron(engine, 0.5, { keepCPUData: true, edgeSegments: 1 })], [ "lathe", () => PrimitiveMesh.createLathe(engine, [new Vector2(0, -1), new Vector2(1, 0), new Vector2(0, 1)], { - keepData: true, + keepCPUData: true, angleRange: new Vector2(0, 360), segments: 12 }) ], [ "tube", - () => PrimitiveMesh.createTube(engine, path, 0.5, { keepData: true, tubularSegments: 12, radialSegments: 8 }) + () => PrimitiveMesh.createTube(engine, path, 0.5, { keepCPUData: true, pathSegments: 12, radialSegments: 8 }) ], - ["polygon", () => PrimitiveMesh.createPolygon(engine, polygon, { keepData: true })], - ["extrusion", () => PrimitiveMesh.createExtrusion(engine, polygon, 2, { keepData: true, steps: 1 })], + ["polygon", () => PrimitiveMesh.createPolygon(engine, polygon, { keepCPUData: true })], + ["extrusion", () => PrimitiveMesh.createExtrusion(engine, polygon, 2, { keepCPUData: true, depthSegments: 1 })], [ "extrusion", () => - PrimitiveMesh.createExtrusion(engine, polygon, 1, { keepData: true, bevelSize: 0.1, bevelOffset: 0.2, steps: 1 }) + PrimitiveMesh.createExtrusion(engine, polygon, 1, { + keepCPUData: true, + bevelWidth: 0.1, + contourOffset: 0.2, + depthSegments: 1 + }) ], - ["extrusion", () => PrimitiveMesh.createExtrusion(engine, polygon, path, { keepData: true, steps: 5 })], + ["extrusion", () => PrimitiveMesh.createExtrusion(engine, polygon, path, { keepCPUData: true, pathSegments: 5 })], [ "extrusion", () => @@ -125,34 +134,37 @@ const creators: [string, () => ModelMesh][] = [ ] }, 1, - { keepData: true, bevelSize: 0.05, bevelThickness: 0.1, bevelOffset: -0.05, steps: 1 } + { keepCPUData: true, bevelWidth: 0.05, bevelDepth: 0.1, contourOffset: -0.05, depthSegments: 1 } ) ], [ "torusKnot", () => - PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2, 3, { keepData: true, tubularSegments: 32, radialSegments: 8 }) + PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2, 3, { keepCPUData: true, pathSegments: 32, radialSegments: 8 }) ], [ "torusKnot", () => PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, -2, -3, { - keepData: true, - tubularSegments: 32, + keepCPUData: true, + pathSegments: 32, radialSegments: 8 }) ], - ["roundedCuboid", () => PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.15, { keepData: true, segments: 3 })] + [ + "roundedCuboid", + () => PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.15, { keepCPUData: true, roundingSegments: 3 }) + ] ]; describe("primitive mesh defaults", () => { - const options = { keepData: true }; + const options = { keepCPUData: 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, subdivisions: 3 }) + () => PrimitiveMesh.createSphere(engine, 1, { ...options, subdivisionLevel: 3 }) ], [ "cuboid", @@ -167,8 +179,8 @@ describe("primitive mesh defaults", () => { ], [ "plane", - () => PrimitiveMesh.createPlane(engine, 2, 3, { ...options, horizontalSegments: 2 }), - () => PrimitiveMesh.createPlane(engine, 2, 3, { ...options, horizontalSegments: 2, verticalSegments: 2 }) + () => PrimitiveMesh.createPlane(engine, 2, 3, { ...options, widthSegments: 2 }), + () => PrimitiveMesh.createPlane(engine, 2, 3, { ...options, widthSegments: 2, depthSegments: 2 }) ], [ "cylinder", @@ -199,7 +211,7 @@ describe("primitive mesh defaults", () => { [ "torus", () => PrimitiveMesh.createTorus(engine, 1, 0.2, { ...options }), - () => PrimitiveMesh.createTorus(engine, 1, 0.2, { ...options, tubularSegments: 30, radialSegments: 30 }) + () => PrimitiveMesh.createTorus(engine, 1, 0.2, { ...options, ringSegments: 30, radialSegments: 30 }) ], [ "circle", @@ -209,27 +221,27 @@ describe("primitive mesh defaults", () => { [ "ring", () => PrimitiveMesh.createRing(engine, 1, 0.5, { ...options }), - () => PrimitiveMesh.createRing(engine, 1, 0.5, { ...options, radialSegments: 32, widthSegments: 1 }) + () => PrimitiveMesh.createRing(engine, 1, 0.5, { ...options, ringSegments: 32, widthSegments: 1 }) ], [ "tetrahedron", () => PrimitiveMesh.createTetrahedron(engine, 1, { ...options }), - () => PrimitiveMesh.createTetrahedron(engine, 1, { ...options, segments: 1 }) + () => PrimitiveMesh.createTetrahedron(engine, 1, { ...options, edgeSegments: 1 }) ], [ "octahedron", () => PrimitiveMesh.createOctahedron(engine, 1, { ...options }), - () => PrimitiveMesh.createOctahedron(engine, 1, { ...options, segments: 1 }) + () => PrimitiveMesh.createOctahedron(engine, 1, { ...options, edgeSegments: 1 }) ], [ "icosahedron", () => PrimitiveMesh.createIcosahedron(engine, 1, { ...options }), - () => PrimitiveMesh.createIcosahedron(engine, 1, { ...options, segments: 1 }) + () => PrimitiveMesh.createIcosahedron(engine, 1, { ...options, edgeSegments: 1 }) ], [ "dodecahedron", () => PrimitiveMesh.createDodecahedron(engine, 1, { ...options }), - () => PrimitiveMesh.createDodecahedron(engine, 1, { ...options, segments: 1 }) + () => PrimitiveMesh.createDodecahedron(engine, 1, { ...options, edgeSegments: 1 }) ], [ "lathe", @@ -239,27 +251,27 @@ describe("primitive mesh defaults", () => { [ "tube", () => PrimitiveMesh.createTube(engine, path, 0.2, { ...options }), - () => PrimitiveMesh.createTube(engine, path, 0.2, { ...options, tubularSegments: 64, radialSegments: 8 }) + () => PrimitiveMesh.createTube(engine, path, 0.2, { ...options, pathSegments: 64, radialSegments: 8 }) ], [ "depth extrusion", () => PrimitiveMesh.createExtrusion(engine, polygon, 2, { ...options }), - () => PrimitiveMesh.createExtrusion(engine, polygon, 2, { ...options, steps: 1 }) + () => PrimitiveMesh.createExtrusion(engine, polygon, 2, { ...options, depthSegments: 1 }) ], [ "path extrusion", () => PrimitiveMesh.createExtrusion(engine, polygon, path, { ...options }), - () => PrimitiveMesh.createExtrusion(engine, polygon, path, { ...options, steps: 1 }) + () => PrimitiveMesh.createExtrusion(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, tubularSegments: 64, radialSegments: 8 }) + () => 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, segments: 2 }) + () => PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0.2, { ...options, roundingSegments: 2 }) ] ]; @@ -307,7 +319,7 @@ describe("procedural mesh geometry", () => { 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, { subdivisions: 4 }); + 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 }); @@ -327,7 +339,7 @@ describe("procedural mesh geometry", () => { const frustum = PrimitiveMesh.createTruncatedCone(engine, 0.5, 1.5, 4); const topOnly = PrimitiveMesh.createCylinder(engine, 1, 3, { caps: PrimitiveMeshCapMode.Top, - keepData: true, + keepCPUData: true, radialSegments: 8, heightSegments: 1 }); @@ -348,10 +360,10 @@ describe("procedural mesh geometry", () => { const fromContours = PrimitiveMesh.createPolygon( engine, { points: polygon.points, holes: polygon.holes }, - { keepData: true } + { keepCPUData: true } ); - const fromShape = PrimitiveMesh.createPolygon(engine, polygon, { keepData: true }); - const withoutHoles = PrimitiveMesh.createPolygon(engine, polygon.points, { keepData: true }); + const fromShape = PrimitiveMesh.createPolygon(engine, polygon, { keepCPUData: true }); + const withoutHoles = PrimitiveMesh.createPolygon(engine, polygon.points, { keepCPUData: true }); try { expect(Array.from(fromContours.getIndices()!)).toEqual(Array.from(fromShape.getIndices()!)); expect(withoutHoles.getIndices()!.length).toBe(6); @@ -364,9 +376,9 @@ describe("procedural mesh geometry", () => { it("honors offset angular ranges for torus sections", () => { const mesh = PrimitiveMesh.createTorus(engine, 1, 0.25, { - keepData: true, - angleRange: new Vector2(90, 180), - tubularSegments: 8, + keepCPUData: true, + ringAngleRange: new Vector2(90, 180), + ringSegments: 8, radialSegments: 6 }); try { @@ -379,37 +391,40 @@ describe("procedural mesh geometry", () => { }); it.each([ - { p: 2, q: 3, expected: new Vector3(1, Math.sqrt(3), 1) }, - { p: 2, q: -3, expected: new Vector3(1, Math.sqrt(3), -1) }, - { p: -2, q: 3, expected: new Vector3(1, -Math.sqrt(3), 1) }, - { p: -2, q: -3, expected: new Vector3(1, -Math.sqrt(3), -1) }, - { p: 0, q: 1, expected: new Vector3(2 + Math.sqrt(3) / 2, 0, 0.5) }, - { p: 1, q: 0, expected: new Vector3((3 * Math.sqrt(3)) / 2, 1.5, 0) } - ])("preserves torus knot windings p=$p, q=$q during creation and restoration", ({ p, q, expected }) => { - const radialSegments = 8; - const mesh = PrimitiveMesh.createTorusKnot(engine, 2, 0.2, p, q, { - keepData: true, - tubularSegments: 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); + { 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, { + keepCPUData: 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(); + 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 }, @@ -419,7 +434,7 @@ describe("procedural mesh geometry", () => { "centers capsule pole UVs with $radialSegments radial segments", ({ radialSegments, capSegments, heightSegments }) => { const mesh = PrimitiveMesh.createCapsule(engine, 1, 2, { - keepData: true, + keepCPUData: true, radialSegments, capSegments, heightSegments @@ -473,7 +488,7 @@ describe("procedural mesh geometry", () => { } ])("preserves $segments segment(s) in a partial lathe", ({ segments, crossSection }) => { const mesh = PrimitiveMesh.createLathe(engine, [new Vector2(1, -1), new Vector2(1, 1)], { - keepData: true, + keepCPUData: true, angleRange: new Vector2(0, 90), segments }); @@ -505,9 +520,9 @@ describe("procedural mesh geometry", () => { const sizes = { x: 2, y: 3, z: 4 }; const radius = 0.25; const mesh = PrimitiveMesh.createRoundedCuboid(engine, sizes.x, sizes.y, sizes.z, radius, { - keepData: true, - separateMaterials: true, - segments + keepCPUData: true, + separateMaterialSlots: true, + roundingSegments: segments }); const faces = [ { axis: "y", sign: 1, u: "x", v: "z", flipU: false, flipV: false }, @@ -550,7 +565,7 @@ describe("procedural mesh geometry", () => { }); it("handles rounded cuboid radius and segment limits without changing the cuboid fallback", () => { - const options = { keepData: true, separateMaterials: true }; + const options = { keepCPUData: true, separateMaterialSlots: true }; const meshes = [ PrimitiveMesh.createCuboid(engine, 2, 3, 4, { ...options, @@ -558,12 +573,12 @@ describe("procedural mesh geometry", () => { heightSegments: 1, depthSegments: 1 }), - PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0, { ...options, segments: 4 }), - PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, -1, { ...options, segments: 4 }), - PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 1, { ...options, segments: 3 }), - PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 8, { ...options, segments: 3 }), - PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0.2, { ...options, segments: 0 }), - PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0.2, { ...options, segments: 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 [ @@ -587,8 +602,8 @@ describe("procedural mesh geometry", () => { ])("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, { - keepData: true, - segments: 4 + keepCPUData: true, + roundingSegments: 4 }); try { const positions = mesh.getPositions()!; @@ -616,13 +631,13 @@ describe("procedural mesh geometry", () => { } }); - it.each([false, true])("controls all generated vertex data through keepData=%s", (keepData) => { - const mesh = PrimitiveMesh.createSphere(engine, 0.5, { keepData, subdivisions: 1 }); + it.each([false, true])("controls all generated vertex data through keepCPUData=%s", (keepCPUData) => { + const mesh = PrimitiveMesh.createSphere(engine, 0.5, { keepCPUData, subdivisionLevel: 1 }); try { for (const binding of mesh.vertexBufferBindings) { - expect(binding!.buffer.readable).toBe(keepData); + expect(binding!.buffer.readable).toBe(keepCPUData); } - if (keepData) { + if (keepCPUData) { expect(mesh.getPositions()).toHaveLength(mesh.vertexCount); expect(mesh.getNormals()).toHaveLength(mesh.vertexCount); expect(mesh.getTangents()).toHaveLength(mesh.vertexCount); @@ -681,7 +696,7 @@ describe("procedural mesh geometry", () => { }); it("keeps sphere tangents perpendicular at non-unit radii", () => { - const mesh = PrimitiveMesh.createSphere(engine, 2, { keepData: true, subdivisions: 3 }); + const mesh = PrimitiveMesh.createSphere(engine, 2, { keepCPUData: true, subdivisionLevel: 3 }); try { expect(mesh.vertexCount).toBe(417); expect(mesh.getIndices()!.length / 3).toBe(768); @@ -699,9 +714,9 @@ describe("procedural mesh geometry", () => { it("supports a northern hemisphere", () => { const mesh = PrimitiveMesh.createSphere(engine, 0.5, { - keepData: true, - verticalRange: new Vector2(0, 90), - subdivisions: 2 + keepCPUData: true, + verticalAngleRange: new Vector2(0, 90), + subdivisionLevel: 2 }); try { expect(mesh.getPositions()!.every((p) => p.y >= -1e-7)).toBe(true); @@ -720,10 +735,10 @@ describe("procedural mesh geometry", () => { ])("clips a sphere to $horizontal and $vertical without cracks", ({ horizontal, vertical }) => { const radius = 2; const mesh = PrimitiveMesh.createSphere(engine, radius, { - keepData: true, - horizontalRange: new Vector2(horizontal[0], horizontal[1]), - verticalRange: new Vector2(vertical[0], vertical[1]), - subdivisions: 3 + keepCPUData: true, + horizontalAngleRange: new Vector2(horizontal[0], horizontal[1]), + verticalAngleRange: new Vector2(vertical[0], vertical[1]), + subdivisionLevel: 3 }); try { const positions = mesh.getPositions()!; @@ -793,11 +808,11 @@ describe("procedural mesh geometry", () => { }); it("rotates complete spheres without changing topology", () => { - const original = PrimitiveMesh.createSphere(engine, 1, { keepData: true, subdivisions: 2 }); + const original = PrimitiveMesh.createSphere(engine, 1, { keepCPUData: true, subdivisionLevel: 2 }); const rotated = PrimitiveMesh.createSphere(engine, 1, { - keepData: true, - horizontalRange: new Vector2(90, 450), - subdivisions: 2 + keepCPUData: true, + horizontalAngleRange: new Vector2(90, 450), + subdivisionLevel: 2 }); try { expect(rotated.getIndices()).toEqual(original.getIndices()); @@ -815,14 +830,18 @@ describe("procedural mesh geometry", () => { }); it("captures sphere ranges for device restoration", () => { - const horizontalRange = new Vector2(20, 290); - const verticalRange = new Vector2(30, 150); - const mesh = PrimitiveMesh.createSphere(engine, 1, { horizontalRange, verticalRange, subdivisions: 3 }); + 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); - horizontalRange.y = 360; - verticalRange.x = 0; + horizontalAngleRange.y = 360; + verticalAngleRange.x = 0; MeshTestUtils.clearBuffer(buffer); (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); expect(MeshTestUtils.readBuffer(buffer)).toEqual(original); @@ -833,18 +852,18 @@ describe("procedural mesh geometry", () => { it("omits cylinder caps and makes material groups opt-in", () => { const open = PrimitiveMesh.createCylinder(engine, 0.5, 2, { - keepData: true, + keepCPUData: true, caps: PrimitiveMeshCapMode.None, radialSegments: 8, heightSegments: 1 }); const grouped = PrimitiveMesh.createCylinder(engine, 0.5, 2, { - separateMaterials: true, + separateMaterialSlots: true, radialSegments: 8, heightSegments: 1 }); const cube = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { - separateMaterials: true, + separateMaterialSlots: true, widthSegments: 1, heightSegments: 1, depthSegments: 1 @@ -863,8 +882,8 @@ describe("procedural mesh geometry", () => { it("orders cuboid material slots by face direction", () => { const mesh = PrimitiveMesh.createCuboid(engine, 1, 2, 3, { - keepData: true, - separateMaterials: true, + keepCPUData: true, + separateMaterialSlots: true, widthSegments: 1, heightSegments: 1, depthSegments: 1 @@ -890,8 +909,8 @@ describe("procedural mesh geometry", () => { name: "cylinder with both caps", create: () => PrimitiveMesh.createCylinder(engine, 1, 2, { - keepData: true, - separateMaterials: true, + keepCPUData: true, + separateMaterialSlots: true, radialSegments: 8, heightSegments: 1 }), @@ -901,8 +920,8 @@ describe("procedural mesh geometry", () => { name: "cylinder with only its top cap", create: () => PrimitiveMesh.createCylinder(engine, 1, 2, { - keepData: true, - separateMaterials: true, + keepCPUData: true, + separateMaterialSlots: true, caps: PrimitiveMeshCapMode.Top, radialSegments: 8, heightSegments: 1 @@ -913,8 +932,8 @@ describe("procedural mesh geometry", () => { name: "cylinder with only its bottom cap", create: () => PrimitiveMesh.createCylinder(engine, 1, 2, { - keepData: true, - separateMaterials: true, + keepCPUData: true, + separateMaterialSlots: true, caps: PrimitiveMeshCapMode.Bottom, radialSegments: 8, heightSegments: 1 @@ -925,8 +944,8 @@ describe("procedural mesh geometry", () => { name: "cylinder without caps", create: () => PrimitiveMesh.createCylinder(engine, 1, 2, { - keepData: true, - separateMaterials: true, + keepCPUData: true, + separateMaterialSlots: true, caps: PrimitiveMeshCapMode.None, radialSegments: 8, heightSegments: 1 @@ -937,8 +956,8 @@ describe("procedural mesh geometry", () => { name: "truncated cone with a zero top radius", create: () => PrimitiveMesh.createTruncatedCone(engine, 0, 1, 2, { - keepData: true, - separateMaterials: true, + keepCPUData: true, + separateMaterialSlots: true, radialSegments: 8, heightSegments: 1 }), @@ -948,8 +967,8 @@ describe("procedural mesh geometry", () => { name: "truncated cone with a zero bottom radius", create: () => PrimitiveMesh.createTruncatedCone(engine, 1, 0, 2, { - keepData: true, - separateMaterials: true, + keepCPUData: true, + separateMaterialSlots: true, radialSegments: 8, heightSegments: 1 }), @@ -959,8 +978,8 @@ describe("procedural mesh geometry", () => { name: "cone with its bottom cap", create: () => PrimitiveMesh.createCone(engine, 1, 2, { - keepData: true, - separateMaterials: true, + keepCPUData: true, + separateMaterialSlots: true, radialSegments: 8, heightSegments: 1 }), @@ -970,8 +989,8 @@ describe("procedural mesh geometry", () => { name: "cone without its bottom cap", create: () => PrimitiveMesh.createCone(engine, 1, 2, { - keepData: true, - separateMaterials: true, + keepCPUData: true, + separateMaterialSlots: true, cap: false, radialSegments: 8, heightSegments: 1 @@ -996,7 +1015,7 @@ describe("procedural mesh geometry", () => { 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, { keepData: true, separateMaterials: true }); + const mesh = PrimitiveMesh.createPolygon(engine, shapes, { keepCPUData: true, separateMaterialSlots: true }); try { const indices = mesh.getIndices()!; const positions = mesh.getPositions()!; @@ -1013,9 +1032,9 @@ describe("procedural mesh geometry", () => { 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.createExtrusion(engine, shapes, 2, { - keepData: true, - separateMaterials: true, - steps: 1 + keepCPUData: true, + separateMaterialSlots: true, + depthSegments: 1 }); try { const indices = mesh.getIndices()!; @@ -1033,12 +1052,12 @@ describe("procedural mesh geometry", () => { } }); - it.each([0.2, -0.2])("offsets extrusion walls and bevels by %s and restores their geometry", (bevelOffset) => { - const options = { keepData: true, separateMaterials: true, bevelSize: 0.1, bevelThickness: 0.2, bevelOffset }; - const mesh = PrimitiveMesh.createExtrusion(engine, polygon, 2, { ...options, steps: 2 }); + it.each([0.2, -0.2])("offsets extrusion walls and bevels by %s and restores their geometry", (contourOffset) => { + const options = { keepCPUData: true, separateMaterialSlots: true, bevelWidth: 0.1, bevelDepth: 0.2, contourOffset }; + const mesh = PrimitiveMesh.createExtrusion(engine, polygon, 2, { ...options, depthSegments: 2 }); try { - const outer = 2 + bevelOffset; - const hole = 1 - bevelOffset; + 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); @@ -1061,7 +1080,7 @@ describe("procedural mesh geometry", () => { const buffer = mesh.vertexBufferBindings[0]!.buffer; const original = buffer.data!.slice(); const indices = Array.from(mesh.getIndices()!); - options.bevelOffset = 100; + options.contourOffset = 100; MeshTestUtils.clearBuffer(buffer); (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); expect(MeshTestUtils.readBuffer(buffer)).toEqual(original); @@ -1072,8 +1091,12 @@ describe("procedural mesh geometry", () => { } }); - it.each([0.2, -0.2])("offsets extrusion contours by %s without adding bevels", (bevelOffset) => { - const mesh = PrimitiveMesh.createExtrusion(engine, polygon, 2, { keepData: true, bevelOffset, steps: 1 }); + it.each([0.2, -0.2])("offsets extrusion contours by %s without adding bevels", (contourOffset) => { + const mesh = PrimitiveMesh.createExtrusion(engine, polygon, 2, { + keepCPUData: true, + contourOffset, + depthSegments: 1 + }); try { const positions = mesh.getPositions()!; expect(positions.every(({ z }) => z === 0 || z === 2)).toBe(true); @@ -1087,8 +1110,8 @@ describe("procedural mesh geometry", () => { topArea += ((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)) / 2; } } - const outer = 2 + bevelOffset; - const hole = 1 - bevelOffset; + const outer = 2 + contourOffset; + const hole = 1 - contourOffset; expect(topArea).toBeCloseTo(4 * (outer * outer - hole * hole), 5); } finally { mesh.destroy(); @@ -1096,7 +1119,7 @@ describe("procedural mesh geometry", () => { }); it("triangulates holes without filling their interiors", () => { - const mesh = PrimitiveMesh.createPolygon(engine, polygon, { keepData: true }); + const mesh = PrimitiveMesh.createPolygon(engine, polygon, { keepCPUData: true }); try { const positions = mesh.getPositions()!; const indices = mesh.getIndices()!; @@ -1177,7 +1200,7 @@ describe("procedural mesh geometry", () => { points: reversed ? points.slice().reverse() : points, holes: holes.map((hole) => (reversed ? hole : hole.slice().reverse())) }; - const mesh = PrimitiveMesh.createPolygon(engine, shape, { keepData: true }); + const mesh = PrimitiveMesh.createPolygon(engine, shape, { keepCPUData: true }); try { const positions = mesh.getPositions()!; const indices = mesh.getIndices()!; @@ -1215,7 +1238,7 @@ describe("procedural mesh geometry", () => { it("preserves multiple holes in extrusion caps and restored buffers", () => { const { points, holes, area } = triangulationCases[1]; - const mesh = PrimitiveMesh.createExtrusion(engine, { points, holes }, 3, { keepData: true, steps: 1 }); + const mesh = PrimitiveMesh.createExtrusion(engine, { points, holes }, 3, { keepCPUData: true, depthSegments: 1 }); try { const positions = mesh.getPositions()!; const indices = Array.from(mesh.getIndices()!); @@ -1248,8 +1271,8 @@ describe("procedural mesh geometry", () => { it("restores captured geometry after caller-owned inputs and buffers change", () => { const points = [new Vector3(0, 0, 0), new Vector3(0, 1, 1), new Vector3(1, 2, 2)]; const mesh = PrimitiveMesh.createTube(engine, points, 0.5, { - keepData: true, - tubularSegments: 8, + keepCPUData: true, + pathSegments: 8, radialSegments: 8 }); try { @@ -1269,16 +1292,16 @@ describe("procedural mesh geometry", () => { }); it.each([ - { type: "tube", tubeRadius: 0.5, keepData: false }, - { type: "tube", tubeRadius: 0.5, keepData: true }, - { type: "extrusion", extrusionDepth: 1, keepData: false }, - { type: "extrusion", extrusionDepth: 1, keepData: true } - ])("copies $type path points for device restoration with keepData=$keepData", ({ type, keepData }) => { + { type: "tube", tubeRadius: 0.5, keepCPUData: false }, + { type: "tube", tubeRadius: 0.5, keepCPUData: true }, + { type: "extrusion", extrusionDepth: 1, keepCPUData: false }, + { type: "extrusion", extrusionDepth: 1, keepCPUData: true } + ])("copies $type path points for device restoration with keepCPUData=$keepCPUData", ({ type, keepCPUData }) => { const points = path.map((point) => point.clone()); const mesh = type === "tube" - ? PrimitiveMesh.createTube(engine, points, 0.5, { keepData, tubularSegments: 12, radialSegments: 8 }) - : PrimitiveMesh.createExtrusion(engine, polygon, points, { keepData, steps: 12 }); + ? PrimitiveMesh.createTube(engine, points, 0.5, { keepCPUData, pathSegments: 12, radialSegments: 8 }) + : PrimitiveMesh.createExtrusion(engine, polygon, points, { keepCPUData, pathSegments: 12 }); try { const buffers = mesh.vertexBufferBindings.map((binding) => binding!.buffer); buffers.push(mesh._primitive.indexBufferBinding!._buffer); @@ -1313,8 +1336,8 @@ describe("procedural mesh geometry", () => { it("restores spheres independently after interleaved creation", () => { const meshes = [ - PrimitiveMesh.createSphere(engine, 0.5, { keepData: true, subdivisions: 2 }), - PrimitiveMesh.createSphere(engine, 2, { keepData: true, subdivisions: 4 }) + PrimitiveMesh.createSphere(engine, 0.5, { keepCPUData: true, subdivisionLevel: 2 }), + PrimitiveMesh.createSphere(engine, 2, { keepCPUData: true, subdivisionLevel: 4 }) ]; const originals = meshes.map((mesh) => ({ vertices: mesh.vertexBufferBindings[0]!.buffer.data!.slice(), @@ -1338,9 +1361,9 @@ describe("procedural mesh geometry", () => { it("uses 32-bit indices for subdivided meshes beyond 65535 vertices", () => { const mesh = PrimitiveMesh.createPlane(engine, 1, 1, { - keepData: true, - horizontalSegments: 256, - verticalSegments: 256 + keepCPUData: true, + widthSegments: 256, + depthSegments: 256 }); try { expect(mesh.vertexCount).toBe(66049); @@ -1352,9 +1375,9 @@ describe("procedural mesh geometry", () => { 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, { - keepData: true, - closed: true, - tubularSegments: segments, + keepCPUData: true, + closedPath: true, + pathSegments: segments, radialSegments: 8 }); try { @@ -1376,8 +1399,8 @@ describe("procedural mesh geometry", () => { it.each([1, 2])("keeps torus-knot cross-sections with %s longitudinal segments", (segments) => { const mesh = PrimitiveMesh.createTorusKnot(engine, 1, 0.2, 2, 3, { - keepData: true, - tubularSegments: segments, + keepCPUData: true, + pathSegments: segments, radialSegments: 8 }); try { @@ -1407,9 +1430,9 @@ describe("procedural mesh geometry", () => { return new Vector3(Math.cos(angle), Math.sin(angle), Math.sin(angle * 2) / 3); }); const mesh = PrimitiveMesh.createTube(engine, points, 0.5, { - keepData: true, - closed: true, - tubularSegments: 40, + keepCPUData: true, + closedPath: true, + pathSegments: 40, radialSegments }); try { @@ -1432,11 +1455,11 @@ describe("procedural mesh geometry", () => { }); 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 = { keepData: true, closed: true }; - const mesh = PrimitiveMesh.createExtrusion(engine, profile, points, { ...options, steps: 32 }); + const options = { keepCPUData: true, closedPath: true }; + const mesh = PrimitiveMesh.createExtrusion(engine, profile, points, { ...options, pathSegments: 32 }); const repeated = PrimitiveMesh.createExtrusion(engine, profile, [...points, points[0].clone()], { ...options, - steps: 32 + pathSegments: 32 }); try { const positions = mesh.getPositions()!; @@ -1461,7 +1484,7 @@ describe("procedural mesh geometry", () => { const original = buffer.data!.slice(); const originalIndices = Array.from(indices); points[0].set(100, 200, 300); - options.closed = false; + options.closedPath = false; MeshTestUtils.clearBuffer(buffer); (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); expect(MeshTestUtils.readBuffer(buffer)).toEqual(original); @@ -1482,10 +1505,10 @@ describe("procedural mesh geometry", () => { ]; 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.createExtrusion(engine, shapes, points, { - keepData: true, - separateMaterials: true, - closed: true, - steps: 16 + keepCPUData: true, + separateMaterialSlots: true, + closedPath: true, + pathSegments: 16 }); try { const counts = [16 * 8 * 6, 16 * 4 * 6]; @@ -1500,20 +1523,21 @@ describe("procedural mesh geometry", () => { }); it("ignores settings from the inactive extrusion mode", () => { - const linearOptions = { keepData: true, steps: 2, bevelSize: 0.1, separateMaterials: true }; - const pathOptions = { keepData: true, steps: 5, separateMaterials: true }; + const linearOptions = { keepCPUData: true, depthSegments: 2, bevelWidth: 0.1, separateMaterialSlots: true }; + const pathOptions = { keepCPUData: true, pathSegments: 5, separateMaterialSlots: true }; const pairs = [ [ PrimitiveMesh.createExtrusion(engine, polygon, 2, linearOptions), - PrimitiveMesh.createExtrusion(engine, polygon, 2, { ...linearOptions, closed: true }) + PrimitiveMesh.createExtrusion(engine, polygon, 2, { ...linearOptions, pathSegments: 7, closedPath: true }) ], [ PrimitiveMesh.createExtrusion(engine, polygon, path, pathOptions), PrimitiveMesh.createExtrusion(engine, polygon, path, { ...pathOptions, - bevelSize: 0.25, - bevelThickness: 0.4, - bevelOffset: 0.5, + depthSegments: 7, + bevelWidth: 0.25, + bevelDepth: 0.4, + contourOffset: 0.5, bevelSegments: 8 }) ] @@ -1537,10 +1561,10 @@ describe("procedural mesh geometry", () => { } }); - it("uses at least three steps to close an extrusion path", () => { + 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.createExtrusion(engine, profile, points, { keepData: true, closed: true }); + const mesh = PrimitiveMesh.createExtrusion(engine, profile, points, { keepCPUData: true, closedPath: true }); try { const positions = mesh.getPositions()!; const indices = mesh.getIndices()!; @@ -1562,8 +1586,8 @@ describe("procedural mesh geometry", () => { 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, { - keepData: true, - tubularSegments: 4, + keepCPUData: true, + pathSegments: 4, radialSegments }); try { @@ -1592,7 +1616,7 @@ describe("procedural mesh geometry", () => { "keeps %s UVs within the shortest longitudinal interval", (create) => { for (const segments of [1, 2, 3]) { - const mesh = PrimitiveMesh[create](engine, 1, { segments, keepData: true }); + const mesh = PrimitiveMesh[create](engine, 1, { edgeSegments: segments, keepCPUData: true }); try { const uvs = mesh.getUVs()!; const indices = mesh.getIndices()!; @@ -1641,10 +1665,10 @@ describe("procedural mesh geometry", () => { it("preserves edited primitive data and material groups after device restoration", async () => { const restoredEngine = await WebGLEngine.create({ canvas: document.createElement("canvas") }); - const released = PrimitiveMesh.createSphere(restoredEngine, 1, { subdivisions: 1 }); + const released = PrimitiveMesh.createSphere(restoredEngine, 1, { subdivisionLevel: 1 }); const mesh = PrimitiveMesh.createCuboid(restoredEngine, 1, 1, 1, { - keepData: true, - separateMaterials: true, + keepCPUData: true, + separateMaterialSlots: true, widthSegments: 1, heightSegments: 1, depthSegments: 1 @@ -1698,9 +1722,9 @@ describe("procedural mesh geometry", () => { it("restores released tangents from edited primitive UVs", () => { const mesh = PrimitiveMesh.createPlane(engine, 2, 3, { - keepData: true, - horizontalSegments: 1, - verticalSegments: 1 + keepCPUData: true, + widthSegments: 1, + depthSegments: 1 }); try { mesh.setUVs(mesh.getUVs()!.map((uv) => new Vector2(uv.y, uv.x))); @@ -1721,9 +1745,9 @@ describe("procedural mesh geometry", () => { it.each([1, 1e-8])("normalizes tangents for a plane of size %s", (size) => { const mesh = PrimitiveMesh.createPlane(engine, size, size, { - keepData: true, - horizontalSegments: 1, - verticalSegments: 1 + keepCPUData: true, + widthSegments: 1, + depthSegments: 1 }); try { for (const tangent of mesh.getTangents()!) { @@ -1752,7 +1776,7 @@ describe("procedural mesh geometry", () => { }); it.each([false, true])("preserves tangent data when adding a vertex channel after reading: %s", (readTangents) => { - const mesh = PrimitiveMesh.createSphere(engine, 0.5, { keepData: true, subdivisions: 2 }); + const mesh = PrimitiveMesh.createSphere(engine, 0.5, { keepCPUData: true, subdivisionLevel: 2 }); try { const original = MeshTestUtils.readBuffer(mesh.vertexBufferBindings[1]!.buffer); if (readTangents) { @@ -1779,7 +1803,7 @@ describe("procedural mesh geometry", () => { }); it("releases primitive tangent data through the ModelMesh buffer lifecycle", () => { - const mesh = PrimitiveMesh.createPlane(engine, 1, 1, { keepData: true }); + const mesh = PrimitiveMesh.createPlane(engine, 1, 1, { keepCPUData: true }); try { const tangentBuffer = mesh.vertexBufferBindings[1]!.buffer; expect(tangentBuffer.readable).toBe(true); @@ -1813,7 +1837,7 @@ describe("procedural mesh geometry", () => { const angle = (i * Math.PI * 2) / 256; return new Vector2(Math.cos(angle), Math.sin(angle)); }); - const mesh = PrimitiveMesh.createExtrusion(engine, contour, 1, { keepData: true, steps: 43 }); + const mesh = PrimitiveMesh.createExtrusion(engine, contour, 1, { keepCPUData: true, depthSegments: 43 }); try { const indices = mesh.getIndices()!; expect(mesh.vertexCount).toBeGreaterThan(65535); @@ -1838,7 +1862,7 @@ describe("procedural mesh geometry", () => { ] }, 1, - { keepData: true, bevelSize: 0.1, steps: 1 } + { keepCPUData: true, bevelWidth: 0.1, depthSegments: 1 } ); try { expect(mesh.getPositions()!.every((p) => [p.x, p.y, p.z].every(Number.isFinite))).toBe(true); diff --git a/tests/src/core/physics/ColliderLayer.test.ts b/tests/src/core/physics/ColliderLayer.test.ts index 7a5f512f0f..ce23389fcd 100644 --- a/tests/src/core/physics/ColliderLayer.test.ts +++ b/tests/src/core/physics/ColliderLayer.test.ts @@ -102,7 +102,7 @@ describe("Collider layer initialization", () => { expect(attach.mock.calls.length).toBe(1); const mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { - keepData: true, + keepCPUData: true, widthSegments: 1, heightSegments: 1, depthSegments: 1 diff --git a/tests/src/core/physics/MeshColliderLayer.test.ts b/tests/src/core/physics/MeshColliderLayer.test.ts index df30258516..9b6c84dab6 100644 --- a/tests/src/core/physics/MeshColliderLayer.test.ts +++ b/tests/src/core/physics/MeshColliderLayer.test.ts @@ -26,7 +26,7 @@ describe("Mesh collider collision layers", () => { engine = await WebGLEngine.create({ canvas: document.createElement("canvas"), physics: createPhysics() }); physics = engine.sceneManager.activeScene.physics; mesh = PrimitiveMesh.createCuboid(engine, 10, 1, 10, { - keepData: true, + keepCPUData: true, widthSegments: 1, heightSegments: 1, depthSegments: 1 diff --git a/tests/src/loader/PrimitiveMeshLoader.test.ts b/tests/src/loader/PrimitiveMeshLoader.test.ts index cd17e843a2..7204a5da38 100644 --- a/tests/src/loader/PrimitiveMeshLoader.test.ts +++ b/tests/src/loader/PrimitiveMeshLoader.test.ts @@ -59,8 +59,8 @@ 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 = { keepData: true }; -const groupedOptions = { keepData: true, separateMaterials: true }; +const options = { keepCPUData: true }; +const groupedOptions = { keepCPUData: true, separateMaterialSlots: true }; describe("PrimitiveMeshLoader", () => { const defaults = { @@ -70,7 +70,7 @@ describe("PrimitiveMeshLoader", () => { create: () => PrimitiveMesh.createCuboid(engine, 1, 1, 1) }, plane: { - data: { type: "plane", planeWidth: 1, planeHeight: 1 }, + data: { type: "plane", planeWidth: 1, planeDepth: 1 }, create: () => PrimitiveMesh.createPlane(engine, 1, 1) }, cylinder: { @@ -91,7 +91,7 @@ describe("PrimitiveMeshLoader", () => { create: () => PrimitiveMesh.createCone(engine, 0.5, 2) }, capsule: { - data: { type: "capsule", capsuleRadius: 0.5, capsuleHeight: 2 }, + data: { type: "capsule", capsuleRadius: 0.5, capsuleCylinderHeight: 2 }, create: () => PrimitiveMesh.createCapsule(engine, 0.5, 2) }, torus: { @@ -136,7 +136,13 @@ describe("PrimitiveMeshLoader", () => { create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors, 1) }, torusKnot: { - data: { type: "torusKnot", torusKnotRadius: 0.5, torusKnotTubeRadius: 0.1, torusKnotP: 2, torusKnotQ: 3 }, + data: { + type: "torusKnot", + torusKnotRadius: 0.5, + torusKnotTubeRadius: 0.1, + torusKnotAxisTurns: 2, + torusKnotCrossSectionTurns: 3 + }, create: () => PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2, 3) }, roundedCuboid: { @@ -159,23 +165,23 @@ describe("PrimitiveMeshLoader", () => { sphereRadius: 2, sphereOptions: { ...options, - horizontalRange: { x: 20, y: 260 }, - verticalRange: { x: 30, y: 150 }, - subdivisions: 3 + horizontalAngleRange: { x: 20, y: 260 }, + verticalAngleRange: { x: 30, y: 150 }, + subdivisionLevel: 3 } }, create: () => PrimitiveMesh.createSphere(engine, 2, { ...options, - horizontalRange: new Vector2(20, 260), - verticalRange: new Vector2(30, 150), - subdivisions: 3 + horizontalAngleRange: new Vector2(20, 260), + verticalAngleRange: new Vector2(30, 150), + subdivisionLevel: 3 }) }, { name: "sphere", - data: { type: "sphere", sphereRadius: 1.5, sphereOptions: { ...options, subdivisions: 2 } }, - create: () => PrimitiveMesh.createSphere(engine, 1.5, { ...options, subdivisions: 2 }) + data: { type: "sphere", sphereRadius: 1.5, sphereOptions: { ...options, subdivisionLevel: 2 } }, + create: () => PrimitiveMesh.createSphere(engine, 1.5, { ...options, subdivisionLevel: 2 }) }, { name: "sphere angular ranges", @@ -184,17 +190,17 @@ describe("PrimitiveMeshLoader", () => { sphereRadius: 2, sphereOptions: { ...options, - horizontalRange: { x: 350, y: 370 }, - verticalRange: { x: 30, y: 150 }, - subdivisions: 3 + horizontalAngleRange: { x: 350, y: 370 }, + verticalAngleRange: { x: 30, y: 150 }, + subdivisionLevel: 3 } }, create: () => PrimitiveMesh.createSphere(engine, 2, { ...options, - horizontalRange: new Vector2(350, 370), - verticalRange: new Vector2(30, 150), - subdivisions: 3 + horizontalAngleRange: new Vector2(350, 370), + verticalAngleRange: new Vector2(30, 150), + subdivisionLevel: 3 }) }, { @@ -219,10 +225,10 @@ describe("PrimitiveMeshLoader", () => { data: { type: "plane", planeWidth: 3, - planeHeight: 5, - planeOptions: { ...options, horizontalSegments: 2, verticalSegments: 4 } + planeDepth: 5, + planeOptions: { ...options, widthSegments: 2, depthSegments: 4 } }, - create: () => PrimitiveMesh.createPlane(engine, 3, 5, { ...options, horizontalSegments: 2, verticalSegments: 4 }) + create: () => PrimitiveMesh.createPlane(engine, 3, 5, { ...options, widthSegments: 2, depthSegments: 4 }) }, { name: "cylinder caps and range", @@ -299,7 +305,7 @@ describe("PrimitiveMeshLoader", () => { data: { type: "capsule", capsuleRadius: 0.75, - capsuleHeight: 3, + capsuleCylinderHeight: 3, capsuleOptions: { ...options, radialSegments: 12, capSegments: 5, heightSegments: 2 } }, create: () => @@ -318,18 +324,18 @@ describe("PrimitiveMeshLoader", () => { torusTubeRadius: 0.25, torusOptions: { ...options, - tubeRange: { x: 45, y: 300 }, - angleRange: { x: 20, y: 200 }, - tubularSegments: 12, + tubeAngleRange: { x: 45, y: 300 }, + ringAngleRange: { x: 20, y: 200 }, + ringSegments: 12, radialSegments: 8 } }, create: () => PrimitiveMesh.createTorus(engine, 2, 0.25, { ...options, - tubeRange: new Vector2(45, 300), - angleRange: new Vector2(20, 200), - tubularSegments: 12, + tubeAngleRange: new Vector2(45, 300), + ringAngleRange: new Vector2(20, 200), + ringSegments: 12, radialSegments: 8 }) }, @@ -349,13 +355,13 @@ describe("PrimitiveMeshLoader", () => { type: "ring", ringOuterRadius: 2, ringInnerRadius: 0.5, - ringOptions: { ...options, angleRange: { x: 40, y: 240 }, radialSegments: 12, widthSegments: 3 } + ringOptions: { ...options, angleRange: { x: 40, y: 240 }, ringSegments: 12, widthSegments: 3 } }, create: () => PrimitiveMesh.createRing(engine, 2, 0.5, { ...options, angleRange: new Vector2(40, 240), - radialSegments: 12, + ringSegments: 12, widthSegments: 3 }) }, @@ -366,23 +372,23 @@ describe("PrimitiveMeshLoader", () => { }, { name: "tetrahedron subdivision", - data: { type: "tetrahedron", tetrahedronRadius: 2, tetrahedronOptions: { ...options, segments: 3 } }, - create: () => PrimitiveMesh.createTetrahedron(engine, 2, { ...options, segments: 3 }) + 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, segments: 2 } }, - create: () => PrimitiveMesh.createOctahedron(engine, 1.5, { ...options, segments: 2 }) + 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, segments: 3 } }, - create: () => PrimitiveMesh.createIcosahedron(engine, 2, { ...options, segments: 3 }) + 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, segments: 2 } }, - create: () => PrimitiveMesh.createDodecahedron(engine, 1.5, { ...options, segments: 2 }) + data: { type: "dodecahedron", dodecahedronRadius: 1.5, dodecahedronOptions: { ...options, edgeSegments: 2 } }, + create: () => PrimitiveMesh.createDodecahedron(engine, 1.5, { ...options, edgeSegments: 2 }) }, { name: "lathe profile and range", @@ -404,13 +410,13 @@ describe("PrimitiveMeshLoader", () => { type: "tube", tubeRadius: 0.2, tubePath: path, - tubeOptions: { ...options, closed: true, tubularSegments: 16, radialSegments: 6 } + tubeOptions: { ...options, closedPath: true, pathSegments: 16, radialSegments: 6 } }, create: () => PrimitiveMesh.createTube(engine, pathVectors, 0.2, { ...options, - closed: true, - tubularSegments: 16, + closedPath: true, + pathSegments: 16, radialSegments: 6 }) }, @@ -427,21 +433,21 @@ describe("PrimitiveMeshLoader", () => { extrusionShapes: shapes, extrusionOptions: { ...groupedOptions, - bevelSize: 0.1, - bevelThickness: 0.2, - bevelOffset: 0.2, + bevelWidth: 0.1, + bevelDepth: 0.2, + contourOffset: 0.2, bevelSegments: 2, - steps: 3 + depthSegments: 3 } }, create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors, 2, { ...groupedOptions, - bevelSize: 0.1, - bevelThickness: 0.2, - bevelOffset: 0.2, + bevelWidth: 0.1, + bevelDepth: 0.2, + contourOffset: 0.2, bevelSegments: 2, - steps: 3 + depthSegments: 3 }) }, { @@ -450,9 +456,10 @@ describe("PrimitiveMeshLoader", () => { type: "extrusion", extrusionDepth: 2, extrusionShapes: shapes, - extrusionOptions: { ...options, bevelOffset: -0.1 } + extrusionOptions: { ...options, contourOffset: -0.1 } }, - create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors, 2, { ...options, bevelOffset: -0.1, steps: 1 }) + create: () => + PrimitiveMesh.createExtrusion(engine, shapeVectors, 2, { ...options, contourOffset: -0.1, depthSegments: 1 }) }, { name: "extrusion along a path", @@ -460,9 +467,10 @@ describe("PrimitiveMeshLoader", () => { type: "extrusion", extrusionPath: path, extrusionShapes: shapes, - extrusionOptions: { ...groupedOptions, steps: 6 } + extrusionOptions: { ...groupedOptions, pathSegments: 6 } }, - create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors, pathVectors, { ...groupedOptions, steps: 6 }) + create: () => + PrimitiveMesh.createExtrusion(engine, shapeVectors, pathVectors, { ...groupedOptions, pathSegments: 6 }) }, { name: "closed extrusion path", @@ -470,10 +478,14 @@ describe("PrimitiveMeshLoader", () => { type: "extrusion", extrusionPath: path, extrusionShapes: shapes, - extrusionOptions: { ...groupedOptions, closed: true, steps: 12 } + extrusionOptions: { ...groupedOptions, closedPath: true, pathSegments: 12 } }, create: () => - PrimitiveMesh.createExtrusion(engine, shapeVectors, pathVectors, { ...groupedOptions, closed: true, steps: 12 }) + PrimitiveMesh.createExtrusion(engine, shapeVectors, pathVectors, { + ...groupedOptions, + closedPath: true, + pathSegments: 12 + }) }, { name: "linear extrusion ignores path-only settings", @@ -481,9 +493,9 @@ describe("PrimitiveMeshLoader", () => { type: "extrusion", extrusionDepth: 2, extrusionShapes: shapes, - extrusionOptions: { ...groupedOptions, steps: 2, closed: true } + extrusionOptions: { ...groupedOptions, depthSegments: 2, closedPath: true } }, - create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors, 2, { ...groupedOptions, steps: 2 }) + create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors, 2, { ...groupedOptions, depthSegments: 2 }) }, { name: "path extrusion ignores linear-only settings", @@ -493,14 +505,15 @@ describe("PrimitiveMeshLoader", () => { extrusionShapes: shapes, extrusionOptions: { ...groupedOptions, - steps: 6, - bevelSize: 0.25, - bevelThickness: 0.4, - bevelOffset: 0.5, + pathSegments: 6, + bevelWidth: 0.25, + bevelDepth: 0.4, + contourOffset: 0.5, bevelSegments: 8 } }, - create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors, pathVectors, { ...groupedOptions, steps: 6 }) + create: () => + PrimitiveMesh.createExtrusion(engine, shapeVectors, pathVectors, { ...groupedOptions, pathSegments: 6 }) }, { name: "torus knot winding", @@ -508,12 +521,12 @@ describe("PrimitiveMeshLoader", () => { type: "torusKnot", torusKnotRadius: 2, torusKnotTubeRadius: 0.2, - torusKnotP: 3, - torusKnotQ: 4, - torusKnotOptions: { ...options, tubularSegments: 48, radialSegments: 6 } + torusKnotAxisTurns: 3, + torusKnotCrossSectionTurns: 4, + torusKnotOptions: { ...options, pathSegments: 48, radialSegments: 6 } }, create: () => - PrimitiveMesh.createTorusKnot(engine, 2, 0.2, 3, 4, { ...options, tubularSegments: 48, radialSegments: 6 }) + PrimitiveMesh.createTorusKnot(engine, 2, 0.2, 3, 4, { ...options, pathSegments: 48, radialSegments: 6 }) }, { name: "negative torus knot windings", @@ -521,12 +534,12 @@ describe("PrimitiveMeshLoader", () => { type: "torusKnot", torusKnotRadius: 2, torusKnotTubeRadius: 0.2, - torusKnotP: -2, - torusKnotQ: -3, - torusKnotOptions: { ...options, tubularSegments: 48, radialSegments: 8 } + torusKnotAxisTurns: -2, + torusKnotCrossSectionTurns: -3, + torusKnotOptions: { ...options, pathSegments: 48, radialSegments: 8 } }, create: () => - PrimitiveMesh.createTorusKnot(engine, 2, 0.2, -2, -3, { ...options, tubularSegments: 48, radialSegments: 8 }) + PrimitiveMesh.createTorusKnot(engine, 2, 0.2, -2, -3, { ...options, pathSegments: 48, radialSegments: 8 }) }, { name: "rounded cuboid", @@ -536,9 +549,9 @@ describe("PrimitiveMeshLoader", () => { roundedCuboidHeight: 3, roundedCuboidDepth: 4, roundedCuboidCornerRadius: 0.2, - roundedCuboidOptions: { ...groupedOptions, segments: 3 } + roundedCuboidOptions: { ...groupedOptions, roundingSegments: 3 } }, - create: () => PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0.2, { ...groupedOptions, segments: 3 }) + create: () => PrimitiveMesh.createRoundedCuboid(engine, 2, 3, 4, 0.2, { ...groupedOptions, roundingSegments: 3 }) }, { name: "cuboid inherited defaults", @@ -547,12 +560,12 @@ describe("PrimitiveMeshLoader", () => { }, { name: "plane inherited defaults", - data: { type: "plane", planeWidth: 2, planeHeight: 2, planeOptions: { horizontalSegments: 4 } }, - create: () => PrimitiveMesh.createPlane(engine, 2, 2, { horizontalSegments: 4 }) + 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, capsuleHeight: 2, capsuleOptions: { radialSegments: 10 } }, + data: { type: "capsule", capsuleRadius: 0.5, capsuleCylinderHeight: 2, capsuleOptions: { radialSegments: 10 } }, create: () => PrimitiveMesh.createCapsule(engine, 0.5, 2, { radialSegments: 10 }) } ]; @@ -600,7 +613,7 @@ describe("PrimitiveMeshLoader", () => { const data: PrimitiveMeshAsset = { type: "sphere", sphereRadius: 0.5, - sphereOptions: { horizontalRange: { x: 350, y: 370 }, verticalRange: { x: 30, y: 150 } } + 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); @@ -609,10 +622,10 @@ describe("PrimitiveMeshLoader", () => { try { mesh = await engine.resourceManager.load({ url: "vector-ranges.mesh", type: AssetType.PrimitiveMesh }); const ranges = create.mock.calls[0][2]!; - expect(ranges.horizontalRange).toBeInstanceOf(Vector2); - expect(ranges.verticalRange).toBeInstanceOf(Vector2); - expect(ranges.horizontalRange!.toJSON()).toEqual({ x: 350, y: 370 }); - expect(ranges.verticalRange!.toJSON()).toEqual({ x: 30, y: 150 }); + 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(); @@ -638,7 +651,7 @@ describe("PrimitiveMeshLoader", () => { ? { type, cylinderRadius: 0.5, cylinderHeight: 2 } : { type, truncatedConeTopRadius: 0.25, truncatedConeBottomRadius: 0.5, truncatedConeHeight: 2 }; const data = JSON.parse( - JSON.stringify({ ...shape, [optionsKey]: { caps, keepData: true, separateMaterials: true } }) + JSON.stringify({ ...shape, [optionsKey]: { caps, keepCPUData: true, separateMaterialSlots: true } }) ); expect(data[optionsKey].caps).toBe(value); request.mockReturnValue(AssetPromise.resolve(data) as any); From 3e253f58f12571de21b44a2b09a2da1dc85a614a Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sat, 14 Nov 2026 22:02:21 +0800 Subject: [PATCH 05/24] refactor(core): clarify extruded polygon creation Rename the extrusion factory, options and serialized inputs to describe its polygon output. Distinguish flat polygons from extruded polygons in public comments and update callers, documentation and visual labels. BREAKING CHANGE: Use createExtrudedPolygon and the corresponding extrudedPolygon asset fields and option interfaces. --- docs/en/graphics/mesh/primitiveMesh.mdx | 26 +++---- docs/zh/graphics/mesh/primitiveMesh.mdx | 24 +++---- e2e/case/primitive-all.ts | 6 +- e2e/case/primitive-contours.ts | 14 ++-- e2e/case/primitive-materials.ts | 9 ++- e2e/case/primitive-topology.ts | 4 +- .../originImage/Primitive_primitive-all.jpg | 4 +- .../Primitive_primitive-materials.jpg | 4 +- .../Primitive_primitive-topology.jpg | 4 +- packages/core/src/mesh/PrimitiveMesh.ts | 29 ++++---- .../core/src/mesh/PrimitiveMeshOptions.ts | 10 +-- packages/core/src/mesh/index.ts | 4 +- .../references/mesh-geometry.md | 6 +- packages/loader/src/PrimitiveMeshAsset.ts | 20 +++--- packages/loader/src/PrimitiveMeshLoader.ts | 10 +-- .../fixtures/PrimitiveMeshApi.ts | 61 ++++++++-------- .../fixtures/PrimitiveMeshAsset.ts | 54 +++++++------- tests/src/core/mesh/ProceduralMesh.test.ts | 63 +++++++++------- tests/src/loader/PrimitiveMeshLoader.test.ts | 71 ++++++++++--------- 19 files changed, 221 insertions(+), 202 deletions(-) diff --git a/docs/en/graphics/mesh/primitiveMesh.mdx b/docs/en/graphics/mesh/primitiveMesh.mdx index 8435905751..6faa711f21 100644 --- a/docs/en/graphics/mesh/primitiveMesh.mdx +++ b/docs/en/graphics/mesh/primitiveMesh.mdx @@ -155,7 +155,7 @@ For torus knots, `axisTurns` counts revolutions around the central axis and `cro | Cylinder, frustum, cone, capsule | `createCylinder`, `createTruncatedCone`, `createCone`, `createCapsule` | | Disk, annulus, torus, torus knot | `createCircle`, `createRing`, `createTorus`, `createTorusKnot` | | Regular polyhedra | `createTetrahedron`, `createOctahedron`, `createIcosahedron`, `createDodecahedron` | -| Revolved profile, path tube, polygon, extrusion, rounded cuboid | `createLathe`, `createTube`, `createPolygon`, `createExtrusion`, `createRoundedCuboid` | +| Revolved profile, path tube, polygon, extruded polygon, rounded cuboid | `createLathe`, `createTube`, `createPolygon`, `createExtrudedPolygon`, `createRoundedCuboid` | ### Subdivisions, angles and caps @@ -186,8 +186,8 @@ import { Vector2, Vector3 } from "@galacean/engine"; 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.createExtrusion(engine, { points: outline, holes: [hole] }, 0.5); -const beveled = PrimitiveMesh.createExtrusion(engine, outline, 0.5, { +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 @@ -197,12 +197,12 @@ const path = Array.from({ length: 65 }, (_, i) => { 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.createExtrusion(engine, outline, path, { 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.createExtrusion(engine, outline, loop, { closedPath: true, pathSegments: 32 }); +const closedPath = PrimitiveMesh.createExtrudedPolygon(engine, outline, loop, { closedPath: true, pathSegments: 32 }); ``` -Extrusion requires a third argument: a numeric depth for linear extrusion, or a `Vector3` array for path extrusion. `LinearExtrusionMeshOptions` contains optional bevel settings; `PathExtrusionMeshOptions` contains optional path settings. Linear extrusion uses `depthSegments`; path extrusion uses `pathSegments`. Each interface declares its mode's settings. A path ignores bevel settings; a numeric depth ignores `closedPath`. Linear extrusion goes along +Z without bevels unless requested. A positive `bevelWidth` enables beveling; `bevelDepth` defaults to the same value. Path extrusion does not generate bevels. Paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points before creating the mesh, as shown above. +`createExtrudedPolygon` requires a third argument: a numeric depth for linear extrusion, or a `Vector3` array for path extrusion. `LinearExtrudedPolygonMeshOptions` contains optional bevel settings; `PathExtrudedPolygonMeshOptions` contains optional path settings. Linear extrusion uses `depthSegments`; path extrusion uses `pathSegments`. Each interface declares its mode's settings. A path ignores bevel settings; a numeric depth ignores `closedPath`. Linear extrusion goes along +Z without bevels unless requested. A positive `bevelWidth` enables beveling; `bevelDepth` defaults to the same value. Path extrusion does not generate bevels. Paths accept `Vector3` arrays and 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. @@ -232,7 +232,7 @@ const sixMaterials = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { | 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 | -| Extrusion | Both end caps, then all walls and bevels, per shape; closed paths have one wall slot per shape | +| 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. @@ -269,7 +269,7 @@ Each `type` selects the matching `PrimitiveMesh.createX` method. Type-prefixed f | `lathe` | `latheProfile` | | `tube` | `tubePath`, `tubeRadius` | | `polygon` | `polygonShapes` | -| `extrusion` | `extrusionShapes`, plus `extrusionDepth` or `extrusionPath` | +| `extrudedPolygon` | `extrudedPolygonShapes`, plus `extrudedPolygonDepth` or `extrudedPolygonPath` | | `torusKnot` | `torusKnotRadius`, `torusKnotTubeRadius`, `torusKnotAxisTurns`, `torusKnotCrossSectionTurns` | | `roundedCuboid` | `roundedCuboidWidth`, `roundedCuboidHeight`, `roundedCuboidDepth`, `roundedCuboidCornerRadius` | @@ -279,8 +279,8 @@ Profiles and polygon contours store `{ x, y }` points; paths store `{ x, y, z }` ```json { - "type": "extrusion", - "extrusionShapes": [ + "type": "extrudedPolygon", + "extrudedPolygonShapes": [ { "points": [ { "x": -2, "y": -2 }, @@ -298,11 +298,11 @@ Profiles and polygon contours store `{ x, y }` points; paths store `{ x, y, z }` ] } ], - "extrusionDepth": 2, - "extrusionOptions": { "bevelWidth": 0.1, "contourOffset": 0.2, "separateMaterialSlots": true } + "extrudedPolygonDepth": 2, + "extrudedPolygonOptions": { "bevelWidth": 0.1, "contourOffset": 0.2, "separateMaterialSlots": true } } ``` -Path extrusion uses the required `extrusionPath` field instead of `extrusionDepth` and ignores bevel settings. Set `extrusionOptions.closedPath` to `true` for a closed path without end caps. Save path points as `{ x, y, z }`. +Path extrusion uses the required `extrudedPolygonPath` field instead of `extrudedPolygonDepth` and ignores bevel settings. Set `extrudedPolygonOptions.closedPath` to `true` for a closed path without end caps. Save path points as `{ x, y, z }`. The type-prefixed fields, including `Options`, pass through the Editor's primitive asset bundler. Editor previews should select the same creation method and parameters as the saved asset. diff --git a/docs/zh/graphics/mesh/primitiveMesh.mdx b/docs/zh/graphics/mesh/primitiveMesh.mdx index adfb213d6f..183121f598 100644 --- a/docs/zh/graphics/mesh/primitiveMesh.mdx +++ b/docs/zh/graphics/mesh/primitiveMesh.mdx @@ -159,7 +159,7 @@ const mirroredKnot = PrimitiveMesh.createTorusKnot(engine, 1, 0.1, 2, -3); | 圆柱、圆台、圆锥、胶囊 | `createCylinder`、`createTruncatedCone`、`createCone`、`createCapsule` | | 圆盘、圆环面、圆环体、环面结 | `createCircle`、`createRing`、`createTorus`、`createTorusKnot` | | 四面体、八面体、二十面体、十二面体 | `createTetrahedron`、`createOctahedron`、`createIcosahedron`、`createDodecahedron` | -| 旋转体、路径管道、平面多边形、拉伸、圆角长方体 | `createLathe`、`createTube`、`createPolygon`、`createExtrusion`、`createRoundedCuboid` | +| 旋转体、路径管道、平面多边形、挤出多边形、圆角长方体 | `createLathe`、`createTube`、`createPolygon`、`createExtrudedPolygon`、`createRoundedCuboid` | ### 分段、角度和端盖 @@ -191,8 +191,8 @@ const outline = [new Vector2(-2, -2), new Vector2(2, -2), new Vector2(2, 2), new 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.createExtrusion(engine, { points: outline, holes: [hole] }, 0.5); -const beveled = PrimitiveMesh.createExtrusion(engine, outline, 0.5, { +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 @@ -203,12 +203,12 @@ const path = Array.from({ length: 65 }, (_, i) => { 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.createExtrusion(engine, outline, path, { 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.createExtrusion(engine, outline, loop, { closedPath: true, pathSegments: 32 }); +const closedPath = PrimitiveMesh.createExtrudedPolygon(engine, outline, loop, { closedPath: true, pathSegments: 32 }); ``` -拉伸的第三个参数必填:传入数值深度时沿 +Z 直线拉伸,传入 `Vector3` 数组时沿路径挤出。`LinearExtrusionMeshOptions` 包含可选的倒角设置,`PathExtrusionMeshOptions` 包含可选的路径设置。直线拉伸用 `depthSegments`,路径拉伸用 `pathSegments`;两个接口分别声明各自模式的设置。沿路径挤出时忽略倒角设置;直线拉伸时忽略 `closedPath`。直线拉伸默认不倒角;`bevelWidth > 0` 时开启倒角,`bevelDepth` 默认等于 `bevelWidth`。沿路径拉伸不生成倒角。路径接收 `Vector3` 数组,并按折线长度均匀采样。使用曲线时,在外层采样成点数组后传入,如上例所示。 +`createExtrudedPolygon` 的第三个参数必填:传入数值深度时沿 +Z 直线拉伸,传入 `Vector3` 数组时沿路径挤出。`LinearExtrudedPolygonMeshOptions` 包含可选的倒角设置,`PathExtrudedPolygonMeshOptions` 包含可选的路径设置。直线拉伸用 `depthSegments`,路径拉伸用 `pathSegments`;两个接口分别声明各自模式的设置。沿路径挤出时忽略倒角设置;直线拉伸时忽略 `closedPath`。直线拉伸默认不倒角;`bevelWidth > 0` 时开启倒角,`bevelDepth` 默认等于 `bevelWidth`。沿路径拉伸不生成倒角。路径接收 `Vector3` 数组,并按折线长度均匀采样。使用曲线时,在外层采样成点数组后传入,如上例所示。 管道和路径挤出的 `closedPath` 默认关闭;开启后自动连接路径首尾并对齐截面,不必重复首点。闭合挤出至少使用三段,不生成端盖。开放挤出保留两端端盖;管道在两种模式下都不生成端盖。 @@ -275,7 +275,7 @@ const asset = { | `lathe` | `latheProfile` | | `tube` | `tubePath`、`tubeRadius` | | `polygon` | `polygonShapes` | -| `extrusion` | `extrusionShapes`,以及 `extrusionDepth` 或 `extrusionPath` | +| `extrudedPolygon` | `extrudedPolygonShapes`,以及 `extrudedPolygonDepth` 或 `extrudedPolygonPath` | | `torusKnot` | `torusKnotRadius`、`torusKnotTubeRadius`、`torusKnotAxisTurns`、`torusKnotCrossSectionTurns` | | `roundedCuboid` | `roundedCuboidWidth`、`roundedCuboidHeight`、`roundedCuboidDepth`、`roundedCuboidCornerRadius` | @@ -285,8 +285,8 @@ const asset = { ```json { - "type": "extrusion", - "extrusionShapes": [ + "type": "extrudedPolygon", + "extrudedPolygonShapes": [ { "points": [ { "x": -2, "y": -2 }, @@ -304,11 +304,11 @@ const asset = { ] } ], - "extrusionDepth": 2, - "extrusionOptions": { "bevelWidth": 0.1, "contourOffset": 0.2, "separateMaterialSlots": true } + "extrudedPolygonDepth": 2, + "extrudedPolygonOptions": { "bevelWidth": 0.1, "contourOffset": 0.2, "separateMaterialSlots": true } } ``` -沿路径拉伸通过必填的 `extrusionPath` 代替 `extrusionDepth`,并忽略倒角设置。`extrusionOptions.closedPath` 设为 `true` 时闭合路径且不生成端盖。路径点保存为 `{ x, y, z }`。 +沿路径拉伸通过必填的 `extrudedPolygonPath` 代替 `extrudedPolygonDepth`,并忽略倒角设置。`extrudedPolygonOptions.closedPath` 设为 `true` 时闭合路径且不生成端盖。路径点保存为 `{ x, y, z }`。 以上类型前缀字段及 `Options` 都能经过 Editor 现有的基础网格打包过滤。Editor 预览应使用与保存资产相同的创建方法和参数。 diff --git a/e2e/case/primitive-all.ts b/e2e/case/primitive-all.ts index 144a88bf7f..caca497d45 100644 --- a/e2e/case/primitive-all.ts +++ b/e2e/case/primitive-all.ts @@ -154,9 +154,9 @@ class PrimitiveMeshGallery { mesh: PrimitiveMesh.createTube(engine, path, 0.2, { pathSegments: 48, radialSegments: 10 }) }, polygon: { label: "Polygon", mesh: PrimitiveMesh.createPolygon(engine, polygon), rotation: new Vector3() }, - extrusion: { - label: "Extrusion", - mesh: PrimitiveMesh.createExtrusion(engine, polygon, 0.6, { + extrudedPolygon: { + label: "Extruded polygon", + mesh: PrimitiveMesh.createExtrudedPolygon(engine, polygon, 0.6, { bevelWidth: 0.1, bevelDepth: 0.1, bevelSegments: 3, diff --git a/e2e/case/primitive-contours.ts b/e2e/case/primitive-contours.ts index 52efffa1c9..734c20b166 100644 --- a/e2e/case/primitive-contours.ts +++ b/e2e/case/primitive-contours.ts @@ -66,12 +66,12 @@ class PrimitiveContours { { label: "Straight extrusion", detail: "depth: 0.6 / no bevel", - mesh: PrimitiveMesh.createExtrusion(engine, polygon, 0.6) + mesh: PrimitiveMesh.createExtrudedPolygon(engine, polygon, 0.6) }, { label: "Independent bevel depth", detail: "bevel width: 0.16 / depth: 0.06", - mesh: PrimitiveMesh.createExtrusion(engine, polygon, 0.6, { + mesh: PrimitiveMesh.createExtrudedPolygon(engine, polygon, 0.6, { bevelWidth: 0.16, bevelDepth: 0.06, bevelSegments: 4 @@ -80,12 +80,12 @@ class PrimitiveContours { { label: "Expanded contour", detail: "offset: +0.15 / no bevel", - mesh: PrimitiveMesh.createExtrusion(engine, polygon, 0.6, { contourOffset: 0.15 }) + mesh: PrimitiveMesh.createExtrudedPolygon(engine, polygon, 0.6, { contourOffset: 0.15 }) }, { label: "Contracted contour", detail: "contourOffset: -0.15", - mesh: PrimitiveMesh.createExtrusion(engine, polygon, 0.6, { contourOffset: -0.15, bevelWidth: 0.08 }) + mesh: PrimitiveMesh.createExtrudedPolygon(engine, polygon, 0.6, { contourOffset: -0.15, bevelWidth: 0.08 }) }, { label: "Open tube", @@ -100,17 +100,17 @@ class PrimitiveContours { { label: "Open profile sweep", detail: "pathSegments: 48", - mesh: PrimitiveMesh.createExtrusion(engine, smallProfile, path, { pathSegments: 48 }) + mesh: PrimitiveMesh.createExtrudedPolygon(engine, smallProfile, path, { pathSegments: 48 }) }, { label: "Closed profile sweep", detail: "closedPath: true / no caps", - mesh: PrimitiveMesh.createExtrusion(engine, smallProfile, loop, { pathSegments: 64, closedPath: true }) + mesh: PrimitiveMesh.createExtrudedPolygon(engine, smallProfile, loop, { pathSegments: 64, closedPath: true }) }, { label: "Hollow profile sweep", detail: "path + inner contour", - mesh: PrimitiveMesh.createExtrusion(engine, smallHoleProfile, path, { pathSegments: 48 }) + mesh: PrimitiveMesh.createExtrudedPolygon(engine, smallHoleProfile, path, { pathSegments: 48 }) } ], 4 diff --git a/e2e/case/primitive-materials.ts b/e2e/case/primitive-materials.ts index a952e193de..7411b6a587 100644 --- a/e2e/case/primitive-materials.ts +++ b/e2e/case/primitive-materials.ts @@ -65,15 +65,18 @@ class PrimitiveMaterials { rotation: new Vector3() }, { - label: "Extrusion / cap and wall", + label: "Extruded / cap and wall", detail: "caps / walls + bevels", - mesh: PrimitiveMesh.createExtrusion(engine, square, 0.6, { bevelWidth: 0.12, separateMaterialSlots: true }), + 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.createExtrusion(engine, profiles, loop, { + mesh: PrimitiveMesh.createExtrudedPolygon(engine, profiles, loop, { pathSegments: 64, closedPath: true, separateMaterialSlots: true diff --git a/e2e/case/primitive-topology.ts b/e2e/case/primitive-topology.ts index 42f688c402..9e21670480 100644 --- a/e2e/case/primitive-topology.ts +++ b/e2e/case/primitive-topology.ts @@ -153,9 +153,9 @@ class PrimitiveTopology { ) }, { - label: "Extrusion / bevel layers", + label: "Extruded / bevel layers", detail: "segments: depth 3 / bevel 3", - mesh: PrimitiveMesh.createExtrusion( + mesh: PrimitiveMesh.createExtrudedPolygon( engine, [new Vector2(-1, -1), new Vector2(1, -1), new Vector2(1, 1), new Vector2(-1, 1)], 0.6, diff --git a/e2e/fixtures/originImage/Primitive_primitive-all.jpg b/e2e/fixtures/originImage/Primitive_primitive-all.jpg index db81641721..17247bbfc6 100644 --- a/e2e/fixtures/originImage/Primitive_primitive-all.jpg +++ b/e2e/fixtures/originImage/Primitive_primitive-all.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b02da204a75e866639aa4fe5c99d68cb2bfcac9256abcd4a4dfd7fd2a42ca194 -size 443010 +oid sha256:5a5451a1a54c15f343174a41a6df8d3329c4223661b6e53d422eee7267819fe2 +size 444327 diff --git a/e2e/fixtures/originImage/Primitive_primitive-materials.jpg b/e2e/fixtures/originImage/Primitive_primitive-materials.jpg index ebf2172d7e..acf3a14b95 100644 --- a/e2e/fixtures/originImage/Primitive_primitive-materials.jpg +++ b/e2e/fixtures/originImage/Primitive_primitive-materials.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:100ab05dd2b58de830e0b08c42cc6b173569d67d9d66fc1543a9cf2e67cbf18e -size 522098 +oid sha256:cf803d113676191953da120cb1ddfc0780509ceadcb1609e75f701347fa002a5 +size 522020 diff --git a/e2e/fixtures/originImage/Primitive_primitive-topology.jpg b/e2e/fixtures/originImage/Primitive_primitive-topology.jpg index 33c2cc1be2..e38134e64e 100644 --- a/e2e/fixtures/originImage/Primitive_primitive-topology.jpg +++ b/e2e/fixtures/originImage/Primitive_primitive-topology.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:76731932960417066b5c7099d25ddf69bccec4e0405084430391318cd7b1d45e -size 825311 +oid sha256:968497a7df5b18572acb61d912ead20c443c415631920b6b7e3d334c4fe52319 +size 825397 diff --git a/packages/core/src/mesh/PrimitiveMesh.ts b/packages/core/src/mesh/PrimitiveMesh.ts index c65790bb4a..f358f0a7f7 100644 --- a/packages/core/src/mesh/PrimitiveMesh.ts +++ b/packages/core/src/mesh/PrimitiveMesh.ts @@ -20,8 +20,8 @@ import type { LatheMeshOptions, TubeMeshOptions, PolygonMeshOptions, - LinearExtrusionMeshOptions, - PathExtrusionMeshOptions, + LinearExtrudedPolygonMeshOptions, + PathExtrudedPolygonMeshOptions, TorusKnotMeshOptions, RoundedCuboidMeshOptions, PolygonShape @@ -530,11 +530,11 @@ export class PrimitiveMesh { } /** - * Triangulate one or more polygons in XY facing +Z. + * Create a zero-thickness polygon mesh in the XY plane, facing +Z. * @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 generated mesh + * @returns The triangulated polygon mesh without side walls */ static createPolygon( engine: Engine, @@ -550,21 +550,22 @@ export class PrimitiveMesh { } /** - * Extrude polygons along +Z or a spatial path. + * Create an extruded polygon mesh with side walls along +Z or a spatial path. * @remarks - * A path selects path extrusion and ignores bevel settings. - * A numeric depth extrudes along +Z and ignores `closedPath`. + * A numeric depth extrudes the contours along +Z and ignores `closedPath`. + * A path sweeps the contours along its points and ignores bevel settings. + * Open extrusions include both end caps; closed paths have no end caps. * @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 depthOrPath - The total depth along +Z, including bevels, or the path points with at least two distinct points + * @param depthOrPath - The total extrusion depth in local units, including bevels, or a path with at least two distinct points * @param options - Linear or path extrusion settings - * @returns The generated mesh + * @returns The extruded polygon mesh with side walls and any end caps */ - static createExtrusion( + static createExtrudedPolygon( engine: Engine, shapes: readonly Vector2[] | PolygonShape | readonly PolygonShape[], depthOrPath: number | readonly Vector3[], - options: LinearExtrusionMeshOptions | PathExtrusionMeshOptions = {} + options: LinearExtrudedPolygonMeshOptions | PathExtrudedPolygonMeshOptions = {} ): ModelMesh { const { depthSegments = 1, @@ -574,12 +575,12 @@ export class PrimitiveMesh { bevelDepth = bevelWidth, contourOffset = 0, bevelSegments = 3 - }: LinearExtrusionMeshOptions & PathExtrusionMeshOptions = options; + }: LinearExtrudedPolygonMeshOptions & PathExtrudedPolygonMeshOptions = options; const path = typeof depthOrPath === "number" ? undefined : depthOrPath; const depth = typeof depthOrPath === "number" ? depthOrPath : 0; return PrimitiveMesh._createMesh( engine, - PrimitiveMesh._createExtrusionData, + PrimitiveMesh._createExtrudedPolygonData, [ PrimitiveMesh._polygons(shapes), depth, @@ -1458,7 +1459,7 @@ export class PrimitiveMesh { return data; } - private static _createExtrusionData( + private static _createExtrudedPolygonData( shapes: readonly PolygonShape[], depth: number, stepCount: number, diff --git a/packages/core/src/mesh/PrimitiveMeshOptions.ts b/packages/core/src/mesh/PrimitiveMeshOptions.ts index f451884275..f373fb2872 100644 --- a/packages/core/src/mesh/PrimitiveMeshOptions.ts +++ b/packages/core/src/mesh/PrimitiveMeshOptions.ts @@ -329,7 +329,7 @@ export interface TubeMeshOptions extends PrimitiveMeshOptions { } /** - * Settings for triangulating polygons in XY facing +Z. + * Settings for a zero-thickness polygon mesh in XY facing +Z. */ export interface PolygonMeshOptions extends PrimitiveMeshOptions { /** @@ -340,9 +340,9 @@ export interface PolygonMeshOptions extends PrimitiveMeshOptions { } /** - * Settings for extruding polygons along +Z. + * Settings for extruding polygon contours along +Z. */ -export interface LinearExtrusionMeshOptions extends PrimitiveMeshOptions { +export interface LinearExtrudedPolygonMeshOptions extends PrimitiveMeshOptions { /** * The number of subdivisions along the extrusion, rounded down with a minimum of 1. * @defaultValue `1` @@ -378,10 +378,10 @@ export interface LinearExtrusionMeshOptions extends PrimitiveMeshOptions { } /** - * Settings for extruding polygons along a polyline, without bevels. + * 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 PathExtrusionMeshOptions extends PrimitiveMeshOptions { +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. diff --git a/packages/core/src/mesh/index.ts b/packages/core/src/mesh/index.ts index a04efc11e3..ebd364f44a 100644 --- a/packages/core/src/mesh/index.ts +++ b/packages/core/src/mesh/index.ts @@ -23,8 +23,8 @@ export type { TorusKnotMeshOptions, RoundedCuboidMeshOptions, PolygonShape, - LinearExtrusionMeshOptions, - PathExtrusionMeshOptions + LinearExtrudedPolygonMeshOptions, + PathExtrudedPolygonMeshOptions } from "./PrimitiveMeshOptions"; export { Skin } from "./Skin"; export { SkinnedMeshRenderer } from "./SkinnedMeshRenderer"; diff --git a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md index f923af5580..2c54cf0e23 100644 --- a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md +++ b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md @@ -61,7 +61,7 @@ Angles use degrees. Ranges use `Vector2`, with `x` as the start angle and `y` as `createSphere(engine, radius, { subdivisionLevel, horizontalAngleRange, verticalAngleRange })` projects a subdivided cube onto a sphere. The subdivision level defaults to 3 and is clamped to 1 through 6. It accepts `horizontalAngleRange` and `verticalAngleRange`. These clip the subdivided surface and leave open boundaries. Horizontal angles start at -X towards +Z, and vertical angles start at +Y. Continuous horizontal intervals such as `new Vector2(350, 370)` cross the seam. Complete spheres and sections use the same subdivision level. -Additional generators include circle, ring, four regular polyhedra, lathe, tube, polygon, extrusion, torus knot and rounded cuboid. Angle ranges belong to options. Rings require the outer radius first, followed by the inner radius. Contours and lathe profiles use `Vector2` arrays; paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points outside the mesh API. A simple polygon is a point array; holes use `{ points, holes }`. Extrusion takes a required numeric depth or `Vector3` path as its third argument, followed by `LinearExtrusionMeshOptions` or `PathExtrusionMeshOptions`. Linear extrusion uses `depthSegments`; path extrusion uses `pathSegments`. Each interface declares its mode's optional settings. A path selects path extrusion and ignores bevel settings; a numeric depth extrudes along +Z and ignores `closedPath`. Straight extrusion defaults to no bevel; a positive `bevelWidth` enables it, with `bevelDepth` defaulting to the same value. Path extrusion has no bevels. +Additional generators include circle, ring, four regular polyhedra, lathe, tube, polygon, extrusion, torus knot and rounded cuboid. Angle ranges belong to options. Rings require the outer radius first, followed by the inner radius. Contours and lathe profiles use `Vector2` arrays; paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points outside the mesh API. A simple polygon is a point array; holes use `{ points, holes }`. Extrusion takes a required numeric depth or `Vector3` path as its third argument, followed by `LinearExtrudedPolygonMeshOptions` or `PathExtrudedPolygonMeshOptions`. Linear extrusion uses `depthSegments`; path extrusion uses `pathSegments`. Each interface declares its mode's optional settings. A path selects path extrusion and ignores bevel settings; a numeric depth extrudes along +Z and ignores `closedPath`. Straight extrusion defaults to no bevel; a positive `bevelWidth` enables it, with `bevelDepth` defaulting to the same value. Path extrusion has no bevels. For straight extrusion, `contourOffset` shifts the side-wall outline and defaults to `0`. Positive values expand the solid and contract holes; negative values do the reverse. The offset also applies when `bevelWidth` is `0`. Bevels are cut into the shifted outline and included in the total `depth`. @@ -71,10 +71,10 @@ Mesh settings share the same options object. `keepCPUData` retains readable CPU ## Serializable primitive assets -`PrimitiveMeshAsset` is exported from `@galacean/engine` and `@galacean/engine-loader` and covers every `PrimitiveMesh.createX` method. Each asset `type` uses the matching lower-camel name: `sphere`, `cuboid`, `plane`, `cylinder`, `truncatedCone`, `cone`, `capsule`, `torus`, `circle`, `ring`, `tetrahedron`, `octahedron`, `icosahedron`, `dodecahedron`, `lathe`, `tube`, `polygon`, `extrusion`, `torusKnot`, `roundedCuboid`. +`PrimitiveMeshAsset` is exported from `@galacean/engine` and `@galacean/engine-loader` and covers every `PrimitiveMesh.createX` method. Each asset `type` uses the matching lower-camel name: `sphere`, `cuboid`, `plane`, `cylinder`, `truncatedCone`, `cone`, `capsule`, `torus`, `circle`, `ring`, `tetrahedron`, `octahedron`, `icosahedron`, `dodecahedron`, `lathe`, `tube`, `polygon`, `extrudedPolygon`, `torusKnot`, `roundedCuboid`. JSON keeps the type prefix for required geometry inputs and the optional settings object: `{ type: "sphere", sphereRadius: 1, sphereOptions: { subdivisionLevel: 3, keepCPUData: true } }`. Each `Options` uses the factory's named configuration fields and omitted defaults. Angular ranges store `Vector2` components as `{ x, y }`, for example `{ type: "circle", circleRadius: 1, circleOptions: { angleRange: { x: 30, y: 180 } } }`. `sphere` uses the subdivided-cube algorithm; `sphereOptions.subdivisionLevel` sets its subdivision level. `cylinderRadius` controls both end radii; unequal radii use `truncatedConeTopRadius` and `truncatedConeBottomRadius`. TypeScript assets use `PrimitiveMeshCapMode` for `caps`; JSON stores its string values `"both"`, `"top"`, `"bottom"`, `"none"`. -Serialized profiles and contours use `{ x, y }`; paths use `{ x, y, z }`. `polygonShapes` and `extrusionShapes` are arrays of `{ points, holes? }`. Straight extrusion requires `extrusionDepth`; path extrusion requires `extrusionPath` and ignores bevel settings. Set `extrusionOptions.closedPath` to `true` for a closed path without end caps. Editor previews and saved assets must select the same factory and parameters. +Serialized profiles and contours use `{ x, y }`; paths use `{ x, y, z }`. `polygonShapes` and `extrudedPolygonShapes` are arrays of `{ points, holes? }`. Straight extrusion requires `extrudedPolygonDepth`; path extrusion requires `extrudedPolygonPath` and ignores bevel settings. Set `extrudedPolygonOptions.closedPath` to `true` for a closed path without end caps. Editor previews and saved assets must select the same factory and parameters. diff --git a/packages/loader/src/PrimitiveMeshAsset.ts b/packages/loader/src/PrimitiveMeshAsset.ts index c63b65e7d8..31fad4b85e 100644 --- a/packages/loader/src/PrimitiveMeshAsset.ts +++ b/packages/loader/src/PrimitiveMeshAsset.ts @@ -5,8 +5,8 @@ import type { CuboidMeshOptions, CylinderMeshOptions, LatheMeshOptions, - LinearExtrusionMeshOptions, - PathExtrusionMeshOptions, + LinearExtrudedPolygonMeshOptions, + PathExtrudedPolygonMeshOptions, PlaneMeshOptions, PolygonMeshOptions, RegularPolyhedronMeshOptions, @@ -209,22 +209,22 @@ export type PrimitiveMeshAsset = polygonOptions?: PolygonMeshOptions; } | { - type: "extrusion"; + type: "extrudedPolygon"; /** * The total extrusion depth in local units, including both bevels. */ - extrusionDepth: number; - extrusionShapes: readonly SerializedPolygonShape[]; - extrusionOptions?: LinearExtrusionMeshOptions | PathExtrusionMeshOptions; + extrudedPolygonDepth: number; + extrudedPolygonShapes: readonly SerializedPolygonShape[]; + extrudedPolygonOptions?: LinearExtrudedPolygonMeshOptions | PathExtrudedPolygonMeshOptions; } | { - type: "extrusion"; + type: "extrudedPolygon"; /** * The path points in local coordinates. */ - extrusionPath: readonly { x: number; y: number; z: number }[]; - extrusionShapes: readonly SerializedPolygonShape[]; - extrusionOptions?: LinearExtrusionMeshOptions | PathExtrusionMeshOptions; + extrudedPolygonPath: readonly { x: number; y: number; z: number }[]; + extrudedPolygonShapes: readonly SerializedPolygonShape[]; + extrudedPolygonOptions?: LinearExtrudedPolygonMeshOptions | PathExtrudedPolygonMeshOptions; } | { type: "torusKnot"; diff --git a/packages/loader/src/PrimitiveMeshLoader.ts b/packages/loader/src/PrimitiveMeshLoader.ts index 4bd65c4398..a895d4147c 100644 --- a/packages/loader/src/PrimitiveMeshLoader.ts +++ b/packages/loader/src/PrimitiveMeshLoader.ts @@ -94,12 +94,12 @@ class PrimitiveMeshLoader extends Loader { 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 "extrusion": - return PrimitiveMesh.createExtrusion( + case "extrudedPolygon": + return PrimitiveMesh.createExtrudedPolygon( engine, - this._parseShapes(data.extrusionShapes), - "extrusionPath" in data ? this._parseVector3s(data.extrusionPath) : data.extrusionDepth, - data.extrusionOptions + this._parseShapes(data.extrudedPolygonShapes), + "extrudedPolygonPath" in data ? this._parseVector3s(data.extrudedPolygonPath) : data.extrudedPolygonDepth, + data.extrudedPolygonOptions ); case "torusKnot": return PrimitiveMesh.createTorusKnot( diff --git a/tests/package-consumer/fixtures/PrimitiveMeshApi.ts b/tests/package-consumer/fixtures/PrimitiveMeshApi.ts index 437093c6ba..9e22efb0dd 100644 --- a/tests/package-consumer/fixtures/PrimitiveMeshApi.ts +++ b/tests/package-consumer/fixtures/PrimitiveMeshApi.ts @@ -6,8 +6,8 @@ import type { CuboidMeshOptions, CylinderMeshOptions, LatheMeshOptions, - LinearExtrusionMeshOptions, - PathExtrusionMeshOptions, + LinearExtrudedPolygonMeshOptions, + PathExtrudedPolygonMeshOptions, PlaneMeshOptions, PolygonMeshOptions, PrimitiveMeshOptions, @@ -104,7 +104,7 @@ const tubeOptions = { keepCPUData: true } satisfies TubeMeshOptions; const polygonOptions = { separateMaterialSlots: true, keepCPUData: true } satisfies PolygonMeshOptions; -const linearExtrusionOptions = { +const linearExtrudedPolygonOptions = { depthSegments: 4, bevelWidth: 0.1, bevelDepth: 0.2, @@ -112,20 +112,21 @@ const linearExtrusionOptions = { bevelSegments: 3, separateMaterialSlots: true, keepCPUData: true -} satisfies LinearExtrusionMeshOptions; +} satisfies LinearExtrudedPolygonMeshOptions; const torusKnotOptions = { pathSegments: 64, radialSegments: 12, keepCPUData: true } satisfies TorusKnotMeshOptions; const roundedCuboidOptions = { roundingSegments: 4, separateMaterialSlots: true, keepCPUData: true } satisfies RoundedCuboidMeshOptions; -const pathExtrusionOptions = { +const pathExtrudedPolygonOptions = { pathSegments: 32, closedPath: true, separateMaterialSlots: true, keepCPUData: true -} satisfies PathExtrusionMeshOptions; -const extrusionOptions: LinearExtrusionMeshOptions | PathExtrusionMeshOptions = pathExtrusionOptions; +} satisfies PathExtrudedPolygonMeshOptions; +const extrudedPolygonOptions: LinearExtrudedPolygonMeshOptions | PathExtrudedPolygonMeshOptions = + pathExtrudedPolygonOptions; // Every factory lists its required inputs and a configuration containing all optional fields const meshes: ModelMesh[] = [ @@ -163,27 +164,27 @@ const meshes: ModelMesh[] = [ PrimitiveMesh.createTube(engine, path, 0.1, tubeOptions), PrimitiveMesh.createPolygon(engine, contour), PrimitiveMesh.createPolygon(engine, contour, polygonOptions), - PrimitiveMesh.createExtrusion(engine, contour, 1), - PrimitiveMesh.createExtrusion(engine, contour, 2, linearExtrusionOptions), + 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.createExtrusion(engine, polygon, 2), - PrimitiveMesh.createExtrusion(engine, polygon, 2, linearExtrusionOptions), + PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2), + PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, linearExtrudedPolygonOptions), PrimitiveMesh.createPolygon(engine, polygons), PrimitiveMesh.createPolygon(engine, polygons, polygonOptions), - PrimitiveMesh.createExtrusion(engine, polygons, 2), - PrimitiveMesh.createExtrusion(engine, polygons, 2, linearExtrusionOptions), - PrimitiveMesh.createExtrusion(engine, contour, path), - PrimitiveMesh.createExtrusion(engine, contour, path, pathExtrusionOptions), - PrimitiveMesh.createExtrusion(engine, polygon, path), - PrimitiveMesh.createExtrusion(engine, polygon, path, pathExtrusionOptions), - PrimitiveMesh.createExtrusion(engine, polygons, path), - PrimitiveMesh.createExtrusion(engine, polygons, path, pathExtrusionOptions), - PrimitiveMesh.createExtrusion(engine, polygons, path, extrusionOptions), + 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 }), @@ -226,7 +227,7 @@ 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.createExtrusion(engine, contour); +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 @@ -263,7 +264,7 @@ 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.createExtrusion(engine, contour, 1, { depth: 1 }); +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 @@ -297,15 +298,15 @@ PrimitiveMesh.createCylinder(engine, 0.5, 2, { caps: "top" }); PrimitiveMesh.createTruncatedCone(engine, 0.25, 0.5, 2, { caps: "none" }); // Fields from the inactive mode follow normal structural compatibility -PrimitiveMesh.createExtrusion(engine, polygon, path, { bevelWidth: 0.1 }); -PrimitiveMesh.createExtrusion(engine, polygon, path, { contourOffset: 0.1 }); -PrimitiveMesh.createExtrusion(engine, polygon, 2, { closedPath: true }); +PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, { bevelWidth: 0.1 }); +PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, { contourOffset: 0.1 }); +PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { closedPath: true }); // @ts-expect-error Bevel offsets use numeric local units -PrimitiveMesh.createExtrusion(engine, polygon, 2, { contourOffset: "0.1" }); +PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { contourOffset: "0.1" }); // @ts-expect-error Explicit linear settings do not declare path closure -const invalidLinearOptions: LinearExtrusionMeshOptions = { closedPath: true }; +const invalidLinearOptions: LinearExtrudedPolygonMeshOptions = { closedPath: true }; // @ts-expect-error Explicit path settings do not declare bevels -const invalidPathOptions: PathExtrusionMeshOptions = { bevelWidth: 0.1 }; +const invalidPathOptions: PathExtrudedPolygonMeshOptions = { bevelWidth: 0.1 }; const samplePath = (t: number, out: Vector3): void => { out.set(t, t * t, 0); @@ -313,7 +314,7 @@ const samplePath = (t: number, out: Vector3): void => { // @ts-expect-error Tube paths accept point arrays PrimitiveMesh.createTube(engine, samplePath, 0.1); // @ts-expect-error Extrusion paths accept point arrays -PrimitiveMesh.createExtrusion(engine, polygon, samplePath); +PrimitiveMesh.createExtrudedPolygon(engine, polygon, samplePath); const serializedContour = [ { x: 0, y: 0 }, @@ -333,4 +334,4 @@ 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.createExtrusion(engine, polygon, serializedPath); +PrimitiveMesh.createExtrudedPolygon(engine, polygon, serializedPath); diff --git a/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts index 288ba1d879..89ba95628e 100644 --- a/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts +++ b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts @@ -46,17 +46,17 @@ const shapes = [ const tube: PrimitiveMeshAsset = { type: "tube", tubeRadius: 0.5, tubePath: path, tubeOptions: { closedPath: true } }; const polygon: PrimitiveMeshAsset = { type: "polygon", polygonShapes: shapes }; -const extrusion: PrimitiveMeshAsset = { - type: "extrusion", - extrusionDepth: 2, - extrusionShapes: shapes, - extrusionOptions: { bevelWidth: 0.1, contourOffset: 0.2, separateMaterialSlots: true } +const extrudedPolygon: PrimitiveMeshAsset = { + type: "extrudedPolygon", + extrudedPolygonDepth: 2, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { bevelWidth: 0.1, contourOffset: 0.2, separateMaterialSlots: true } }; const pathExtrusion: PrimitiveMeshAsset = { - type: "extrusion", - extrusionPath: path, - extrusionShapes: shapes, - extrusionOptions: { closedPath: true } + type: "extrudedPolygon", + extrudedPolygonPath: path, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { closedPath: true } }; const torusKnot: PrimitiveMeshAsset = { type: "torusKnot", @@ -88,28 +88,28 @@ const callbackPath: PrimitiveMeshAsset = { type: "tube", tubeRadius: 0.5, tubePa // @ts-expect-error A polygon asset needs its contours const missingShapes: PrimitiveMeshAsset = { type: "polygon" }; const mixedExtrusion: PrimitiveMeshAsset = { - type: "extrusion", - extrusionDepth: 2, - extrusionPath: path, - extrusionShapes: shapes + type: "extrudedPolygon", + extrudedPolygonDepth: 2, + extrudedPolygonPath: path, + extrudedPolygonShapes: shapes }; const beveledPath: PrimitiveMeshAsset = { - type: "extrusion", - extrusionPath: path, - extrusionShapes: shapes, - extrusionOptions: { bevelWidth: 1 } + type: "extrudedPolygon", + extrudedPolygonPath: path, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { bevelWidth: 1 } }; const offsetPath: PrimitiveMeshAsset = { - type: "extrusion", - extrusionPath: path, - extrusionShapes: shapes, - extrusionOptions: { contourOffset: 0.1 } + type: "extrudedPolygon", + extrudedPolygonPath: path, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { contourOffset: 0.1 } }; const closedDepth: PrimitiveMeshAsset = { - type: "extrusion", - extrusionDepth: 2, - extrusionShapes: shapes, - extrusionOptions: { closedPath: true } + type: "extrudedPolygon", + extrudedPolygonDepth: 2, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { closedPath: true } }; const wrongOptions: PrimitiveMeshAsset = { type: "sphere", @@ -150,7 +150,7 @@ void [ ungroupedSphere, tube, polygon, - extrusion, + extrudedPolygon, pathExtrusion, torusKnot, cylinder, @@ -176,7 +176,7 @@ 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: "extrusion", extrusionShapes: shapes }; +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/mesh/ProceduralMesh.test.ts b/tests/src/core/mesh/ProceduralMesh.test.ts index 935ac4b862..429f5a3b9d 100644 --- a/tests/src/core/mesh/ProceduralMesh.test.ts +++ b/tests/src/core/mesh/ProceduralMesh.test.ts @@ -106,22 +106,28 @@ const creators: [string, () => ModelMesh][] = [ () => PrimitiveMesh.createTube(engine, path, 0.5, { keepCPUData: true, pathSegments: 12, radialSegments: 8 }) ], ["polygon", () => PrimitiveMesh.createPolygon(engine, polygon, { keepCPUData: true })], - ["extrusion", () => PrimitiveMesh.createExtrusion(engine, polygon, 2, { keepCPUData: true, depthSegments: 1 })], [ - "extrusion", + "extrudedPolygon", + () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { keepCPUData: true, depthSegments: 1 }) + ], + [ + "extrudedPolygon", () => - PrimitiveMesh.createExtrusion(engine, polygon, 1, { + PrimitiveMesh.createExtrudedPolygon(engine, polygon, 1, { keepCPUData: true, bevelWidth: 0.1, contourOffset: 0.2, depthSegments: 1 }) ], - ["extrusion", () => PrimitiveMesh.createExtrusion(engine, polygon, path, { keepCPUData: true, pathSegments: 5 })], [ - "extrusion", + "extrudedPolygon", + () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, { keepCPUData: true, pathSegments: 5 }) + ], + [ + "extrudedPolygon", () => - PrimitiveMesh.createExtrusion( + PrimitiveMesh.createExtrudedPolygon( engine, { points: [ @@ -255,13 +261,13 @@ describe("primitive mesh defaults", () => { ], [ "depth extrusion", - () => PrimitiveMesh.createExtrusion(engine, polygon, 2, { ...options }), - () => PrimitiveMesh.createExtrusion(engine, polygon, 2, { ...options, depthSegments: 1 }) + () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { ...options }), + () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { ...options, depthSegments: 1 }) ], [ "path extrusion", - () => PrimitiveMesh.createExtrusion(engine, polygon, path, { ...options }), - () => PrimitiveMesh.createExtrusion(engine, polygon, path, { ...options, pathSegments: 1 }) + () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, { ...options }), + () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, { ...options, pathSegments: 1 }) ], [ "torus knot", @@ -1031,7 +1037,7 @@ describe("procedural mesh geometry", () => { 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.createExtrusion(engine, shapes, 2, { + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, shapes, 2, { keepCPUData: true, separateMaterialSlots: true, depthSegments: 1 @@ -1054,7 +1060,7 @@ describe("procedural mesh geometry", () => { it.each([0.2, -0.2])("offsets extrusion walls and bevels by %s and restores their geometry", (contourOffset) => { const options = { keepCPUData: true, separateMaterialSlots: true, bevelWidth: 0.1, bevelDepth: 0.2, contourOffset }; - const mesh = PrimitiveMesh.createExtrusion(engine, polygon, 2, { ...options, depthSegments: 2 }); + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { ...options, depthSegments: 2 }); try { const outer = 2 + contourOffset; const hole = 1 - contourOffset; @@ -1092,7 +1098,7 @@ describe("procedural mesh geometry", () => { }); it.each([0.2, -0.2])("offsets extrusion contours by %s without adding bevels", (contourOffset) => { - const mesh = PrimitiveMesh.createExtrusion(engine, polygon, 2, { + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { keepCPUData: true, contourOffset, depthSegments: 1 @@ -1238,7 +1244,10 @@ describe("procedural mesh geometry", () => { it("preserves multiple holes in extrusion caps and restored buffers", () => { const { points, holes, area } = triangulationCases[1]; - const mesh = PrimitiveMesh.createExtrusion(engine, { points, holes }, 3, { keepCPUData: true, depthSegments: 1 }); + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, { points, holes }, 3, { + keepCPUData: true, + depthSegments: 1 + }); try { const positions = mesh.getPositions()!; const indices = Array.from(mesh.getIndices()!); @@ -1294,14 +1303,14 @@ describe("procedural mesh geometry", () => { it.each([ { type: "tube", tubeRadius: 0.5, keepCPUData: false }, { type: "tube", tubeRadius: 0.5, keepCPUData: true }, - { type: "extrusion", extrusionDepth: 1, keepCPUData: false }, - { type: "extrusion", extrusionDepth: 1, keepCPUData: true } + { type: "extrudedPolygon", extrudedPolygonDepth: 1, keepCPUData: false }, + { type: "extrudedPolygon", extrudedPolygonDepth: 1, keepCPUData: true } ])("copies $type path points for device restoration with keepCPUData=$keepCPUData", ({ type, keepCPUData }) => { const points = path.map((point) => point.clone()); const mesh = type === "tube" ? PrimitiveMesh.createTube(engine, points, 0.5, { keepCPUData, pathSegments: 12, radialSegments: 8 }) - : PrimitiveMesh.createExtrusion(engine, polygon, points, { keepCPUData, pathSegments: 12 }); + : PrimitiveMesh.createExtrudedPolygon(engine, polygon, points, { keepCPUData, pathSegments: 12 }); try { const buffers = mesh.vertexBufferBindings.map((binding) => binding!.buffer); buffers.push(mesh._primitive.indexBufferBinding!._buffer); @@ -1456,8 +1465,8 @@ describe("procedural mesh geometry", () => { 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 = { keepCPUData: true, closedPath: true }; - const mesh = PrimitiveMesh.createExtrusion(engine, profile, points, { ...options, pathSegments: 32 }); - const repeated = PrimitiveMesh.createExtrusion(engine, profile, [...points, points[0].clone()], { + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, profile, points, { ...options, pathSegments: 32 }); + const repeated = PrimitiveMesh.createExtrudedPolygon(engine, profile, [...points, points[0].clone()], { ...options, pathSegments: 32 }); @@ -1504,7 +1513,7 @@ describe("procedural mesh geometry", () => { { 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.createExtrusion(engine, shapes, points, { + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, shapes, points, { keepCPUData: true, separateMaterialSlots: true, closedPath: true, @@ -1527,12 +1536,12 @@ describe("procedural mesh geometry", () => { const pathOptions = { keepCPUData: true, pathSegments: 5, separateMaterialSlots: true }; const pairs = [ [ - PrimitiveMesh.createExtrusion(engine, polygon, 2, linearOptions), - PrimitiveMesh.createExtrusion(engine, polygon, 2, { ...linearOptions, pathSegments: 7, closedPath: true }) + PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, linearOptions), + PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { ...linearOptions, pathSegments: 7, closedPath: true }) ], [ - PrimitiveMesh.createExtrusion(engine, polygon, path, pathOptions), - PrimitiveMesh.createExtrusion(engine, polygon, path, { + PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, pathOptions), + PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, { ...pathOptions, depthSegments: 7, bevelWidth: 0.25, @@ -1564,7 +1573,7 @@ describe("procedural mesh geometry", () => { 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.createExtrusion(engine, profile, points, { keepCPUData: true, closedPath: true }); + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, profile, points, { keepCPUData: true, closedPath: true }); try { const positions = mesh.getPositions()!; const indices = mesh.getIndices()!; @@ -1837,7 +1846,7 @@ describe("procedural mesh geometry", () => { const angle = (i * Math.PI * 2) / 256; return new Vector2(Math.cos(angle), Math.sin(angle)); }); - const mesh = PrimitiveMesh.createExtrusion(engine, contour, 1, { keepCPUData: true, depthSegments: 43 }); + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, contour, 1, { keepCPUData: true, depthSegments: 43 }); try { const indices = mesh.getIndices()!; expect(mesh.vertexCount).toBeGreaterThan(65535); @@ -1849,7 +1858,7 @@ describe("procedural mesh geometry", () => { }); it("handles repeated contour endpoints when beveling", () => { - const mesh = PrimitiveMesh.createExtrusion( + const mesh = PrimitiveMesh.createExtrudedPolygon( engine, { points: [ diff --git a/tests/src/loader/PrimitiveMeshLoader.test.ts b/tests/src/loader/PrimitiveMeshLoader.test.ts index 7204a5da38..d839f74ac5 100644 --- a/tests/src/loader/PrimitiveMeshLoader.test.ts +++ b/tests/src/loader/PrimitiveMeshLoader.test.ts @@ -131,9 +131,9 @@ describe("PrimitiveMeshLoader", () => { data: { type: "polygon", polygonShapes: shapes }, create: () => PrimitiveMesh.createPolygon(engine, shapeVectors) }, - extrusion: { - data: { type: "extrusion", extrusionDepth: 1, extrusionShapes: shapes }, - create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors, 1) + extrudedPolygon: { + data: { type: "extrudedPolygon", extrudedPolygonDepth: 1, extrudedPolygonShapes: shapes }, + create: () => PrimitiveMesh.createExtrudedPolygon(engine, shapeVectors, 1) }, torusKnot: { data: { @@ -428,10 +428,10 @@ describe("PrimitiveMeshLoader", () => { { name: "beveled extrusion", data: { - type: "extrusion", - extrusionDepth: 2, - extrusionShapes: shapes, - extrusionOptions: { + type: "extrudedPolygon", + extrudedPolygonDepth: 2, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { ...groupedOptions, bevelWidth: 0.1, bevelDepth: 0.2, @@ -441,7 +441,7 @@ describe("PrimitiveMeshLoader", () => { } }, create: () => - PrimitiveMesh.createExtrusion(engine, shapeVectors, 2, { + PrimitiveMesh.createExtrudedPolygon(engine, shapeVectors, 2, { ...groupedOptions, bevelWidth: 0.1, bevelDepth: 0.2, @@ -453,35 +453,39 @@ describe("PrimitiveMeshLoader", () => { { name: "inset extrusion without bevels", data: { - type: "extrusion", - extrusionDepth: 2, - extrusionShapes: shapes, - extrusionOptions: { ...options, contourOffset: -0.1 } + type: "extrudedPolygon", + extrudedPolygonDepth: 2, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { ...options, contourOffset: -0.1 } }, create: () => - PrimitiveMesh.createExtrusion(engine, shapeVectors, 2, { ...options, contourOffset: -0.1, depthSegments: 1 }) + PrimitiveMesh.createExtrudedPolygon(engine, shapeVectors, 2, { + ...options, + contourOffset: -0.1, + depthSegments: 1 + }) }, { name: "extrusion along a path", data: { - type: "extrusion", - extrusionPath: path, - extrusionShapes: shapes, - extrusionOptions: { ...groupedOptions, pathSegments: 6 } + type: "extrudedPolygon", + extrudedPolygonPath: path, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { ...groupedOptions, pathSegments: 6 } }, create: () => - PrimitiveMesh.createExtrusion(engine, shapeVectors, pathVectors, { ...groupedOptions, pathSegments: 6 }) + PrimitiveMesh.createExtrudedPolygon(engine, shapeVectors, pathVectors, { ...groupedOptions, pathSegments: 6 }) }, { name: "closed extrusion path", data: { - type: "extrusion", - extrusionPath: path, - extrusionShapes: shapes, - extrusionOptions: { ...groupedOptions, closedPath: true, pathSegments: 12 } + type: "extrudedPolygon", + extrudedPolygonPath: path, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { ...groupedOptions, closedPath: true, pathSegments: 12 } }, create: () => - PrimitiveMesh.createExtrusion(engine, shapeVectors, pathVectors, { + PrimitiveMesh.createExtrudedPolygon(engine, shapeVectors, pathVectors, { ...groupedOptions, closedPath: true, pathSegments: 12 @@ -490,20 +494,21 @@ describe("PrimitiveMeshLoader", () => { { name: "linear extrusion ignores path-only settings", data: { - type: "extrusion", - extrusionDepth: 2, - extrusionShapes: shapes, - extrusionOptions: { ...groupedOptions, depthSegments: 2, closedPath: true } + type: "extrudedPolygon", + extrudedPolygonDepth: 2, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { ...groupedOptions, depthSegments: 2, closedPath: true } }, - create: () => PrimitiveMesh.createExtrusion(engine, shapeVectors, 2, { ...groupedOptions, depthSegments: 2 }) + create: () => + PrimitiveMesh.createExtrudedPolygon(engine, shapeVectors, 2, { ...groupedOptions, depthSegments: 2 }) }, { name: "path extrusion ignores linear-only settings", data: { - type: "extrusion", - extrusionPath: path, - extrusionShapes: shapes, - extrusionOptions: { + type: "extrudedPolygon", + extrudedPolygonPath: path, + extrudedPolygonShapes: shapes, + extrudedPolygonOptions: { ...groupedOptions, pathSegments: 6, bevelWidth: 0.25, @@ -513,7 +518,7 @@ describe("PrimitiveMeshLoader", () => { } }, create: () => - PrimitiveMesh.createExtrusion(engine, shapeVectors, pathVectors, { ...groupedOptions, pathSegments: 6 }) + PrimitiveMesh.createExtrudedPolygon(engine, shapeVectors, pathVectors, { ...groupedOptions, pathSegments: 6 }) }, { name: "torus knot winding", From 026ffa245bd0d9f97d41dc640be6245ba8702f1f Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sat, 14 Nov 2026 22:33:18 +0800 Subject: [PATCH 06/24] chore: restore repository license --- LICENSE | 42 ------------------------------------------ 1 file changed, 42 deletions(-) diff --git a/LICENSE b/LICENSE index 36987e9152..742b2b0fff 100644 --- a/LICENSE +++ b/LICENSE @@ -19,45 +19,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Third-party notices -=================== - -Regular-polyhedron vertex and face tables and rounded-cuboid UV mapping are derived from three.js -Copyright (c) 2010-2026 three.js authors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -Polygon triangulation adapted from Mapbox Earcut 3.0.2. -https://github.com/mapbox/earcut/tree/v3.0.2 - -ISC License -Copyright (c) 2024, Mapbox - -Permission to use, copy, modify, and/or distribute this software for any purpose -with or without fee is hereby granted, provided that the above copyright notice -and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS -OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -THIS SOFTWARE. From 6f9554609d4ecb5ae7715121a40e034cd1096251 Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sat, 14 Nov 2026 22:39:21 +0800 Subject: [PATCH 07/24] perf(core): avoid default primitive option allocations Read optional primitive settings without materializing empty objects. Preserve dependent defaults and accept absent settings throughout the shared mesh creation path. --- packages/core/src/mesh/PrimitiveMesh.ts | 135 +++++++++++++----------- 1 file changed, 76 insertions(+), 59 deletions(-) diff --git a/packages/core/src/mesh/PrimitiveMesh.ts b/packages/core/src/mesh/PrimitiveMesh.ts index f358f0a7f7..db5f27a059 100644 --- a/packages/core/src/mesh/PrimitiveMesh.ts +++ b/packages/core/src/mesh/PrimitiveMesh.ts @@ -182,8 +182,10 @@ export class PrimitiveMesh { * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createSphere(engine: Engine, radius: number, options: SphereMeshOptions = {}): ModelMesh { - const { subdivisionLevel = 3, horizontalAngleRange, verticalAngleRange } = options; + 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, @@ -213,9 +215,11 @@ export class PrimitiveMesh { width: number, height: number, depth: number, - options: CuboidMeshOptions = {} + options?: CuboidMeshOptions ): ModelMesh { - const { widthSegments = 1, heightSegments = widthSegments, depthSegments = widthSegments } = options; + const widthSegments = options?.widthSegments ?? 1; + const heightSegments = options?.heightSegments ?? widthSegments; + const depthSegments = options?.depthSegments ?? widthSegments; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createCuboidData, @@ -232,8 +236,9 @@ export class PrimitiveMesh { * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createPlane(engine: Engine, width: number, depth: number, options: PlaneMeshOptions = {}): ModelMesh { - const { widthSegments = 1, depthSegments = widthSegments } = options; + 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, @@ -250,8 +255,11 @@ export class PrimitiveMesh { * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createCylinder(engine: Engine, radius: number, height: number, options: CylinderMeshOptions = {}): ModelMesh { - const { radialSegments = 20, heightSegments = 1, caps = PrimitiveMeshCapMode.Both, angleRange } = options; + 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, @@ -285,9 +293,12 @@ export class PrimitiveMesh { topRadius: number, bottomRadius: number, height: number, - options: TruncatedConeMeshOptions = {} + options?: TruncatedConeMeshOptions ): ModelMesh { - const { radialSegments = 20, heightSegments = 1, caps = PrimitiveMeshCapMode.Both, angleRange } = options; + 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, @@ -315,8 +326,11 @@ export class PrimitiveMesh { * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createCone(engine: Engine, radius: number, height: number, options: ConeMeshOptions = {}): ModelMesh { - const { radialSegments = 20, heightSegments = 1, cap = true, angleRange } = options; + 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, @@ -338,9 +352,11 @@ export class PrimitiveMesh { engine: Engine, radius: number, cylinderHeight: number, - options: CapsuleMeshOptions = {} + options?: CapsuleMeshOptions ): ModelMesh { - const { radialSegments = 6, capSegments = radialSegments, heightSegments = 1 } = options; + const radialSegments = options?.radialSegments ?? 6; + const capSegments = options?.capSegments ?? radialSegments; + const heightSegments = options?.heightSegments ?? 1; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createCapsuleData, @@ -357,8 +373,11 @@ export class PrimitiveMesh { * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createTorus(engine: Engine, radius: number, tubeRadius: number, options: TorusMeshOptions = {}): ModelMesh { - const { ringSegments = 30, radialSegments = 30, ringAngleRange, tubeAngleRange } = options; + 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( @@ -385,8 +404,9 @@ export class PrimitiveMesh { * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createCircle(engine: Engine, radius: number, options: CircleMeshOptions = {}): ModelMesh { - const { segments = 32, angleRange } = options; + 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, @@ -404,13 +424,10 @@ export class PrimitiveMesh { * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createRing( - engine: Engine, - outerRadius: number, - innerRadius: number, - options: RingMeshOptions = {} - ): ModelMesh { - const { ringSegments = 32, widthSegments = 1, angleRange } = options; + 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, @@ -427,8 +444,8 @@ export class PrimitiveMesh { * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createTetrahedron(engine: Engine, radius: number, options: RegularPolyhedronMeshOptions = {}): ModelMesh { - const { edgeSegments = 1 } = options; + static createTetrahedron(engine: Engine, radius: number, options?: RegularPolyhedronMeshOptions): ModelMesh { + const edgeSegments = options?.edgeSegments ?? 1; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createRegularPolyhedronData, @@ -444,8 +461,8 @@ export class PrimitiveMesh { * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createOctahedron(engine: Engine, radius: number, options: RegularPolyhedronMeshOptions = {}): ModelMesh { - const { edgeSegments = 1 } = options; + static createOctahedron(engine: Engine, radius: number, options?: RegularPolyhedronMeshOptions): ModelMesh { + const edgeSegments = options?.edgeSegments ?? 1; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createRegularPolyhedronData, @@ -461,8 +478,8 @@ export class PrimitiveMesh { * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createIcosahedron(engine: Engine, radius: number, options: RegularPolyhedronMeshOptions = {}): ModelMesh { - const { edgeSegments = 1 } = options; + static createIcosahedron(engine: Engine, radius: number, options?: RegularPolyhedronMeshOptions): ModelMesh { + const edgeSegments = options?.edgeSegments ?? 1; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createRegularPolyhedronData, @@ -478,8 +495,8 @@ export class PrimitiveMesh { * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createDodecahedron(engine: Engine, radius: number, options: RegularPolyhedronMeshOptions = {}): ModelMesh { - const { edgeSegments = 1 } = options; + static createDodecahedron(engine: Engine, radius: number, options?: RegularPolyhedronMeshOptions): ModelMesh { + const edgeSegments = options?.edgeSegments ?? 1; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createRegularPolyhedronData, @@ -495,8 +512,9 @@ export class PrimitiveMesh { * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createLathe(engine: Engine, profile: readonly Vector2[], options: LatheMeshOptions = {}): ModelMesh { - const { segments = 12, angleRange } = options; + static createLathe(engine: Engine, profile: readonly Vector2[], options?: LatheMeshOptions): ModelMesh { + const segments = options?.segments ?? 12; + const angleRange = options?.angleRange; const startAngle = angleRange?.x ?? 0; return PrimitiveMesh._createMesh( engine, @@ -514,13 +532,10 @@ export class PrimitiveMesh { * @param options - Optional mesh generation settings * @returns The generated mesh */ - static createTube( - engine: Engine, - path: readonly Vector3[], - radius: number, - options: TubeMeshOptions = {} - ): ModelMesh { - const { pathSegments = 64, radialSegments = 8, closedPath = false } = options; + 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, @@ -539,7 +554,7 @@ export class PrimitiveMesh { static createPolygon( engine: Engine, shapes: readonly Vector2[] | PolygonShape | readonly PolygonShape[], - options: PolygonMeshOptions = {} + options?: PolygonMeshOptions ): ModelMesh { return PrimitiveMesh._createMesh( engine, @@ -565,17 +580,17 @@ export class PrimitiveMesh { engine: Engine, shapes: readonly Vector2[] | PolygonShape | readonly PolygonShape[], depthOrPath: number | readonly Vector3[], - options: LinearExtrudedPolygonMeshOptions | PathExtrudedPolygonMeshOptions = {} + options?: LinearExtrudedPolygonMeshOptions | PathExtrudedPolygonMeshOptions ): ModelMesh { - const { - depthSegments = 1, - pathSegments = 1, - closedPath = false, - bevelWidth = 0, - bevelDepth = bevelWidth, - contourOffset = 0, - bevelSegments = 3 - }: LinearExtrudedPolygonMeshOptions & PathExtrudedPolygonMeshOptions = options; + 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( @@ -612,9 +627,10 @@ export class PrimitiveMesh { tubeRadius: number, axisTurns: number, crossSectionTurns: number, - options: TorusKnotMeshOptions = {} + options?: TorusKnotMeshOptions ): ModelMesh { - const { pathSegments = 64, radialSegments = 8 } = options; + const pathSegments = options?.pathSegments ?? 64; + const radialSegments = options?.radialSegments ?? 8; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createTorusKnotData, @@ -641,9 +657,9 @@ export class PrimitiveMesh { height: number, depth: number, cornerRadius: number, - options: RoundedCuboidMeshOptions = {} + options?: RoundedCuboidMeshOptions ): ModelMesh { - const { roundingSegments = 2 } = options; + const roundingSegments = options?.roundingSegments ?? 2; return PrimitiveMesh._createMesh( engine, PrimitiveMesh._createRoundedCuboidData, @@ -1944,8 +1960,9 @@ export class PrimitiveMesh { engine: Engine, generate: (...args: T) => PrimitiveMeshBuilder, args: T, - { keepCPUData = false, separateMaterialSlots = false }: { keepCPUData?: boolean; separateMaterialSlots?: boolean } + options?: { keepCPUData?: boolean; separateMaterialSlots?: boolean } ): ModelMesh { + const keepCPUData = options?.keepCPUData ?? false; for (let i = 0; i < args.length; i++) { args[i] = PrimitiveMesh._copy(args[i]); } @@ -1975,7 +1992,7 @@ export class PrimitiveMesh { PrimitiveMesh._setBounds(mesh, data); mesh.uploadData(!keepCPUData); mesh.clearSubMesh(); - if (separateMaterialSlots && data.groups.length) { + if (options?.separateMaterialSlots && data.groups.length) { for (const group of data.groups) { mesh.addSubMesh(group.start, group.count); } From 224f73ab018c467f11af8e88a48014a5665a2a10 Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sat, 14 Nov 2026 22:52:56 +0800 Subject: [PATCH 08/24] refactor(core): separate extrusion overload contracts Pair numeric depths with linear options and path arrays with path options. Give each overload its own parameter documentation and align serialized assets, loader calls, examples and consumer checks. BREAKING CHANGE: Narrow union-valued extrusion inputs before calling createExtrudedPolygon and use the options for the selected mode. --- docs/en/graphics/mesh/primitiveMesh.mdx | 7 +++- docs/zh/graphics/mesh/primitiveMesh.mdx | 7 +++- packages/core/src/mesh/PrimitiveMesh.ts | 32 +++++++++++++---- .../references/mesh-geometry.md | 2 +- packages/loader/src/PrimitiveMeshAsset.ts | 4 +-- packages/loader/src/PrimitiveMeshLoader.ts | 10 +++++- .../package-consumer/PrimitiveMeshApi.test.ts | 35 +++++++++---------- .../fixtures/PrimitiveMeshApi.ts | 6 +++- .../fixtures/PrimitiveMeshAsset.ts | 3 ++ tests/src/core/mesh/ProceduralMesh.test.ts | 20 ++++++----- tests/src/loader/PrimitiveMeshLoader.test.ts | 20 ++++++----- 11 files changed, 96 insertions(+), 50 deletions(-) diff --git a/docs/en/graphics/mesh/primitiveMesh.mdx b/docs/en/graphics/mesh/primitiveMesh.mdx index 6faa711f21..cdff42baa5 100644 --- a/docs/en/graphics/mesh/primitiveMesh.mdx +++ b/docs/en/graphics/mesh/primitiveMesh.mdx @@ -202,7 +202,12 @@ const loop = [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` requires a third argument: a numeric depth for linear extrusion, or a `Vector3` array for path extrusion. `LinearExtrudedPolygonMeshOptions` contains optional bevel settings; `PathExtrudedPolygonMeshOptions` contains optional path settings. Linear extrusion uses `depthSegments`; path extrusion uses `pathSegments`. Each interface declares its mode's settings. A path ignores bevel settings; a numeric depth ignores `closedPath`. Linear extrusion goes along +Z without bevels unless requested. A positive `bevelWidth` enables beveling; `bevelDepth` defaults to the same value. Path extrusion does not generate bevels. Paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points before creating the mesh, as shown above. +`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. diff --git a/docs/zh/graphics/mesh/primitiveMesh.mdx b/docs/zh/graphics/mesh/primitiveMesh.mdx index 183121f598..313da8f9db 100644 --- a/docs/zh/graphics/mesh/primitiveMesh.mdx +++ b/docs/zh/graphics/mesh/primitiveMesh.mdx @@ -208,7 +208,12 @@ const loop = [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` 的第三个参数必填:传入数值深度时沿 +Z 直线拉伸,传入 `Vector3` 数组时沿路径挤出。`LinearExtrudedPolygonMeshOptions` 包含可选的倒角设置,`PathExtrudedPolygonMeshOptions` 包含可选的路径设置。直线拉伸用 `depthSegments`,路径拉伸用 `pathSegments`;两个接口分别声明各自模式的设置。沿路径挤出时忽略倒角设置;直线拉伸时忽略 `closedPath`。直线拉伸默认不倒角;`bevelWidth > 0` 时开启倒角,`bevelDepth` 默认等于 `bevelWidth`。沿路径拉伸不生成倒角。路径接收 `Vector3` 数组,并按折线长度均匀采样。使用曲线时,在外层采样成点数组后传入,如上例所示。 +`createExtrudedPolygon` 提供两个重载: + +- `depth: number` 沿 +Z 直线挤出,生成侧壁和两端封盖。`LinearExtrudedPolygonMeshOptions` 控制 `depthSegments`、倒角和材质分组。 +- `path: readonly Vector3[]` 沿空间路径挤出。`PathExtrudedPolygonMeshOptions` 控制 `pathSegments`、`closedPath` 和材质分组。开放路径生成两端封盖;闭合路径连接首尾截面,不生成封盖。 + +直线挤出默认不倒角;`bevelWidth > 0` 时开启倒角,`bevelDepth` 默认等于 `bevelWidth`。路径挤出不提供倒角设置。路径按折线长度均匀采样;使用曲线时,在外层采样成点数组后传入,如上例所示。 管道和路径挤出的 `closedPath` 默认关闭;开启后自动连接路径首尾并对齐截面,不必重复首点。闭合挤出至少使用三段,不生成端盖。开放挤出保留两端端盖;管道在两种模式下都不生成端盖。 diff --git a/packages/core/src/mesh/PrimitiveMesh.ts b/packages/core/src/mesh/PrimitiveMesh.ts index db5f27a059..a41fe5c283 100644 --- a/packages/core/src/mesh/PrimitiveMesh.ts +++ b/packages/core/src/mesh/PrimitiveMesh.ts @@ -565,17 +565,35 @@ export class PrimitiveMesh { } /** - * Create an extruded polygon mesh with side walls along +Z or a spatial path. + * Extrude polygon contours along +Z. + * @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 createExtrudedPolygon( + engine: Engine, + shapes: readonly Vector2[] | PolygonShape | readonly PolygonShape[], + depth: number, + options?: LinearExtrudedPolygonMeshOptions + ): ModelMesh; + /** + * Extrude polygon contours along a spatial path. * @remarks - * A numeric depth extrudes the contours along +Z and ignores `closedPath`. - * A path sweeps the contours along its points and ignores bevel settings. - * Open extrusions include both end caps; closed paths have no end caps. + * Open paths generate both end caps; closed paths join the end cross-sections without caps. * @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 depthOrPath - The total extrusion depth in local units, including bevels, or a path with at least two distinct points - * @param options - Linear or path extrusion settings - * @returns The extruded polygon mesh with side walls and any end caps + * @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[], diff --git a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md index 2c54cf0e23..8c18d324ff 100644 --- a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md +++ b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md @@ -61,7 +61,7 @@ Angles use degrees. Ranges use `Vector2`, with `x` as the start angle and `y` as `createSphere(engine, radius, { subdivisionLevel, horizontalAngleRange, verticalAngleRange })` projects a subdivided cube onto a sphere. The subdivision level defaults to 3 and is clamped to 1 through 6. It accepts `horizontalAngleRange` and `verticalAngleRange`. These clip the subdivided surface and leave open boundaries. Horizontal angles start at -X towards +Z, and vertical angles start at +Y. Continuous horizontal intervals such as `new Vector2(350, 370)` cross the seam. Complete spheres and sections use the same subdivision level. -Additional generators include circle, ring, four regular polyhedra, lathe, tube, polygon, extrusion, torus knot and rounded cuboid. Angle ranges belong to options. Rings require the outer radius first, followed by the inner radius. Contours and lathe profiles use `Vector2` arrays; paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points outside the mesh API. A simple polygon is a point array; holes use `{ points, holes }`. Extrusion takes a required numeric depth or `Vector3` path as its third argument, followed by `LinearExtrudedPolygonMeshOptions` or `PathExtrudedPolygonMeshOptions`. Linear extrusion uses `depthSegments`; path extrusion uses `pathSegments`. Each interface declares its mode's optional settings. A path selects path extrusion and ignores bevel settings; a numeric depth extrudes along +Z and ignores `closedPath`. Straight extrusion defaults to no bevel; a positive `bevelWidth` enables it, with `bevelDepth` defaulting to the same value. Path extrusion has no bevels. +Additional generators include circle, ring, four regular polyhedra, lathe, tube, polygon, extrusion, torus knot and rounded cuboid. Angle ranges belong to options. Rings require the outer radius first, followed by the inner radius. Contours and lathe profiles use `Vector2` arrays; paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points outside the mesh API. A simple polygon is a point array; holes use `{ points, holes }`. Extrusion has two overloads: a required numeric `depth` followed by `LinearExtrudedPolygonMeshOptions`, or a required `Vector3` array `path` followed by `PathExtrudedPolygonMeshOptions`. The depth overload extrudes along +Z and uses `depthSegments`; the path overload uses `pathSegments` and `closedPath`. Each overload declares its own parameter names, comments and optional settings. Open extrusions have both end caps; closed paths join their end cross-sections without caps. Straight extrusion defaults to no bevel; a positive `bevelWidth` enables it, with `bevelDepth` defaulting to the same value. Path extrusion has no bevels. For straight extrusion, `contourOffset` shifts the side-wall outline and defaults to `0`. Positive values expand the solid and contract holes; negative values do the reverse. The offset also applies when `bevelWidth` is `0`. Bevels are cut into the shifted outline and included in the total `depth`. diff --git a/packages/loader/src/PrimitiveMeshAsset.ts b/packages/loader/src/PrimitiveMeshAsset.ts index 31fad4b85e..7eeea17d6b 100644 --- a/packages/loader/src/PrimitiveMeshAsset.ts +++ b/packages/loader/src/PrimitiveMeshAsset.ts @@ -215,7 +215,7 @@ export type PrimitiveMeshAsset = */ extrudedPolygonDepth: number; extrudedPolygonShapes: readonly SerializedPolygonShape[]; - extrudedPolygonOptions?: LinearExtrudedPolygonMeshOptions | PathExtrudedPolygonMeshOptions; + extrudedPolygonOptions?: LinearExtrudedPolygonMeshOptions; } | { type: "extrudedPolygon"; @@ -224,7 +224,7 @@ export type PrimitiveMeshAsset = */ extrudedPolygonPath: readonly { x: number; y: number; z: number }[]; extrudedPolygonShapes: readonly SerializedPolygonShape[]; - extrudedPolygonOptions?: LinearExtrudedPolygonMeshOptions | PathExtrudedPolygonMeshOptions; + extrudedPolygonOptions?: PathExtrudedPolygonMeshOptions; } | { type: "torusKnot"; diff --git a/packages/loader/src/PrimitiveMeshLoader.ts b/packages/loader/src/PrimitiveMeshLoader.ts index a895d4147c..5f769a7284 100644 --- a/packages/loader/src/PrimitiveMeshLoader.ts +++ b/packages/loader/src/PrimitiveMeshLoader.ts @@ -95,10 +95,18 @@ class PrimitiveMeshLoader extends Loader { 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), - "extrudedPolygonPath" in data ? this._parseVector3s(data.extrudedPolygonPath) : data.extrudedPolygonDepth, + data.extrudedPolygonDepth, data.extrudedPolygonOptions ); case "torusKnot": diff --git a/tests/package-consumer/PrimitiveMeshApi.test.ts b/tests/package-consumer/PrimitiveMeshApi.test.ts index f660a96b6d..6c83e6cf63 100644 --- a/tests/package-consumer/PrimitiveMeshApi.test.ts +++ b/tests/package-consumer/PrimitiveMeshApi.test.ts @@ -41,15 +41,20 @@ it.each(["PrimitiveMeshApi", "PrimitiveMeshAsset"])("type-checks %s and rejects for (const factory of factories) { const signatures = checker.getTypeOfSymbolAtLocation(factory, source).getCallSignatures(); - expect(signatures, `Expected one call signature: ${factory.name}`).toHaveLength(1); + 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( - examples.some((call) => checker.getResolvedSignature(call)?.getDeclaration() === signature.getDeclaration()), + overloadExamples.length, `Missing overload example: ${factory.name}${checker.signatureToString(signature)}` - ).toBe(true); + ).toBeGreaterThan(0); const optionsIndex = signature.getParameters().findIndex((parameter) => parameter.name === "options"); const optionsType = checker.getNonNullableType( @@ -71,7 +76,7 @@ it.each(["PrimitiveMeshApi", "PrimitiveMeshAsset"])("type-checks %s and rejects ).toBeUndefined(); } const documentedFields = new Set( - examples.flatMap((call) => { + overloadExamples.flatMap((call) => { const options = call.arguments[optionsIndex]; return options ? checker @@ -90,20 +95,14 @@ it.each(["PrimitiveMeshApi", "PrimitiveMeshAsset"])("type-checks %s and rejects ); } } - } - - const parameters = signatures.map((signature) => signature.getDeclaration()!.parameters); - const minimum = Math.min( - ...parameters.map( - (list) => list.filter((parameter) => !parameter.questionToken && !parameter.initializer).length - ) - ); - const maximum = Math.max(...parameters.map((list) => list.length)); - for (let count = minimum; count <= maximum; count++) { - expect( - examples.some((call) => call.arguments.length === count), - `Missing optional-argument example: ${factory.name} with ${count} arguments` - ).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 index 9e22efb0dd..e27d5f755b 100644 --- a/tests/package-consumer/fixtures/PrimitiveMeshApi.ts +++ b/tests/package-consumer/fixtures/PrimitiveMeshApi.ts @@ -297,10 +297,14 @@ 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" }); -// Fields from the inactive mode follow normal structural compatibility +// @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 diff --git a/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts index 89ba95628e..fbef7d6c0b 100644 --- a/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts +++ b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts @@ -93,18 +93,21 @@ const mixedExtrusion: PrimitiveMeshAsset = { 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, diff --git a/tests/src/core/mesh/ProceduralMesh.test.ts b/tests/src/core/mesh/ProceduralMesh.test.ts index 429f5a3b9d..dd1c6e50b9 100644 --- a/tests/src/core/mesh/ProceduralMesh.test.ts +++ b/tests/src/core/mesh/ProceduralMesh.test.ts @@ -1534,21 +1534,23 @@ describe("procedural mesh geometry", () => { it("ignores settings from the inactive extrusion mode", () => { const linearOptions = { keepCPUData: true, depthSegments: 2, bevelWidth: 0.1, separateMaterialSlots: true }; const pathOptions = { keepCPUData: 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, { ...linearOptions, pathSegments: 7, closedPath: true }) + PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, mixedLinearOptions) ], [ PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, pathOptions), - PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, { - ...pathOptions, - depthSegments: 7, - bevelWidth: 0.25, - bevelDepth: 0.4, - contourOffset: 0.5, - bevelSegments: 8 - }) + PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, mixedPathOptions) ] ]; try { diff --git a/tests/src/loader/PrimitiveMeshLoader.test.ts b/tests/src/loader/PrimitiveMeshLoader.test.ts index d839f74ac5..84dfd89b4e 100644 --- a/tests/src/loader/PrimitiveMeshLoader.test.ts +++ b/tests/src/loader/PrimitiveMeshLoader.test.ts @@ -61,6 +61,15 @@ const shapeVectors = shapes.map(({ points, holes }) => ({ })); const options = { keepCPUData: true }; const groupedOptions = { keepCPUData: 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 = { @@ -497,7 +506,7 @@ describe("PrimitiveMeshLoader", () => { type: "extrudedPolygon", extrudedPolygonDepth: 2, extrudedPolygonShapes: shapes, - extrudedPolygonOptions: { ...groupedOptions, depthSegments: 2, closedPath: true } + extrudedPolygonOptions: mixedLinearOptions }, create: () => PrimitiveMesh.createExtrudedPolygon(engine, shapeVectors, 2, { ...groupedOptions, depthSegments: 2 }) @@ -508,14 +517,7 @@ describe("PrimitiveMeshLoader", () => { type: "extrudedPolygon", extrudedPolygonPath: path, extrudedPolygonShapes: shapes, - extrudedPolygonOptions: { - ...groupedOptions, - pathSegments: 6, - bevelWidth: 0.25, - bevelDepth: 0.4, - contourOffset: 0.5, - bevelSegments: 8 - } + extrudedPolygonOptions: mixedPathOptions }, create: () => PrimitiveMesh.createExtrudedPolygon(engine, shapeVectors, pathVectors, { ...groupedOptions, pathSegments: 6 }) From 50f7db281e7c8ecd4e32ee4fbe471b97e7c9e83b Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sat, 14 Nov 2026 23:31:17 +0800 Subject: [PATCH 09/24] refactor(core): use standard primitive tangent initialization Route primitive creation through ModelMesh.calculateTangents and uploadData. Remove the specialized tangent initialization and buffer repacking branches while preserving CPU-data release and listener fixes. --- packages/core/src/mesh/ModelMesh.ts | 63 +++++++++------------- packages/core/src/mesh/PrimitiveMesh.ts | 14 ++--- tests/src/core/mesh/ProceduralMesh.test.ts | 29 ++++++++++ 3 files changed, 58 insertions(+), 48 deletions(-) diff --git a/packages/core/src/mesh/ModelMesh.ts b/packages/core/src/mesh/ModelMesh.ts index 58b0b132f5..99646dc576 100644 --- a/packages/core/src/mesh/ModelMesh.ts +++ b/packages/core/src/mesh/ModelMesh.ts @@ -687,14 +687,6 @@ export class ModelMesh extends Mesh { this.setTangents(MeshTangentUtils.calculateTangents(positions, normals, uvs, this._indices)); } - /** - * @internal - */ - _initializeTangents(tangents: Float32Array, releaseData: boolean): void { - this._updateAdvancedVertexElement(true, VertexAttribute.Tangent, VertexElementFlags.Tangent); - this._updateInternalVertexBuffer(releaseData, tangents); - } - /** * @internal */ @@ -802,7 +794,7 @@ export class ModelMesh extends Mesh { this._advancedVertexDataVersions[elementIndex] = this._dataVersionCounter++; } - private _updateInternalVertexBuffer(releaseData: boolean, initialData?: Float32Array): void { + private _updateInternalVertexBuffer(releaseData: boolean): void { const bufferStride = this._internalVertexBufferStride; const vertexCount = this.vertexCount; const bufferCreatedInfo = this._internalVertexBufferCreatedInfo; @@ -813,14 +805,7 @@ export class ModelMesh extends Mesh { // Destroy old internal vertex buffer const createdInternalBufferIndex = bufferCreatedInfo.z; if (createdInternalBufferIndex !== -1) { - const buffer = this._primitive.vertexBufferBindings[createdInternalBufferIndex]?.buffer; - const tangentElement = this._primitive._vertexElementMap[VertexAttribute.Tangent]; - // Raw tangents are read lazily; preserve them before repacking the owned buffer - if (buffer?.readable && tangentElement?.bindingIndex === createdInternalBufferIndex) { - this.getTangents(); - this._advancedVertexDataVersions[VertexElementIndex.Tangent] = this._dataVersionCounter++; - } - buffer?.destroy(); + this._primitive.vertexBufferBindings[createdInternalBufferIndex]?.buffer.destroy(); this._setVertexBufferBinding(createdInternalBufferIndex, null); } @@ -828,14 +813,10 @@ export class ModelMesh extends Mesh { const isCreate = bufferStride * this.vertexCount > 0; if (isCreate) { // No matter the internal buffer is stride change or vertex count change, we need set to internal buffer again - if (!initialData) { - this._advancedDataUpdateFlag |= this._internalVertexElementsFlags; - } + this._advancedDataUpdateFlag |= this._internalVertexElementsFlags; const bufferUsage = releaseData ? BufferUsage.Static : BufferUsage.Dynamic; - const vertexBuffer = initialData - ? new Buffer(this._engine, BufferBindFlag.VertexBuffer, initialData, bufferUsage, !releaseData) - : new Buffer(this._engine, BufferBindFlag.VertexBuffer, needByteLength, bufferUsage, true); + const vertexBuffer = new Buffer(this._engine, BufferBindFlag.VertexBuffer, needByteLength, bufferUsage, true); this._setVertexBufferBinding(vertexBufferIndex, new VertexBufferBinding(vertexBuffer, bufferStride)); } bufferCreatedInfo.set(bufferStride, vertexCount, isCreate ? vertexBufferIndex : -1); @@ -902,11 +883,15 @@ export class ModelMesh extends Mesh { return vertices; } - private _updateAdvancedVertexElement(present: boolean, attribute: VertexAttribute, flag: VertexElementFlags): void { + private _updateAdvancedVertexElement( + vertices: VertexType[] | null, + attribute: VertexAttribute, + flag: VertexElementFlags + ): void { const primitive = this._primitive; const vertexElementMap = primitive._vertexElementMap; - if (present) { + if (vertices) { if (!vertexElementMap[attribute]) { const format = this._getAttributeFormat(attribute); const offset = this._internalVertexBufferStride; @@ -939,59 +924,59 @@ export class ModelMesh extends Mesh { const advancedElementUpdateFlag = this._advancedElementUpdateFlag; if (advancedElementUpdateFlag & VertexElementFlags.Position) { - this._updateAdvancedVertexElement(!!this._positions, VertexAttribute.Position, VertexElementFlags.Position); + this._updateAdvancedVertexElement(this._positions, VertexAttribute.Position, VertexElementFlags.Position); } if (advancedElementUpdateFlag & VertexElementFlags.Normal) { - this._updateAdvancedVertexElement(!!this._normals, VertexAttribute.Normal, VertexElementFlags.Normal); + this._updateAdvancedVertexElement(this._normals, VertexAttribute.Normal, VertexElementFlags.Normal); } if (advancedElementUpdateFlag & VertexElementFlags.Color) { - this._updateAdvancedVertexElement(!!this._colors, VertexAttribute.Color, VertexElementFlags.Color); + this._updateAdvancedVertexElement(this._colors, VertexAttribute.Color, VertexElementFlags.Color); } if (advancedElementUpdateFlag & VertexElementFlags.BoneWeight) { - this._updateAdvancedVertexElement(!!this._boneWeights, VertexAttribute.BoneWeight, VertexElementFlags.BoneWeight); + this._updateAdvancedVertexElement(this._boneWeights, VertexAttribute.BoneWeight, VertexElementFlags.BoneWeight); } if (advancedElementUpdateFlag & VertexElementFlags.BoneIndex) { - this._updateAdvancedVertexElement(!!this._boneIndices, VertexAttribute.BoneIndex, VertexElementFlags.BoneIndex); + this._updateAdvancedVertexElement(this._boneIndices, VertexAttribute.BoneIndex, VertexElementFlags.BoneIndex); } if (advancedElementUpdateFlag & VertexElementFlags.Tangent) { - this._updateAdvancedVertexElement(!!this._tangents, VertexAttribute.Tangent, VertexElementFlags.Tangent); + this._updateAdvancedVertexElement(this._tangents, VertexAttribute.Tangent, VertexElementFlags.Tangent); } if (advancedElementUpdateFlag & VertexElementFlags.UV) { - this._updateAdvancedVertexElement(!!this._uv, VertexAttribute.UV, VertexElementFlags.UV); + this._updateAdvancedVertexElement(this._uv, VertexAttribute.UV, VertexElementFlags.UV); } if (advancedElementUpdateFlag & VertexElementFlags.UV1) { - this._updateAdvancedVertexElement(!!this._uv1, VertexAttribute.UV1, VertexElementFlags.UV1); + this._updateAdvancedVertexElement(this._uv1, VertexAttribute.UV1, VertexElementFlags.UV1); } if (advancedElementUpdateFlag & VertexElementFlags.UV2) { - this._updateAdvancedVertexElement(!!this._uv2, VertexAttribute.UV2, VertexElementFlags.UV2); + this._updateAdvancedVertexElement(this._uv2, VertexAttribute.UV2, VertexElementFlags.UV2); } if (advancedElementUpdateFlag & VertexElementFlags.UV3) { - this._updateAdvancedVertexElement(!!this._uv3, VertexAttribute.UV3, VertexElementFlags.UV3); + this._updateAdvancedVertexElement(this._uv3, VertexAttribute.UV3, VertexElementFlags.UV3); } if (advancedElementUpdateFlag & VertexElementFlags.UV4) { - this._updateAdvancedVertexElement(!!this._uv4, VertexAttribute.UV4, VertexElementFlags.UV4); + this._updateAdvancedVertexElement(this._uv4, VertexAttribute.UV4, VertexElementFlags.UV4); } if (advancedElementUpdateFlag & VertexElementFlags.UV5) { - this._updateAdvancedVertexElement(!!this._uv5, VertexAttribute.UV5, VertexElementFlags.UV5); + this._updateAdvancedVertexElement(this._uv5, VertexAttribute.UV5, VertexElementFlags.UV5); } if (advancedElementUpdateFlag & VertexElementFlags.UV6) { - this._updateAdvancedVertexElement(!!this._uv6, VertexAttribute.UV6, VertexElementFlags.UV6); + this._updateAdvancedVertexElement(this._uv6, VertexAttribute.UV6, VertexElementFlags.UV6); } if (advancedElementUpdateFlag & VertexElementFlags.UV7) { - this._updateAdvancedVertexElement(!!this._uv7, VertexAttribute.UV7, VertexElementFlags.UV7); + this._updateAdvancedVertexElement(this._uv7, VertexAttribute.UV7, VertexElementFlags.UV7); } } diff --git a/packages/core/src/mesh/PrimitiveMesh.ts b/packages/core/src/mesh/PrimitiveMesh.ts index a41fe5c283..cc5b5cc66b 100644 --- a/packages/core/src/mesh/PrimitiveMesh.ts +++ b/packages/core/src/mesh/PrimitiveMesh.ts @@ -4,7 +4,6 @@ import { GLCapabilityType } from "../base/Constant"; import { BufferBindFlag, BufferUsage, VertexElement, VertexElementFormat } from "../graphic"; import { Buffer } from "../graphic/Buffer"; import { ModelMesh } from "./ModelMesh"; -import { MeshTangentUtils } from "./MeshTangentUtils"; import type { SphereMeshOptions, CuboidMeshOptions, @@ -1997,18 +1996,15 @@ export class PrimitiveMesh { 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, - keepCPUData - ); + const vertexBuffer = new Buffer(mesh.engine, BufferBindFlag.VertexBuffer, vertices, BufferUsage.Static, true); mesh.setVertexBufferBinding(vertexBuffer, 32, 0); - mesh._initializeTangents(MeshTangentUtils.calculateTangentsFromBuffer(vertices, indices), !keepCPUData); mesh.setIndices(indices); + mesh.calculateTangents(); PrimitiveMesh._setBounds(mesh, data); mesh.uploadData(!keepCPUData); + if (!keepCPUData) { + vertexBuffer.markAsUnreadable(); + } mesh.clearSubMesh(); if (options?.separateMaterialSlots && data.groups.length) { for (const group of data.groups) { diff --git a/tests/src/core/mesh/ProceduralMesh.test.ts b/tests/src/core/mesh/ProceduralMesh.test.ts index dd1c6e50b9..f77cb08fda 100644 --- a/tests/src/core/mesh/ProceduralMesh.test.ts +++ b/tests/src/core/mesh/ProceduralMesh.test.ts @@ -9,6 +9,7 @@ import { SetDataOptions, Vector2, Vector3, + Vector4, VertexAttribute, VertexElement, VertexElementFormat, @@ -1813,6 +1814,34 @@ describe("procedural mesh geometry", () => { } }); + it("uses standard tangent access and mutation for primitives", () => { + const mesh = PrimitiveMesh.createPlane(engine, 1, 1, { keepCPUData: 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, { keepCPUData: true }); try { From eaa71d286ca135987776d4f00ecef0e04b7affca Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sat, 14 Nov 2026 23:39:21 +0800 Subject: [PATCH 10/24] docs(core): tighten tangent comments --- packages/core/src/mesh/MeshTangentUtils.ts | 2 +- packages/core/src/mesh/ModelMesh.ts | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/packages/core/src/mesh/MeshTangentUtils.ts b/packages/core/src/mesh/MeshTangentUtils.ts index 1d7997c837..3df94c5708 100644 --- a/packages/core/src/mesh/MeshTangentUtils.ts +++ b/packages/core/src/mesh/MeshTangentUtils.ts @@ -26,7 +26,7 @@ export class MeshTangentUtils { ): Vector4[] | Float32Array { const vertexCount = vertices ? vertices.length / 8 : positions!.length; const indexCount = indices ? indices.length : vertexCount; - // Accumulate in double precision before converting to the GPU buffer format + // Accumulate the tangent basis in double precision const basis = new Float64Array(vertexCount * 6); for (let i = 0; i < indexCount; i += 3) { const a = indices ? indices[i] : i; diff --git a/packages/core/src/mesh/ModelMesh.ts b/packages/core/src/mesh/ModelMesh.ts index 99646dc576..f94fb69174 100644 --- a/packages/core/src/mesh/ModelMesh.ts +++ b/packages/core/src/mesh/ModelMesh.ts @@ -668,11 +668,10 @@ export class ModelMesh extends Mesh { } /** - * Calculate tangent vectors from the mesh's positions, normals and UV coordinates. + * Calculate tangents from readable positions, normals and UVs. * @remarks - * Position, normal and UV data must be readable. - * Without indices, each consecutive triplet of vertices forms a triangle. - * Triangles with degenerate UV coordinates do not contribute to the tangent basis. + * Without indices, every three consecutive vertices form a triangle. + * Triangles with zero UV area are ignored. * @see http://foundationsofgameenginedev.com/FGED2-sample.pdf */ calculateTangents(): void { From 309f902bdf22d018b22643a615c2f23e7dbdae9f Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sat, 14 Nov 2026 23:52:35 +0800 Subject: [PATCH 11/24] test(core): cover vertex buffer listener lifecycle --- tests/src/core/ModelMesh.test.ts | 98 +++++++++++++++++++++- tests/src/core/mesh/ProceduralMesh.test.ts | 2 + 2 files changed, 99 insertions(+), 1 deletion(-) 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/mesh/ProceduralMesh.test.ts b/tests/src/core/mesh/ProceduralMesh.test.ts index f77cb08fda..d4fada769d 100644 --- a/tests/src/core/mesh/ProceduralMesh.test.ts +++ b/tests/src/core/mesh/ProceduralMesh.test.ts @@ -1663,6 +1663,8 @@ describe("procedural mesh geometry", () => { 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); From 75bf822962724265b6ddc15346abf8201c4d1b26 Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sun, 15 Nov 2026 00:00:17 +0800 Subject: [PATCH 12/24] refactor(core): remove redundant mesh checks --- packages/core/src/mesh/ModelMesh.ts | 13 ++++--------- packages/core/src/mesh/PrimitiveMesh.ts | 1 - packages/core/src/mesh/primitive/PolygonUtils.ts | 6 +----- 3 files changed, 5 insertions(+), 15 deletions(-) diff --git a/packages/core/src/mesh/ModelMesh.ts b/packages/core/src/mesh/ModelMesh.ts index f94fb69174..15b02319ca 100644 --- a/packages/core/src/mesh/ModelMesh.ts +++ b/packages/core/src/mesh/ModelMesh.ts @@ -695,7 +695,7 @@ export class ModelMesh extends Mesh { let updateInfo = updateInfos[index]; const previousBinding = vertexBufferBindings[index]; - if (previousBinding && updateInfo) { + if (previousBinding) { previousBinding.buffer._dataUpdateManager.removeListener(updateInfo.onBufferChanged); } @@ -712,10 +712,8 @@ export class ModelMesh extends Mesh { binding.buffer._dataUpdateManager.addListener(updateInfo.onBufferChanged); updateInfo.reset(); updateInfo.onBufferChanged(); - } else { - if (index + 1 == vertexBufferBindings.length) { - vertexBufferBindings.length--; - } + } else if (index + 1 == vertexBufferBindings.length) { + vertexBufferBindings.length--; } } @@ -743,10 +741,7 @@ export class ModelMesh extends Mesh { protected override _onDestroy(): void { const bindings = this._primitive.vertexBufferBindings; for (let i = 0; i < bindings.length; i++) { - const updateInfo = this._vertexBufferInfos[i]; - if (updateInfo) { - bindings[i]?.buffer._dataUpdateManager.removeListener(updateInfo.onBufferChanged); - } + bindings[i]?.buffer._dataUpdateManager.removeListener(this._vertexBufferInfos[i].onBufferChanged); } super._onDestroy(); this._releaseCache(true); diff --git a/packages/core/src/mesh/PrimitiveMesh.ts b/packages/core/src/mesh/PrimitiveMesh.ts index cc5b5cc66b..3b3ac9b870 100644 --- a/packages/core/src/mesh/PrimitiveMesh.ts +++ b/packages/core/src/mesh/PrimitiveMesh.ts @@ -2005,7 +2005,6 @@ export class PrimitiveMesh { if (!keepCPUData) { vertexBuffer.markAsUnreadable(); } - mesh.clearSubMesh(); if (options?.separateMaterialSlots && data.groups.length) { for (const group of data.groups) { mesh.addSubMesh(group.start, group.count); diff --git a/packages/core/src/mesh/primitive/PolygonUtils.ts b/packages/core/src/mesh/primitive/PolygonUtils.ts index 830dcf1c82..ec9c9d5172 100644 --- a/packages/core/src/mesh/primitive/PolygonUtils.ts +++ b/packages/core/src/mesh/primitive/PolygonUtils.ts @@ -662,11 +662,7 @@ export class PolygonUtils { const px = (a.x + b.x) / 2; const py = (a.y + b.y) / 2; do { - if ( - p.y > py !== p.next.y > py && - p.next.y !== p.y && - px < ((p.next.x - p.x) * (py - p.y)) / (p.next.y - p.y) + p.x - ) { + 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; From 43850cbc14e78ae8943cd4f087ab1bc48e9e3e58 Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sun, 15 Nov 2026 00:18:54 +0800 Subject: [PATCH 13/24] refactor(loader): derive serialized primitive shapes --- packages/loader/src/PrimitiveMeshAsset.ts | 40 ++++++++++--------- packages/loader/src/PrimitiveMeshLoader.ts | 4 +- .../fixtures/PrimitiveMeshAsset.ts | 25 ++++++++++++ 3 files changed, 49 insertions(+), 20 deletions(-) diff --git a/packages/loader/src/PrimitiveMeshAsset.ts b/packages/loader/src/PrimitiveMeshAsset.ts index 7eeea17d6b..9cdf73e911 100644 --- a/packages/loader/src/PrimitiveMeshAsset.ts +++ b/packages/loader/src/PrimitiveMeshAsset.ts @@ -9,6 +9,7 @@ import type { PathExtrudedPolygonMeshOptions, PlaneMeshOptions, PolygonMeshOptions, + PolygonShape, RegularPolyhedronMeshOptions, RingMeshOptions, RoundedCuboidMeshOptions, @@ -18,19 +19,22 @@ import type { TruncatedConeMeshOptions, TubeMeshOptions } from "@galacean/engine-core"; -import type { Vector2 } from "@galacean/engine-math"; +import type { Vector2, Vector3 } from "@galacean/engine-math"; /** * @internal */ -export type SerializedPrimitiveMeshOptions = { - [Key in keyof T]: Extract extends never ? T[Key] : { x: number; y: number }; +export type SerializedPrimitiveMeshData = { + [Key in keyof T]: SerializedPrimitiveMeshValue; }; -type SerializedPolygonShape = { - points: readonly { x: number; y: number }[]; - holes?: readonly (readonly { x: number; y: number }[])[]; -}; +type SerializedPrimitiveMeshValue = T extends Vector2 | Vector3 + ? ReturnType + : T extends object + ? SerializedPrimitiveMeshData + : T; + +type SerializedPolygonShape = SerializedPrimitiveMeshData; /** * Serialized inputs and optional settings for every primitive mesh factory. @@ -43,7 +47,7 @@ export type PrimitiveMeshAsset = * The radius in local units. */ sphereRadius: number; - sphereOptions?: SerializedPrimitiveMeshOptions; + sphereOptions?: SerializedPrimitiveMeshData; } | { type: "cuboid"; @@ -83,7 +87,7 @@ export type PrimitiveMeshAsset = * The full size along Y in local units. */ cylinderHeight: number; - cylinderOptions?: SerializedPrimitiveMeshOptions; + cylinderOptions?: SerializedPrimitiveMeshData; } | { type: "truncatedCone"; @@ -99,7 +103,7 @@ export type PrimitiveMeshAsset = * The full size along Y in local units. */ truncatedConeHeight: number; - truncatedConeOptions?: SerializedPrimitiveMeshOptions; + truncatedConeOptions?: SerializedPrimitiveMeshData; } | { type: "cone"; @@ -111,7 +115,7 @@ export type PrimitiveMeshAsset = * The full size along Y in local units. */ coneHeight: number; - coneOptions?: SerializedPrimitiveMeshOptions; + coneOptions?: SerializedPrimitiveMeshData; } | { type: "capsule"; @@ -135,7 +139,7 @@ export type PrimitiveMeshAsset = * The radius of the tube cross-section in local units. */ torusTubeRadius: number; - torusOptions?: SerializedPrimitiveMeshOptions; + torusOptions?: SerializedPrimitiveMeshData; } | { type: "circle"; @@ -143,7 +147,7 @@ export type PrimitiveMeshAsset = * The radius in local units. */ circleRadius: number; - circleOptions?: SerializedPrimitiveMeshOptions; + circleOptions?: SerializedPrimitiveMeshData; } | { type: "ring"; @@ -155,7 +159,7 @@ export type PrimitiveMeshAsset = * The inner radius in local units. */ ringInnerRadius: number; - ringOptions?: SerializedPrimitiveMeshOptions; + ringOptions?: SerializedPrimitiveMeshData; } | { type: "tetrahedron"; @@ -191,12 +195,12 @@ export type PrimitiveMeshAsset = } | { type: "lathe"; - latheProfile: readonly { x: number; y: number }[]; - latheOptions?: SerializedPrimitiveMeshOptions; + latheProfile: SerializedPrimitiveMeshData; + latheOptions?: SerializedPrimitiveMeshData; } | { type: "tube"; - tubePath: readonly { x: number; y: number; z: number }[]; + tubePath: SerializedPrimitiveMeshData; /** * The radius of the cross-section in local units. */ @@ -222,7 +226,7 @@ export type PrimitiveMeshAsset = /** * The path points in local coordinates. */ - extrudedPolygonPath: readonly { x: number; y: number; z: number }[]; + extrudedPolygonPath: SerializedPrimitiveMeshData; extrudedPolygonShapes: readonly SerializedPolygonShape[]; extrudedPolygonOptions?: PathExtrudedPolygonMeshOptions; } diff --git a/packages/loader/src/PrimitiveMeshLoader.ts b/packages/loader/src/PrimitiveMeshLoader.ts index 5f769a7284..46c2ebaaba 100644 --- a/packages/loader/src/PrimitiveMeshLoader.ts +++ b/packages/loader/src/PrimitiveMeshLoader.ts @@ -11,7 +11,7 @@ import { resourceLoader } from "@galacean/engine-core"; import { Vector2, Vector3 } from "@galacean/engine-math"; -import type { PrimitiveMeshAsset, SerializedPrimitiveMeshOptions } from "./PrimitiveMeshAsset"; +import type { PrimitiveMeshAsset, SerializedPrimitiveMeshData } from "./PrimitiveMeshAsset"; @resourceLoader(AssetType.PrimitiveMesh, ["mesh"], false) class PrimitiveMeshLoader extends Loader { @@ -134,7 +134,7 @@ class PrimitiveMeshLoader extends Loader { } } - private _parseRangeOptions(options: SerializedPrimitiveMeshOptions | undefined): T | undefined { + private _parseRangeOptions(options: SerializedPrimitiveMeshData | undefined): T | undefined { if (!options) { return; } diff --git a/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts index fbef7d6c0b..f1e060b4ef 100644 --- a/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts +++ b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts @@ -44,6 +44,28 @@ const shapes = [ } ] 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 = { @@ -151,6 +173,9 @@ void [ exportedFromEngine, sphereSection, ungroupedSphere, + polygonWithHoles, + invalidHolePoint, + invalidPathPoint, tube, polygon, extrudedPolygon, From cf1a786ccafdb3384d66f5cbe9ebc5a2a14888e1 Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sun, 15 Nov 2026 00:25:33 +0800 Subject: [PATCH 14/24] refactor(loader): inline serialized polygon types --- packages/loader/src/PrimitiveMeshAsset.ts | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/packages/loader/src/PrimitiveMeshAsset.ts b/packages/loader/src/PrimitiveMeshAsset.ts index 9cdf73e911..cb331bbdc2 100644 --- a/packages/loader/src/PrimitiveMeshAsset.ts +++ b/packages/loader/src/PrimitiveMeshAsset.ts @@ -34,8 +34,6 @@ type SerializedPrimitiveMeshValue = T extends Vector2 | Vector3 ? SerializedPrimitiveMeshData : T; -type SerializedPolygonShape = SerializedPrimitiveMeshData; - /** * 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. @@ -209,7 +207,7 @@ export type PrimitiveMeshAsset = } | { type: "polygon"; - polygonShapes: readonly SerializedPolygonShape[]; + polygonShapes: readonly SerializedPrimitiveMeshData[]; polygonOptions?: PolygonMeshOptions; } | { @@ -218,7 +216,7 @@ export type PrimitiveMeshAsset = * The total extrusion depth in local units, including both bevels. */ extrudedPolygonDepth: number; - extrudedPolygonShapes: readonly SerializedPolygonShape[]; + extrudedPolygonShapes: readonly SerializedPrimitiveMeshData[]; extrudedPolygonOptions?: LinearExtrudedPolygonMeshOptions; } | { @@ -227,7 +225,7 @@ export type PrimitiveMeshAsset = * The path points in local coordinates. */ extrudedPolygonPath: SerializedPrimitiveMeshData; - extrudedPolygonShapes: readonly SerializedPolygonShape[]; + extrudedPolygonShapes: readonly SerializedPrimitiveMeshData[]; extrudedPolygonOptions?: PathExtrudedPolygonMeshOptions; } | { From 57ee6775e97efa7d0ecf6c2ca43270d1edf4c926 Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sun, 15 Nov 2026 00:34:15 +0800 Subject: [PATCH 15/24] perf(loader): avoid unnecessary primitive option copies --- packages/loader/src/PrimitiveMeshLoader.ts | 6 ++--- tests/src/loader/PrimitiveMeshLoader.test.ts | 24 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/packages/loader/src/PrimitiveMeshLoader.ts b/packages/loader/src/PrimitiveMeshLoader.ts index 46c2ebaaba..e7a3e29852 100644 --- a/packages/loader/src/PrimitiveMeshLoader.ts +++ b/packages/loader/src/PrimitiveMeshLoader.ts @@ -138,15 +138,15 @@ class PrimitiveMeshLoader extends Loader { if (!options) { return; } - const result = { ...options } as T; + 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[key] = new Vector2(range.x, range.y) as T[typeof key]; + (result ??= { ...options } as T)[key] = new Vector2(range.x, range.y) as T[typeof key]; } } - return result; + return result ?? (options as T); } private _parseVector2s(points: readonly { x: number; y: number }[]): Vector2[] { diff --git a/tests/src/loader/PrimitiveMeshLoader.test.ts b/tests/src/loader/PrimitiveMeshLoader.test.ts index 84dfd89b4e..8547b09a36 100644 --- a/tests/src/loader/PrimitiveMeshLoader.test.ts +++ b/tests/src/loader/PrimitiveMeshLoader.test.ts @@ -616,6 +616,29 @@ describe("PrimitiveMeshLoader", () => { } }); + it.each([{}, { subdivisionLevel: 1, keepCPUData: 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", @@ -629,6 +652,7 @@ describe("PrimitiveMeshLoader", () => { 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 }); From 5ba172b4e8328c16a7f0cc0ad7453f4cfa007c56 Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sun, 15 Nov 2026 00:38:11 +0800 Subject: [PATCH 16/24] refactor(loader): clarify primitive parser input types --- packages/loader/src/PrimitiveMeshLoader.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/loader/src/PrimitiveMeshLoader.ts b/packages/loader/src/PrimitiveMeshLoader.ts index e7a3e29852..718f9e33d3 100644 --- a/packages/loader/src/PrimitiveMeshLoader.ts +++ b/packages/loader/src/PrimitiveMeshLoader.ts @@ -149,15 +149,15 @@ class PrimitiveMeshLoader extends Loader { return result ?? (options as T); } - private _parseVector2s(points: readonly { x: number; y: number }[]): Vector2[] { + private _parseVector2s(points: SerializedPrimitiveMeshData): Vector2[] { return points.map(({ x, y }) => new Vector2(x, y)); } - private _parseVector3s(points: readonly { x: number; y: number; z: number }[]): Vector3[] { + private _parseVector3s(points: SerializedPrimitiveMeshData): Vector3[] { return points.map(({ x, y, z }) => new Vector3(x, y, z)); } - private _parseShapes(shapes: Extract["polygonShapes"]): PolygonShape[] { + private _parseShapes(shapes: readonly SerializedPrimitiveMeshData[]): PolygonShape[] { return shapes.map(({ points, holes }) => ({ points: this._parseVector2s(points), holes: holes?.map((hole) => this._parseVector2s(hole)) From 7b40aeb0dcb5268f19c3b35c9d3971c6d9e45e81 Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sun, 15 Nov 2026 01:17:53 +0800 Subject: [PATCH 17/24] fix(core): preserve non-indexed primitive restoration --- packages/core/src/mesh/PrimitiveMesh.ts | 2 +- .../mesh/primitive/PrimitiveMeshRestorer.ts | 8 ++-- tests/src/core/mesh/ProceduralMesh.test.ts | 39 +++++++++++++++++++ 3 files changed, 44 insertions(+), 5 deletions(-) diff --git a/packages/core/src/mesh/PrimitiveMesh.ts b/packages/core/src/mesh/PrimitiveMesh.ts index 3b3ac9b870..b4f0f67f0b 100644 --- a/packages/core/src/mesh/PrimitiveMesh.ts +++ b/packages/core/src/mesh/PrimitiveMesh.ts @@ -1976,7 +1976,7 @@ export class PrimitiveMesh { private static _createMesh( engine: Engine, generate: (...args: T) => PrimitiveMeshBuilder, - args: T, + args: [...T], options?: { keepCPUData?: boolean; separateMaterialSlots?: boolean } ): ModelMesh { const keepCPUData = options?.keepCPUData ?? false; diff --git a/packages/core/src/mesh/primitive/PrimitiveMeshRestorer.ts b/packages/core/src/mesh/primitive/PrimitiveMeshRestorer.ts index b5fbe3949b..b2bf1a5ee2 100644 --- a/packages/core/src/mesh/primitive/PrimitiveMeshRestorer.ts +++ b/packages/core/src/mesh/primitive/PrimitiveMeshRestorer.ts @@ -26,6 +26,7 @@ export class PrimitiveMeshRestorer extends ContentRestorer< override restoreContent(): void { const mesh = this.resource; const vertexBuffer = this._vertexBuffer; + const indexBuffer = mesh._primitive.indexBufferBinding?._buffer; const indices = mesh.accessible ? mesh.getIndices() : null; let generated: PrimitiveMeshBuilder | undefined; // Only regenerate owned buffers; readable data includes changes made after creation @@ -40,15 +41,14 @@ export class PrimitiveMeshRestorer extends ContentRestorer< generated ??= this._generateData(); buffer.setData(generated.vertices); } else if (buffer === this._tangentBuffer) { - generated ??= this._generateData(); const vertexData = vertexBuffer.readable ? vertexBuffer.data : null; const vertices = vertexData ? new Float32Array(vertexData.buffer, vertexData.byteOffset, vertexBuffer.byteLength / 4) - : generated.vertices; - buffer.setData(MeshTangentUtils.calculateTangentsFromBuffer(vertices, indices ?? generated.indices)); + : (generated ??= this._generateData()).vertices; + const tangentIndices = indexBuffer ? (indices ?? (generated ??= this._generateData()).indices) : null; + buffer.setData(MeshTangentUtils.calculateTangentsFromBuffer(vertices, tangentIndices)); } } - const indexBuffer = mesh._primitive.indexBufferBinding?._buffer; if (indexBuffer) { if (indices) { indexBuffer.setData(indices); diff --git a/tests/src/core/mesh/ProceduralMesh.test.ts b/tests/src/core/mesh/ProceduralMesh.test.ts index d4fada769d..fcf2a5aa98 100644 --- a/tests/src/core/mesh/ProceduralMesh.test.ts +++ b/tests/src/core/mesh/ProceduralMesh.test.ts @@ -1757,6 +1757,45 @@ describe("procedural mesh geometry", () => { } }); + it.each([false, true])("restores non-indexed primitive tangents with released data: %s", (releaseData) => { + const mesh = PrimitiveMesh.createPlane(engine, 1, 1, { + widthSegments: 2, + depthSegments: 1, + keepCPUData: true + }); + try { + mesh.setPositions([ + new Vector3(0, 0, 0), + new Vector3(1, 0, 0), + new Vector3(0, 1, 0), + new Vector3(2, 0, 0), + new Vector3(3, 0, 0), + new Vector3(2, 1, 0) + ]); + mesh.setNormals(Array.from({ length: 6 }, () => new Vector3(0, 0, 1))); + mesh.setUVs([ + new Vector2(0, 0), + new Vector2(1, 0), + new Vector2(0, 1), + new Vector2(0, 0), + new Vector2(0, 1), + new Vector2(1, 0) + ]); + mesh.setIndices(null); + mesh.clearSubMesh(); + mesh.addSubMesh(0, 6); + mesh.calculateTangents(); + mesh.uploadData(releaseData); + const tangentBuffer = mesh.vertexBufferBindings[1]!.buffer; + const original = MeshTestUtils.readBuffer(tangentBuffer); + MeshTestUtils.clearBuffer(tangentBuffer); + (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); + expect(MeshTestUtils.readBuffer(tangentBuffer)).toEqual(original); + } finally { + mesh.destroy(); + } + }); + it.each([1, 1e-8])("normalizes tangents for a plane of size %s", (size) => { const mesh = PrimitiveMesh.createPlane(engine, size, size, { keepCPUData: true, From 032c33a7074df70d065263e79fa9450d88318196 Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sun, 15 Nov 2026 01:18:14 +0800 Subject: [PATCH 18/24] test(e2e): refresh primitive rendering baselines --- e2e/config.ts | 44 +++++++++---------- ...UInstancing_gpu-instancing-custom-data.jpg | 4 +- ...ticleRenderer-emit-billboard-stretched.jpg | 4 +- ...h-cone-scale-3d-rotation-life-seperate.jpg | 4 +- ...derer-emit-mesh-cone-scale-3d-rotation.jpg | 4 +- ...mesh-cone-scale-rotation-life-seperate.jpg | 4 +- ...rer-emit-mesh-cone-scale-rotation-life.jpg | 4 +- ...er-emit-mesh-cone-scale-rotation-world.jpg | 4 +- ...Renderer-emit-mesh-cone-scale-rotation.jpg | 4 +- ...rticle_particleRenderer-emit-mesh-cone.jpg | 4 +- ...ticleRenderer-emit-mesh-no-shape-world.jpg | 4 +- ...le_particleRenderer-emit-mesh-no-shape.jpg | 4 +- .../Primitive_primitive-capsule.jpg | 4 +- .../Primitive_primitive-cylinder.jpg | 4 +- e2e/primitive-mesh.md | 2 + 15 files changed, 50 insertions(+), 48 deletions(-) diff --git a/e2e/config.ts b/e2e/config.ts index 162d4dd6d4..3e182f0302 100644 --- a/e2e/config.ts +++ b/e2e/config.ts @@ -232,43 +232,43 @@ export const E2E_CONFIG = { sections: { category: "Primitive", caseFileName: "primitive-sections", - threshold: 0, + threshold: 0.005, diffPercentage: 0.02 }, contours: { category: "Primitive", caseFileName: "primitive-contours", - threshold: 0, + threshold: 0.005, diffPercentage: 0.02 }, topology: { category: "Primitive", caseFileName: "primitive-topology", - threshold: 0, + threshold: 0.005, diffPercentage: 0.02 }, materials: { category: "Primitive", caseFileName: "primitive-materials", - threshold: 0, + threshold: 0.005, diffPercentage: 0.02 }, "sphere-sections": { category: "Primitive", caseFileName: "primitive-sphere-sections", - threshold: 0, + threshold: 0.005, diffPercentage: 0.02 }, all: { category: "Primitive", caseFileName: "primitive-all", - threshold: 0, + threshold: 0.005, diffPercentage: 0.02 }, capsule: { category: "Primitive", caseFileName: "primitive-capsule", - threshold: 0, + threshold: 0.005, diffPercentage: 0.0016 }, cone: { @@ -280,13 +280,13 @@ export const E2E_CONFIG = { cuboid: { category: "Primitive", caseFileName: "primitive-cuboid", - threshold: 0, + threshold: 0.005, diffPercentage: 0.0016 }, cylinder: { category: "Primitive", caseFileName: "primitive-cylinder", - threshold: 0, + threshold: 0.005, diffPercentage: 0.0036 }, plane: { @@ -418,55 +418,55 @@ export const E2E_CONFIG = { particleEmitMeshNoShape: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-no-shape", - threshold: 0, + threshold: 0.005, diffPercentage: 0.00136 }, particleEmitMeshCone: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-cone", - threshold: 0, + threshold: 0.005, diffPercentage: 0.00219 }, particleEmitMeshConeScaleRotation: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-cone-scale-rotation", - threshold: 0, + threshold: 0.005, diffPercentage: 0.0031 }, particleEmitMeshConeScaleRotationWorld: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-cone-scale-rotation-world", - threshold: 0, + threshold: 0.005, diffPercentage: 0.00928 }, particleEmitMeshNoShapeWorld: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-no-shape-world", - threshold: 0, + threshold: 0.005, diffPercentage: 0.00146 }, particleEmitMeshConeScale3DRotation: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-cone-scale-3d-rotation", - threshold: 0, + threshold: 0.005, diffPercentage: 0.0184 }, particleEmitMeshConeScaleRotationLife: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-cone-scale-rotation-life", - threshold: 0, + threshold: 0.005, diffPercentage: 0.036459 }, particleEmitMeshConeScaleRotationLifeSeperate: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-cone-scale-rotation-life-seperate", - threshold: 0, + threshold: 0.005, diffPercentage: 0.0068 }, particleEmitMeshConeScale3DRotationLifeSeperate: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-cone-scale-3d-rotation-life-seperate", - threshold: 0, + threshold: 0.005, diffPercentage: 0.00782 }, particleEmitMeshRotationLifeCurve: { @@ -484,7 +484,7 @@ export const E2E_CONFIG = { particleEmitBillboardStretched: { category: "Particle", caseFileName: "particleRenderer-emit-billboard-stretched", - threshold: 0, + threshold: 0.005, diffPercentage: 0.0 }, inheritVelocityStretched: { @@ -546,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/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/Particle_particleRenderer-emit-billboard-stretched.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-billboard-stretched.jpg index 6a8de173f3..b42ed8ecdf 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-billboard-stretched.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-billboard-stretched.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a21cb5ef10639a2fc5261d552e131c8ddfad8ad74d3fcd8dac0b5cdfafb1e06e -size 54304 +oid sha256:bcb242517e6a247e9134022e68da589222effb66fe23612f72fbb7790526af0f +size 55860 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-3d-rotation-life-seperate.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-3d-rotation-life-seperate.jpg index 4e41693021..88dba3763b 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-3d-rotation-life-seperate.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-3d-rotation-life-seperate.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:05dde457049ed9276cc12d328d88a8d5a3178a0ef77cb80d84d8b54b88481817 -size 168814 +oid sha256:23071f38dabccc3492958c8daea8c5e30303cd0d57ba436cbe66c627e8f63340 +size 173330 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-3d-rotation.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-3d-rotation.jpg index 86a5668b2b..581e40b561 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-3d-rotation.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-3d-rotation.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1a7694f1cb9c84c7b7961644b0c46ce776464052332610710323036f01ae948e -size 165653 +oid sha256:26e7b9cc91b4eecebde7bc664e103c0de374ff9ddcd20107ac15f2e5d64e088b +size 197456 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-life-seperate.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-life-seperate.jpg index 29a5d409df..06754c710a 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-life-seperate.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-life-seperate.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1fb9fa66aef3f361ab6f7c3e0b74adf12eb500728a8ea784a0013e1f87886c2a -size 133674 +oid sha256:40288944c6145a22c0b9b8925b746568f18c7b59635c5ccb425c737638eacff8 +size 157777 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-life.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-life.jpg index 67ffe795b0..32ec984f8d 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-life.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-life.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:24e4b97384202cf7c0c05ca63064a38c40aeace3fdf494e9852ff8f06100f3b4 -size 189203 +oid sha256:7ff09f82e4b26cf91c5070575e371aa5a1f1ca921cc9597dd680c13e277bf83b +size 181501 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-world.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-world.jpg index dad85120f5..2efa701fb6 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-world.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-world.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0ffd8248dcdae4bdfc04e430b2ad4ba9380bf1a95dd1afbff30bba67aa7ba625 -size 143461 +oid sha256:04c5df34da746da36a0a28c4a3a4d464e658835e1374b9cdad24d99629115db0 +size 148015 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation.jpg index f4d8da466a..1e5952c676 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:e4d73c785ea2b6a5322f2067dd7c9f92b101f068bda61334f4f0d7486b593095 -size 244846 +oid sha256:9f0e3e3bea6bb4c7e2850ba66856216503124468c6f6a2545526a76c68b63769 +size 233910 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone.jpg index 291522d4ce..c944d6ad7d 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:154344f6c6ef52832319dde824e4035ffcabce4484fbbd616bc66da8956ee300 -size 178327 +oid sha256:16c2d3d1ac6bc04fe1d2ffbbb726f04d119f6220a59e41381506a042552f76fe +size 184788 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-no-shape-world.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-no-shape-world.jpg index 99c03f99c5..545f9c0def 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-no-shape-world.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-no-shape-world.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b4db419900abc3caef3aa52a9c7388007f65eb1894e87ba8c9e2150025a0a5d8 -size 78327 +oid sha256:22f14f13f5c99abcd826ab81e283b4bcadde09d4bdb82435f44a785b62ce1d08 +size 57705 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-no-shape.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-no-shape.jpg index 235adea154..28f4927d93 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-no-shape.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-no-shape.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:08d65b43eadae85d6828cc41c957a2e0fcf7c33af4dec0b77ae62fe80ee3f1ea -size 67130 +oid sha256:36f34e92d138bc0cec7a5dd7a4c21d4830b5ac47bda0383003c0c8868b0bfddb +size 68831 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-cylinder.jpg b/e2e/fixtures/originImage/Primitive_primitive-cylinder.jpg index b234dddcff..a169161330 100644 --- a/e2e/fixtures/originImage/Primitive_primitive-cylinder.jpg +++ b/e2e/fixtures/originImage/Primitive_primitive-cylinder.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b4736d2feef50a0da43e1b73a7fe33ff54c7866fad44907051b1194937435959 -size 99016 +oid sha256:76b76bda3e2e370c0d5385b916c9b1ce177ee79f5a33ca10d24e08b3b3dcdb14 +size 99097 diff --git a/e2e/primitive-mesh.md b/e2e/primitive-mesh.md index b3a4e52348..ade86243e6 100644 --- a/e2e/primitive-mesh.md +++ b/e2e/primitive-mesh.md @@ -21,4 +21,6 @@ After changing engine package sources, run `pnpm run build` before the tests. To 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. Cylinder and capsule UV changes also update the older primitive and particle baselines that use those meshes. + 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. From 763c502906f4419cfdb232180275f005d7c62b77 Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sun, 15 Nov 2026 01:38:51 +0800 Subject: [PATCH 19/24] fix(core): preserve cylinder texture and cap ordering --- docs/en/graphics/mesh/primitiveMesh.mdx | 2 +- docs/zh/graphics/mesh/primitiveMesh.mdx | 2 +- e2e/config.ts | 22 ++--- ...ticleRenderer-emit-billboard-stretched.jpg | 4 +- ...h-cone-scale-3d-rotation-life-seperate.jpg | 4 +- ...derer-emit-mesh-cone-scale-3d-rotation.jpg | 4 +- ...mesh-cone-scale-rotation-life-seperate.jpg | 4 +- ...rer-emit-mesh-cone-scale-rotation-life.jpg | 4 +- ...er-emit-mesh-cone-scale-rotation-world.jpg | 4 +- ...Renderer-emit-mesh-cone-scale-rotation.jpg | 4 +- ...rticle_particleRenderer-emit-mesh-cone.jpg | 4 +- ...ticleRenderer-emit-mesh-no-shape-world.jpg | 4 +- ...le_particleRenderer-emit-mesh-no-shape.jpg | 4 +- .../originImage/Primitive_primitive-all.jpg | 4 +- .../Primitive_primitive-cylinder.jpg | 4 +- .../Primitive_primitive-sections.jpg | 4 +- e2e/primitive-mesh.md | 2 +- packages/core/src/mesh/PrimitiveMesh.ts | 48 ++++++---- .../core/src/mesh/PrimitiveMeshOptions.ts | 6 +- tests/src/core/mesh/ProceduralMesh.test.ts | 89 +++++++++++++++++++ 20 files changed, 164 insertions(+), 59 deletions(-) diff --git a/docs/en/graphics/mesh/primitiveMesh.mdx b/docs/en/graphics/mesh/primitiveMesh.mdx index cdff42baa5..4006df81ad 100644 --- a/docs/en/graphics/mesh/primitiveMesh.mdx +++ b/docs/en/graphics/mesh/primitiveMesh.mdx @@ -161,7 +161,7 @@ For torus knots, `axisTurns` counts revolutions around the central axis and `cro 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, cones and lathes rotate around Y starting from +Z; a sphere's vertical angle starts at +Y. +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; lathes start from +Z towards +X. A sphere's vertical angle starts at +Y. ```ts import { PrimitiveMeshCapMode, Vector2 } from "@galacean/engine"; diff --git a/docs/zh/graphics/mesh/primitiveMesh.mdx b/docs/zh/graphics/mesh/primitiveMesh.mdx index 313da8f9db..915d699e01 100644 --- a/docs/zh/graphics/mesh/primitiveMesh.mdx +++ b/docs/zh/graphics/mesh/primitiveMesh.mdx @@ -165,7 +165,7 @@ const mirroredKnot = PrimitiveMesh.createTorusKnot(engine, 1, 0.1, 2, -3); 管道和环面结用 `pathSegments` 控制沿路径的分段,圆环用 `ringSegments` 控制环向分段,`radialSegments` 控制管截面的周向分段。胶囊的 `capSegments` 控制每个半球从极点到赤道的分段,`cylinderHeight` 表示直筒部分的高度。正多面体用 `edgeSegments`,圆角长方体用 `roundingSegments`。 -角度范围统一放在配置对象中。所有角度均使用**度数**,范围使用 `Vector2`,`x` 表示起始角,`y` 表示结束角。跨越 360 度时使用连续角度,例如 `new Vector2(350, 370)`。圆柱、圆锥和旋转体围绕 Y 轴,0 度从 +Z 方向开始;球体的垂直角度从 +Y 极点开始。 +角度范围统一放在配置对象中。所有角度均使用**度数**,范围使用 `Vector2`,`x` 表示起始角,`y` 表示结束角。跨越 360 度时使用连续角度,例如 `new Vector2(350, 370)`。圆柱、圆台和圆锥围绕 Y 轴,从 -Z 朝 -X 方向开始;旋转体从 +Z 朝 +X 方向开始。球体的垂直角度从 +Y 极点开始。 ```ts import { PrimitiveMeshCapMode, Vector2 } from "@galacean/engine"; diff --git a/e2e/config.ts b/e2e/config.ts index 3e182f0302..0a6c444235 100644 --- a/e2e/config.ts +++ b/e2e/config.ts @@ -286,7 +286,7 @@ export const E2E_CONFIG = { cylinder: { category: "Primitive", caseFileName: "primitive-cylinder", - threshold: 0.005, + threshold: 0, diffPercentage: 0.0036 }, plane: { @@ -418,55 +418,55 @@ export const E2E_CONFIG = { particleEmitMeshNoShape: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-no-shape", - threshold: 0.005, + threshold: 0, diffPercentage: 0.00136 }, particleEmitMeshCone: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-cone", - threshold: 0.005, + threshold: 0, diffPercentage: 0.00219 }, particleEmitMeshConeScaleRotation: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-cone-scale-rotation", - threshold: 0.005, + threshold: 0, diffPercentage: 0.0031 }, particleEmitMeshConeScaleRotationWorld: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-cone-scale-rotation-world", - threshold: 0.005, + threshold: 0, diffPercentage: 0.00928 }, particleEmitMeshNoShapeWorld: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-no-shape-world", - threshold: 0.005, + threshold: 0, diffPercentage: 0.00146 }, particleEmitMeshConeScale3DRotation: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-cone-scale-3d-rotation", - threshold: 0.005, + threshold: 0, diffPercentage: 0.0184 }, particleEmitMeshConeScaleRotationLife: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-cone-scale-rotation-life", - threshold: 0.005, + threshold: 0, diffPercentage: 0.036459 }, particleEmitMeshConeScaleRotationLifeSeperate: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-cone-scale-rotation-life-seperate", - threshold: 0.005, + threshold: 0, diffPercentage: 0.0068 }, particleEmitMeshConeScale3DRotationLifeSeperate: { category: "Particle", caseFileName: "particleRenderer-emit-mesh-cone-scale-3d-rotation-life-seperate", - threshold: 0.005, + threshold: 0, diffPercentage: 0.00782 }, particleEmitMeshRotationLifeCurve: { @@ -484,7 +484,7 @@ export const E2E_CONFIG = { particleEmitBillboardStretched: { category: "Particle", caseFileName: "particleRenderer-emit-billboard-stretched", - threshold: 0.005, + threshold: 0, diffPercentage: 0.0 }, inheritVelocityStretched: { diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-billboard-stretched.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-billboard-stretched.jpg index b42ed8ecdf..6a8de173f3 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-billboard-stretched.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-billboard-stretched.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:bcb242517e6a247e9134022e68da589222effb66fe23612f72fbb7790526af0f -size 55860 +oid sha256:a21cb5ef10639a2fc5261d552e131c8ddfad8ad74d3fcd8dac0b5cdfafb1e06e +size 54304 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-3d-rotation-life-seperate.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-3d-rotation-life-seperate.jpg index 88dba3763b..4e41693021 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-3d-rotation-life-seperate.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-3d-rotation-life-seperate.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:23071f38dabccc3492958c8daea8c5e30303cd0d57ba436cbe66c627e8f63340 -size 173330 +oid sha256:05dde457049ed9276cc12d328d88a8d5a3178a0ef77cb80d84d8b54b88481817 +size 168814 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-3d-rotation.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-3d-rotation.jpg index 581e40b561..86a5668b2b 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-3d-rotation.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-3d-rotation.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:26e7b9cc91b4eecebde7bc664e103c0de374ff9ddcd20107ac15f2e5d64e088b -size 197456 +oid sha256:1a7694f1cb9c84c7b7961644b0c46ce776464052332610710323036f01ae948e +size 165653 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-life-seperate.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-life-seperate.jpg index 06754c710a..29a5d409df 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-life-seperate.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-life-seperate.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:40288944c6145a22c0b9b8925b746568f18c7b59635c5ccb425c737638eacff8 -size 157777 +oid sha256:1fb9fa66aef3f361ab6f7c3e0b74adf12eb500728a8ea784a0013e1f87886c2a +size 133674 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-life.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-life.jpg index 32ec984f8d..67ffe795b0 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-life.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-life.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7ff09f82e4b26cf91c5070575e371aa5a1f1ca921cc9597dd680c13e277bf83b -size 181501 +oid sha256:24e4b97384202cf7c0c05ca63064a38c40aeace3fdf494e9852ff8f06100f3b4 +size 189203 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-world.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-world.jpg index 2efa701fb6..dad85120f5 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-world.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation-world.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:04c5df34da746da36a0a28c4a3a4d464e658835e1374b9cdad24d99629115db0 -size 148015 +oid sha256:0ffd8248dcdae4bdfc04e430b2ad4ba9380bf1a95dd1afbff30bba67aa7ba625 +size 143461 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation.jpg index 1e5952c676..f4d8da466a 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone-scale-rotation.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:9f0e3e3bea6bb4c7e2850ba66856216503124468c6f6a2545526a76c68b63769 -size 233910 +oid sha256:e4d73c785ea2b6a5322f2067dd7c9f92b101f068bda61334f4f0d7486b593095 +size 244846 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone.jpg index c944d6ad7d..291522d4ce 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-cone.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:16c2d3d1ac6bc04fe1d2ffbbb726f04d119f6220a59e41381506a042552f76fe -size 184788 +oid sha256:154344f6c6ef52832319dde824e4035ffcabce4484fbbd616bc66da8956ee300 +size 178327 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-no-shape-world.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-no-shape-world.jpg index 545f9c0def..99c03f99c5 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-no-shape-world.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-no-shape-world.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:22f14f13f5c99abcd826ab81e283b4bcadde09d4bdb82435f44a785b62ce1d08 -size 57705 +oid sha256:b4db419900abc3caef3aa52a9c7388007f65eb1894e87ba8c9e2150025a0a5d8 +size 78327 diff --git a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-no-shape.jpg b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-no-shape.jpg index 28f4927d93..235adea154 100644 --- a/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-no-shape.jpg +++ b/e2e/fixtures/originImage/Particle_particleRenderer-emit-mesh-no-shape.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:36f34e92d138bc0cec7a5dd7a4c21d4830b5ac47bda0383003c0c8868b0bfddb -size 68831 +oid sha256:08d65b43eadae85d6828cc41c957a2e0fcf7c33af4dec0b77ae62fe80ee3f1ea +size 67130 diff --git a/e2e/fixtures/originImage/Primitive_primitive-all.jpg b/e2e/fixtures/originImage/Primitive_primitive-all.jpg index 17247bbfc6..0db7e8b795 100644 --- a/e2e/fixtures/originImage/Primitive_primitive-all.jpg +++ b/e2e/fixtures/originImage/Primitive_primitive-all.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:5a5451a1a54c15f343174a41a6df8d3329c4223661b6e53d422eee7267819fe2 -size 444327 +oid sha256:d7ffaf5ec2debdd21f035db54069812ae4dcb14ccd889a80ee754177b3083b07 +size 444193 diff --git a/e2e/fixtures/originImage/Primitive_primitive-cylinder.jpg b/e2e/fixtures/originImage/Primitive_primitive-cylinder.jpg index a169161330..b234dddcff 100644 --- a/e2e/fixtures/originImage/Primitive_primitive-cylinder.jpg +++ b/e2e/fixtures/originImage/Primitive_primitive-cylinder.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:76b76bda3e2e370c0d5385b916c9b1ce177ee79f5a33ca10d24e08b3b3dcdb14 -size 99097 +oid sha256:b4736d2feef50a0da43e1b73a7fe33ff54c7866fad44907051b1194937435959 +size 99016 diff --git a/e2e/fixtures/originImage/Primitive_primitive-sections.jpg b/e2e/fixtures/originImage/Primitive_primitive-sections.jpg index db940f83ca..b9e53bf708 100644 --- a/e2e/fixtures/originImage/Primitive_primitive-sections.jpg +++ b/e2e/fixtures/originImage/Primitive_primitive-sections.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:93eb69dd3979e5a7aa49ee5f34128d4f72281ff74bbd47b1e880902b5a6397e1 -size 630715 +oid sha256:8f7477bb295eaeb55ae08e7fe22f679a9005ddbae544977d44a79414ff376bb3 +size 639592 diff --git a/e2e/primitive-mesh.md b/e2e/primitive-mesh.md index ade86243e6..d4ccca7fe4 100644 --- a/e2e/primitive-mesh.md +++ b/e2e/primitive-mesh.md @@ -21,6 +21,6 @@ After changing engine package sources, run `pnpm run build` before the tests. To 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. Cylinder and capsule UV changes also update the older primitive and particle baselines that use those meshes. +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/packages/core/src/mesh/PrimitiveMesh.ts b/packages/core/src/mesh/PrimitiveMesh.ts index b4f0f67f0b..c6bb08510f 100644 --- a/packages/core/src/mesh/PrimitiveMesh.ts +++ b/packages/core/src/mesh/PrimitiveMesh.ts @@ -272,7 +272,8 @@ export class PrimitiveMesh { caps === PrimitiveMeshCapMode.Both || caps === PrimitiveMeshCapMode.Top, caps === PrimitiveMeshCapMode.Both || caps === PrimitiveMeshCapMode.Bottom, startAngle, - (angleRange?.y ?? 360) - startAngle + (angleRange?.y ?? 360) - startAngle, + options?.separateMaterialSlots ?? false ], options ); @@ -311,7 +312,8 @@ export class PrimitiveMesh { caps === PrimitiveMeshCapMode.Both || caps === PrimitiveMeshCapMode.Top, caps === PrimitiveMeshCapMode.Both || caps === PrimitiveMeshCapMode.Bottom, startAngle, - (angleRange?.y ?? 360) - startAngle + (angleRange?.y ?? 360) - startAngle, + options?.separateMaterialSlots ?? false ], options ); @@ -849,11 +851,12 @@ export class PrimitiveMesh { includeTopCap: boolean, includeBottomCap: boolean, startAngleDegrees: number, - arcDegrees: number + arcDegrees: number, + separateMaterialSlots: boolean = false ): PrimitiveMeshBuilder { const radial = PrimitiveMesh._getSegmentCount(radialSegments, 3); const vertical = PrimitiveMesh._getSegmentCount(heightSegments); - const startAngle = MathUtil.degreeToRadian(startAngleDegrees); + 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; @@ -887,12 +890,18 @@ export class PrimitiveMesh { } } 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; @@ -902,32 +911,39 @@ export class PrimitiveMesh { } 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 cos = circle[x * 2]; - const sin = circle[x * 2 + 1]; + const offset = (rowStart + x) * 8; + const positionX = data.vertices[offset]; + const positionZ = data.vertices[offset + 2]; data.addVertex( - radius * sin, + positionX, (sign * height) / 2, - radius * cos, + positionZ, 0, sign, 0, - (sin + 1) / 2, - (cos * sign + 1) / 2 + 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; - if (sign > 0) { - data.addTriangle(center, current, next); - } else { - data.addTriangle(center, next, current); - } + 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); } - data.addGroup(start); } } diff --git a/packages/core/src/mesh/PrimitiveMeshOptions.ts b/packages/core/src/mesh/PrimitiveMeshOptions.ts index f373fb2872..d90960368c 100644 --- a/packages/core/src/mesh/PrimitiveMeshOptions.ts +++ b/packages/core/src/mesh/PrimitiveMeshOptions.ts @@ -115,7 +115,7 @@ export interface CylinderMeshOptions extends PrimitiveMeshOptions { */ caps?: PrimitiveMeshCapMode; /** - * The start (`x`) and end (`y`) angles in degrees around Y, measured from +Z towards +X. + * The start (`x`) and end (`y`) angles in degrees around Y, measured from -Z towards -X. * @defaultValue `new Vector2(0, 360)` */ angleRange?: Vector2; @@ -147,7 +147,7 @@ export interface TruncatedConeMeshOptions extends PrimitiveMeshOptions { */ caps?: PrimitiveMeshCapMode; /** - * The start (`x`) and end (`y`) angles in degrees around Y, measured from +Z towards +X. + * The start (`x`) and end (`y`) angles in degrees around Y, measured from -Z towards -X. * @defaultValue `new Vector2(0, 360)` */ angleRange?: Vector2; @@ -179,7 +179,7 @@ export interface ConeMeshOptions extends PrimitiveMeshOptions { */ cap?: boolean; /** - * The start (`x`) and end (`y`) angles in degrees around Y, measured from +Z towards +X. + * The start (`x`) and end (`y`) angles in degrees around Y, measured from -Z towards -X. * @defaultValue `new Vector2(0, 360)` */ angleRange?: Vector2; diff --git a/tests/src/core/mesh/ProceduralMesh.test.ts b/tests/src/core/mesh/ProceduralMesh.test.ts index fcf2a5aa98..129bf6d72e 100644 --- a/tests/src/core/mesh/ProceduralMesh.test.ts +++ b/tests/src/core/mesh/ProceduralMesh.test.ts @@ -363,6 +363,95 @@ describe("procedural mesh geometry", () => { } }); + const cylinderOptions = { keepCPUData: 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, From 3f37ca62e1be99c2899b4732c36f7a58b4c0302b Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sun, 15 Nov 2026 01:54:40 +0800 Subject: [PATCH 20/24] refactor(core): align mesh data retention option naming --- docs/en/graphics/mesh/primitiveMesh.mdx | 6 +- docs/zh/graphics/mesh/primitiveMesh.mdx | 6 +- e2e/case/primitive-materials.ts | 2 +- e2e/case/primitive-topology.ts | 2 +- e2e/primitive-mesh.md | 2 +- packages/core/src/mesh/PrimitiveMesh.ts | 8 +- .../core/src/mesh/PrimitiveMeshOptions.ts | 4 +- .../references/mesh-geometry.md | 4 +- .../fixtures/PrimitiveMeshApi.ts | 38 ++-- .../fixtures/PrimitiveMeshAsset.ts | 2 +- tests/src/core/mesh/BlendShapeManager.test.ts | 2 +- tests/src/core/mesh/PrimitiveMesh.test.ts | 18 +- tests/src/core/mesh/ProceduralMesh.test.ts | 190 +++++++++--------- tests/src/core/physics/ColliderLayer.test.ts | 2 +- .../core/physics/MeshColliderLayer.test.ts | 2 +- tests/src/loader/PrimitiveMeshLoader.test.ts | 8 +- 16 files changed, 151 insertions(+), 145 deletions(-) diff --git a/docs/en/graphics/mesh/primitiveMesh.mdx b/docs/en/graphics/mesh/primitiveMesh.mdx index 4006df81ad..9bb3c3022f 100644 --- a/docs/en/graphics/mesh/primitiveMesh.mdx +++ b/docs/en/graphics/mesh/primitiveMesh.mdx @@ -218,7 +218,7 @@ For tubes and path extrusions, `closedPath` defaults to `false`. Set it to `true Mesh settings and subdivision counts belong to the optional settings object: ```ts -const editable = PrimitiveMesh.createSphere(engine, 1, { keepCPUData: true, subdivisionLevel: 3 }); +const editable = PrimitiveMesh.createSphere(engine, 1, { keepMeshData: true, subdivisionLevel: 3 }); const sixMaterials = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { separateMaterialSlots: true, widthSegments: 1, @@ -227,7 +227,7 @@ const sixMaterials = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { }); ``` -`keepCPUData` defaults to false. Set it to true to retain readable CPU vertex attributes. +`keepMeshData` defaults to false. Set it to true to retain vertex attributes and indices for reading or editing after upload. `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: @@ -255,7 +255,7 @@ import type { PrimitiveMeshAsset } from "@galacean/engine"; const asset = { type: "sphere", sphereRadius: 1, - sphereOptions: { subdivisionLevel: 3, keepCPUData: true } + sphereOptions: { subdivisionLevel: 3, keepMeshData: true } } satisfies PrimitiveMeshAsset; ``` diff --git a/docs/zh/graphics/mesh/primitiveMesh.mdx b/docs/zh/graphics/mesh/primitiveMesh.mdx index 915d699e01..a1094e3d21 100644 --- a/docs/zh/graphics/mesh/primitiveMesh.mdx +++ b/docs/zh/graphics/mesh/primitiveMesh.mdx @@ -224,7 +224,7 @@ const closedPath = PrimitiveMesh.createExtrudedPolygon(engine, outline, loop, { 网格设置与分段设置放在同一个可选配置对象中: ```ts -const editable = PrimitiveMesh.createSphere(engine, 1, { keepCPUData: true, subdivisionLevel: 3 }); +const editable = PrimitiveMesh.createSphere(engine, 1, { keepMeshData: true, subdivisionLevel: 3 }); const sixMaterials = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { separateMaterialSlots: true, widthSegments: 1, @@ -233,7 +233,7 @@ const sixMaterials = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { }); ``` -`keepCPUData` 默认关闭,设为 `true` 时保留可读的 CPU 顶点属性。 +`keepMeshData` 默认关闭,设为 `true` 时保留顶点属性和索引,供上传后读取或修改。 `separateMaterialSlots` 适用于长方体、圆柱、圆台、圆锥、多边形、挤出和圆角长方体。默认关闭,生成一个 SubMesh;开启后,生成的 SubMesh 按以下顺序对应材质槽: @@ -261,7 +261,7 @@ import type { PrimitiveMeshAsset } from "@galacean/engine"; const asset = { type: "sphere", sphereRadius: 1, - sphereOptions: { subdivisionLevel: 3, keepCPUData: true } + sphereOptions: { subdivisionLevel: 3, keepMeshData: true } } satisfies PrimitiveMeshAsset; ``` diff --git a/e2e/case/primitive-materials.ts b/e2e/case/primitive-materials.ts index 7411b6a587..229616d998 100644 --- a/e2e/case/primitive-materials.ts +++ b/e2e/case/primitive-materials.ts @@ -27,7 +27,7 @@ class PrimitiveMaterials { 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, keepCPUData: true }); + 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."); } diff --git a/e2e/case/primitive-topology.ts b/e2e/case/primitive-topology.ts index 9e21670480..9b8e76118a 100644 --- a/e2e/case/primitive-topology.ts +++ b/e2e/case/primitive-topology.ts @@ -8,7 +8,7 @@ class PrimitiveTopology { static async create(): Promise { const gallery = await PrimitiveMeshGallery.create(); const { engine } = gallery; - const keep = { keepCPUData: true }; + const keep = { keepMeshData: true }; const examples: PrimitiveMeshExample[] = [ { label: "Sphere / level 1", diff --git a/e2e/primitive-mesh.md b/e2e/primitive-mesh.md index d4ccca7fe4..47de85af51 100644 --- a/e2e/primitive-mesh.md +++ b/e2e/primitive-mesh.md @@ -9,7 +9,7 @@ The suite contains six galleries with 90 examples. Each screenshot fixes the cam | `primitive-sections` | 15 | Circle/ring sectors, both torus ranges, cylinder cap combinations, cone caps and partial lathes | | `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, `keepCPUData`, JSON asset loading and corner-radius clamping | +| `primitive-materials` | 12 | Material-slot order, multiple shapes, `keepMeshData`, JSON asset loading and corner-radius clamping | Run all six galleries: diff --git a/packages/core/src/mesh/PrimitiveMesh.ts b/packages/core/src/mesh/PrimitiveMesh.ts index c6bb08510f..4cbcee704d 100644 --- a/packages/core/src/mesh/PrimitiveMesh.ts +++ b/packages/core/src/mesh/PrimitiveMesh.ts @@ -1993,9 +1993,9 @@ export class PrimitiveMesh { engine: Engine, generate: (...args: T) => PrimitiveMeshBuilder, args: [...T], - options?: { keepCPUData?: boolean; separateMaterialSlots?: boolean } + options?: { keepMeshData?: boolean; separateMaterialSlots?: boolean } ): ModelMesh { - const keepCPUData = options?.keepCPUData ?? false; + const keepMeshData = options?.keepMeshData ?? false; for (let i = 0; i < args.length; i++) { args[i] = PrimitiveMesh._copy(args[i]); } @@ -2017,8 +2017,8 @@ export class PrimitiveMesh { mesh.setIndices(indices); mesh.calculateTangents(); PrimitiveMesh._setBounds(mesh, data); - mesh.uploadData(!keepCPUData); - if (!keepCPUData) { + mesh.uploadData(!keepMeshData); + if (!keepMeshData) { vertexBuffer.markAsUnreadable(); } if (options?.separateMaterialSlots && data.groups.length) { diff --git a/packages/core/src/mesh/PrimitiveMeshOptions.ts b/packages/core/src/mesh/PrimitiveMeshOptions.ts index d90960368c..1e191ad764 100644 --- a/packages/core/src/mesh/PrimitiveMeshOptions.ts +++ b/packages/core/src/mesh/PrimitiveMeshOptions.ts @@ -6,10 +6,10 @@ import type { PrimitiveMeshCapMode } from "./enums/PrimitiveMeshCapMode"; */ export interface PrimitiveMeshOptions { /** - * Whether to retain readable CPU copies of vertex attributes and indices after upload. + * Whether to retain readable mesh data after uploading it to the GPU. * @defaultValue `false` */ - keepCPUData?: boolean; + keepMeshData?: boolean; } /** diff --git a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md index 8c18d324ff..ffeb53c8e0 100644 --- a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md +++ b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md @@ -67,13 +67,13 @@ For straight extrusion, `contourOffset` shifts the side-wall outline and default For tubes and path extrusions, `closedPath` defaults to `false`. When enabled, the path ends join with matching cross-sections, and the closing point need not be repeated. Closed extrusions use at least three path segments and have no end caps. Open extrusions have both end caps; tubes have no end caps in either mode. -Mesh settings share the same options object. `keepCPUData` retains readable CPU attributes and defaults to false. `separateMaterialSlots` defaults to false and is only available for cuboids, cylinders, truncated cones, cones, polygons, extrusions and rounded cuboids. With it enabled, cuboid slots follow +Y, -Y, -X, +X, +Z, -Z; cylinders use side, top, bottom; cones use side, bottom. Disabled or zero-radius caps do not reserve slots. Polygon slots follow shape order, with holes sharing the outer contour's slot. Each open extrusion shape contributes two consecutive slots: both caps, then all walls and bevels. Closed path extrusions contribute one wall slot per shape. Rebuilding a mesh with different parts requires matching the material array to its new slot order. Input values are captured at creation for deterministic device restoration. +Mesh settings share the same options object. `keepMeshData` retains vertex attributes and indices for reading or editing after upload and defaults to false. `separateMaterialSlots` defaults to false and is only available for cuboids, cylinders, truncated cones, cones, polygons, extrusions and rounded cuboids. With it enabled, cuboid slots follow +Y, -Y, -X, +X, +Z, -Z; cylinders use side, top, bottom; cones use side, bottom. Disabled or zero-radius caps do not reserve slots. Polygon slots follow shape order, with holes sharing the outer contour's slot. Each open extrusion shape contributes two consecutive slots: both caps, then all walls and bevels. Closed path extrusions contribute one wall slot per shape. Rebuilding a mesh with different parts requires matching the material array to its new slot order. Input values are captured at creation for deterministic device restoration. ## Serializable primitive assets `PrimitiveMeshAsset` is exported from `@galacean/engine` and `@galacean/engine-loader` and covers every `PrimitiveMesh.createX` method. Each asset `type` uses the matching lower-camel name: `sphere`, `cuboid`, `plane`, `cylinder`, `truncatedCone`, `cone`, `capsule`, `torus`, `circle`, `ring`, `tetrahedron`, `octahedron`, `icosahedron`, `dodecahedron`, `lathe`, `tube`, `polygon`, `extrudedPolygon`, `torusKnot`, `roundedCuboid`. -JSON keeps the type prefix for required geometry inputs and the optional settings object: `{ type: "sphere", sphereRadius: 1, sphereOptions: { subdivisionLevel: 3, keepCPUData: true } }`. Each `Options` uses the factory's named configuration fields and omitted defaults. Angular ranges store `Vector2` components as `{ x, y }`, for example `{ type: "circle", circleRadius: 1, circleOptions: { angleRange: { x: 30, y: 180 } } }`. `sphere` uses the subdivided-cube algorithm; `sphereOptions.subdivisionLevel` sets its subdivision level. `cylinderRadius` controls both end radii; unequal radii use `truncatedConeTopRadius` and `truncatedConeBottomRadius`. +JSON keeps the type prefix for required geometry inputs and the optional settings object: `{ type: "sphere", sphereRadius: 1, sphereOptions: { subdivisionLevel: 3, keepMeshData: true } }`. Each `Options` uses the factory's named configuration fields and omitted defaults. Angular ranges store `Vector2` components as `{ x, y }`, for example `{ type: "circle", circleRadius: 1, circleOptions: { angleRange: { x: 30, y: 180 } } }`. `sphere` uses the subdivided-cube algorithm; `sphereOptions.subdivisionLevel` sets its subdivision level. `cylinderRadius` controls both end radii; unequal radii use `truncatedConeTopRadius` and `truncatedConeBottomRadius`. TypeScript assets use `PrimitiveMeshCapMode` for `caps`; JSON stores its string values `"both"`, `"top"`, `"bottom"`, `"none"`. diff --git a/tests/package-consumer/fixtures/PrimitiveMeshApi.ts b/tests/package-consumer/fixtures/PrimitiveMeshApi.ts index e27d5f755b..edb3cf9b02 100644 --- a/tests/package-consumer/fixtures/PrimitiveMeshApi.ts +++ b/tests/package-consumer/fixtures/PrimitiveMeshApi.ts @@ -36,28 +36,28 @@ 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 = { keepCPUData: true } satisfies PrimitiveMeshOptions; +const commonOptions = { keepMeshData: true } satisfies PrimitiveMeshOptions; const sphereOptions = { subdivisionLevel: 4, horizontalAngleRange: new Vector2(350, 370), verticalAngleRange: new Vector2(30, 150), - keepCPUData: true + keepMeshData: true } satisfies SphereMeshOptions; const cuboidOptions = { widthSegments: 2, heightSegments: 3, depthSegments: 4, separateMaterialSlots: true, - keepCPUData: true + keepMeshData: true } satisfies CuboidMeshOptions; -const planeOptions = { widthSegments: 4, depthSegments: 2, keepCPUData: true } satisfies PlaneMeshOptions; +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, - keepCPUData: true + keepMeshData: true } satisfies CylinderMeshOptions; const truncatedConeOptions = { radialSegments: 32, @@ -65,7 +65,7 @@ const truncatedConeOptions = { caps: PrimitiveMeshCapMode.None, angleRange: new Vector2(0, 270), separateMaterialSlots: true, - keepCPUData: true + keepMeshData: true } satisfies TruncatedConeMeshOptions; const coneOptions = { radialSegments: 32, @@ -73,37 +73,37 @@ const coneOptions = { cap: false, angleRange: new Vector2(0, 270), separateMaterialSlots: true, - keepCPUData: true + keepMeshData: true } satisfies ConeMeshOptions; const capsuleOptions = { radialSegments: 12, capSegments: 6, heightSegments: 3, - keepCPUData: true + keepMeshData: true } satisfies CapsuleMeshOptions; const torusOptions = { ringSegments: 64, radialSegments: 16, ringAngleRange: new Vector2(0, 270), tubeAngleRange: new Vector2(0, 180), - keepCPUData: true + keepMeshData: true } satisfies TorusMeshOptions; -const circleOptions = { segments: 32, angleRange: new Vector2(0, 180), keepCPUData: true } satisfies CircleMeshOptions; +const circleOptions = { segments: 32, angleRange: new Vector2(0, 180), keepMeshData: true } satisfies CircleMeshOptions; const ringOptions = { ringSegments: 32, widthSegments: 4, angleRange: new Vector2(0, 270), - keepCPUData: true + keepMeshData: true } satisfies RingMeshOptions; -const regularPolyhedronOptions = { edgeSegments: 2, keepCPUData: true } satisfies RegularPolyhedronMeshOptions; -const latheOptions = { segments: 32, angleRange: new Vector2(0, 270), keepCPUData: true } satisfies LatheMeshOptions; +const regularPolyhedronOptions = { edgeSegments: 2, keepMeshData: true } satisfies RegularPolyhedronMeshOptions; +const latheOptions = { segments: 32, angleRange: new Vector2(0, 270), keepMeshData: true } satisfies LatheMeshOptions; const tubeOptions = { pathSegments: 64, radialSegments: 8, closedPath: true, - keepCPUData: true + keepMeshData: true } satisfies TubeMeshOptions; -const polygonOptions = { separateMaterialSlots: true, keepCPUData: true } satisfies PolygonMeshOptions; +const polygonOptions = { separateMaterialSlots: true, keepMeshData: true } satisfies PolygonMeshOptions; const linearExtrudedPolygonOptions = { depthSegments: 4, bevelWidth: 0.1, @@ -111,19 +111,19 @@ const linearExtrudedPolygonOptions = { contourOffset: 0.1, bevelSegments: 3, separateMaterialSlots: true, - keepCPUData: true + keepMeshData: true } satisfies LinearExtrudedPolygonMeshOptions; -const torusKnotOptions = { pathSegments: 64, radialSegments: 12, keepCPUData: true } satisfies TorusKnotMeshOptions; +const torusKnotOptions = { pathSegments: 64, radialSegments: 12, keepMeshData: true } satisfies TorusKnotMeshOptions; const roundedCuboidOptions = { roundingSegments: 4, separateMaterialSlots: true, - keepCPUData: true + keepMeshData: true } satisfies RoundedCuboidMeshOptions; const pathExtrudedPolygonOptions = { pathSegments: 32, closedPath: true, separateMaterialSlots: true, - keepCPUData: true + keepMeshData: true } satisfies PathExtrudedPolygonMeshOptions; const extrudedPolygonOptions: LinearExtrudedPolygonMeshOptions | PathExtrudedPolygonMeshOptions = pathExtrudedPolygonOptions; diff --git a/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts index f1e060b4ef..1db1aabdc8 100644 --- a/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts +++ b/tests/package-consumer/fixtures/PrimitiveMeshAsset.ts @@ -12,7 +12,7 @@ const everyAssetHasAFactory: Exclude e const sphere: PrimitiveMeshAsset = { type: "sphere", sphereRadius: 1, - sphereOptions: { verticalAngleRange: { x: 0, y: 90 }, keepCPUData: true, subdivisionLevel: 3 } + sphereOptions: { verticalAngleRange: { x: 0, y: 90 }, keepMeshData: true, subdivisionLevel: 3 } }; const exportedFromEngine: EnginePrimitiveMeshAsset = sphere; const sphereSection: PrimitiveMeshAsset = { diff --git a/tests/src/core/mesh/BlendShapeManager.test.ts b/tests/src/core/mesh/BlendShapeManager.test.ts index eb7ed0a589..387696b963 100644 --- a/tests/src/core/mesh/BlendShapeManager.test.ts +++ b/tests/src/core/mesh/BlendShapeManager.test.ts @@ -218,7 +218,7 @@ describe("BlendShapeManager", () => { ); blendShapeWeights0_7.addFrame(frame); const modelMeshWebgl2 = PrimitiveMesh.createCuboid(engineWebGL2, 1, 1, 1, { - keepCPUData: true, + keepMeshData: true, widthSegments: 1, heightSegments: 1, depthSegments: 1 diff --git a/tests/src/core/mesh/PrimitiveMesh.test.ts b/tests/src/core/mesh/PrimitiveMesh.test.ts index 53049eb839..5dbb1be8a1 100644 --- a/tests/src/core/mesh/PrimitiveMesh.test.ts +++ b/tests/src/core/mesh/PrimitiveMesh.test.ts @@ -21,7 +21,7 @@ describe("PrimitiveMesh", () => { it("createSphere", () => { const radius = 2.333; const subdivisionLevel = 3.2; - const sphereMesh = PrimitiveMesh.createSphere(engine, radius, { keepCPUData: true, subdivisionLevel }); + const sphereMesh = PrimitiveMesh.createSphere(engine, radius, { keepMeshData: true, subdivisionLevel }); expect(sphereMesh.vertexCount).equal(417); expect(sphereMesh.vertexElements.length).equal(4); @@ -37,7 +37,7 @@ describe("PrimitiveMesh", () => { const height = 3.2; const depth = 4.5; const cuboidMesh = PrimitiveMesh.createCuboid(engine, width, height, depth, { - keepCPUData: true, + keepMeshData: true, widthSegments: 1, heightSegments: 1, depthSegments: 1 @@ -61,7 +61,7 @@ describe("PrimitiveMesh", () => { const floorRadialSegments = Math.floor(radialSegments); const floorHeightSegments = Math.floor(heightSegments); const truncatedConeMesh = PrimitiveMesh.createTruncatedCone(engine, radiusTop, radiusBottom, height, { - keepCPUData: true, + keepMeshData: true, radialSegments, heightSegments }); @@ -89,7 +89,7 @@ describe("PrimitiveMesh", () => { const floorRingSegments = Math.floor(ringSegments); const arc = 180; const torusMesh = PrimitiveMesh.createTorus(engine, radius, tubeRadius, { - keepCPUData: true, + keepMeshData: true, ringAngleRange: new Vector2(0, 0 + arc), ringSegments, radialSegments @@ -113,7 +113,7 @@ describe("PrimitiveMesh", () => { const floorHSegments = Math.floor(hSegments); const floorVSegments = Math.floor(vSegments); const planeMesh = PrimitiveMesh.createPlane(engine, width, height, { - keepCPUData: true, + keepMeshData: true, widthSegments: hSegments, depthSegments: vSegments }); @@ -135,7 +135,7 @@ describe("PrimitiveMesh", () => { const floorRadialSegments = Math.floor(radialSegments); const floorHeightSegments = Math.floor(heightSegments); const coneMesh = PrimitiveMesh.createCone(engine, radius, height, { - keepCPUData: true, + keepMeshData: true, radialSegments, heightSegments }); @@ -156,7 +156,7 @@ describe("PrimitiveMesh", () => { const floorRadialSegments = Math.floor(radialSegments); const floorHeightSegments = Math.floor(heightSegments); const capsuleMesh = PrimitiveMesh.createCapsule(engine, radius, height, { - keepCPUData: true, + keepMeshData: true, radialSegments, capSegments: radialSegments, heightSegments @@ -180,7 +180,7 @@ describe("PrimitiveMesh", () => { if (engine["_hardwareRenderer"].canIUse(GLCapabilityType.elementIndexUint)) { const mesh = PrimitiveMesh.createPlane(engine, radius * 2, radius * 2, { - keepCPUData: true, + keepMeshData: true, widthSegments: segments, depthSegments: segments }); @@ -193,7 +193,7 @@ describe("PrimitiveMesh", () => { } else { expect(() => PrimitiveMesh.createPlane(engine, radius * 2, radius * 2, { - keepCPUData: true, + keepMeshData: true, widthSegments: segments, depthSegments: segments }) diff --git a/tests/src/core/mesh/ProceduralMesh.test.ts b/tests/src/core/mesh/ProceduralMesh.test.ts index 129bf6d72e..a9b9b243f3 100644 --- a/tests/src/core/mesh/ProceduralMesh.test.ts +++ b/tests/src/core/mesh/ProceduralMesh.test.ts @@ -30,36 +30,36 @@ const polygon = { 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, { keepCPUData: true, subdivisionLevel: 2 })], + ["sphere", () => PrimitiveMesh.createSphere(engine, 2, { keepMeshData: true, subdivisionLevel: 2 })], [ "cuboid", () => PrimitiveMesh.createCuboid(engine, 1, 1, 1, { - keepCPUData: true, + keepMeshData: true, widthSegments: 3, heightSegments: 2, depthSegments: 2 }) ], - ["plane", () => PrimitiveMesh.createPlane(engine, 1, 1, { keepCPUData: true, widthSegments: 3, depthSegments: 2 })], + ["plane", () => PrimitiveMesh.createPlane(engine, 1, 1, { keepMeshData: true, widthSegments: 3, depthSegments: 2 })], [ "cylinder", () => PrimitiveMesh.createTruncatedCone(engine, 0.25, 1, 2, { - keepCPUData: true, + keepMeshData: true, radialSegments: 12, heightSegments: 1 }) ], [ "cone", - () => PrimitiveMesh.createCone(engine, 0.5, 2, { keepCPUData: true, radialSegments: 12, heightSegments: 1 }) + () => PrimitiveMesh.createCone(engine, 0.5, 2, { keepMeshData: true, radialSegments: 12, heightSegments: 1 }) ], [ "capsule", () => PrimitiveMesh.createCapsule(engine, 0.5, 2, { - keepCPUData: true, + keepMeshData: true, radialSegments: 12, capSegments: 4, heightSegments: 1 @@ -69,7 +69,7 @@ const creators: [string, () => ModelMesh][] = [ "torus", () => PrimitiveMesh.createTorus(engine, 0.5, 0.1, { - keepCPUData: true, + keepMeshData: true, ringAngleRange: new Vector2(0, 360), ringSegments: 16, radialSegments: 8 @@ -77,45 +77,45 @@ const creators: [string, () => ModelMesh][] = [ ], [ "circle", - () => PrimitiveMesh.createCircle(engine, 0.5, { keepCPUData: true, angleRange: new Vector2(0, 180), segments: 12 }) + () => PrimitiveMesh.createCircle(engine, 0.5, { keepMeshData: true, angleRange: new Vector2(0, 180), segments: 12 }) ], [ "ring", () => PrimitiveMesh.createRing(engine, 0.5, 0.25, { - keepCPUData: true, + keepMeshData: true, angleRange: new Vector2(0, 360), ringSegments: 12, widthSegments: 2 }) ], - ["tetrahedron", () => PrimitiveMesh.createTetrahedron(engine, 0.5, { keepCPUData: true, edgeSegments: 1 })], - ["octahedron", () => PrimitiveMesh.createOctahedron(engine, 0.5, { keepCPUData: true, edgeSegments: 1 })], - ["icosahedron", () => PrimitiveMesh.createIcosahedron(engine, 0.5, { keepCPUData: true, edgeSegments: 2 })], - ["dodecahedron", () => PrimitiveMesh.createDodecahedron(engine, 0.5, { keepCPUData: true, edgeSegments: 1 })], + ["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 })], [ "lathe", () => PrimitiveMesh.createLathe(engine, [new Vector2(0, -1), new Vector2(1, 0), new Vector2(0, 1)], { - keepCPUData: true, + keepMeshData: true, angleRange: new Vector2(0, 360), segments: 12 }) ], [ "tube", - () => PrimitiveMesh.createTube(engine, path, 0.5, { keepCPUData: true, pathSegments: 12, radialSegments: 8 }) + () => PrimitiveMesh.createTube(engine, path, 0.5, { keepMeshData: true, pathSegments: 12, radialSegments: 8 }) ], - ["polygon", () => PrimitiveMesh.createPolygon(engine, polygon, { keepCPUData: true })], + ["polygon", () => PrimitiveMesh.createPolygon(engine, polygon, { keepMeshData: true })], [ "extrudedPolygon", - () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { keepCPUData: true, depthSegments: 1 }) + () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { keepMeshData: true, depthSegments: 1 }) ], [ "extrudedPolygon", () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, 1, { - keepCPUData: true, + keepMeshData: true, bevelWidth: 0.1, contourOffset: 0.2, depthSegments: 1 @@ -123,7 +123,7 @@ const creators: [string, () => ModelMesh][] = [ ], [ "extrudedPolygon", - () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, { keepCPUData: true, pathSegments: 5 }) + () => PrimitiveMesh.createExtrudedPolygon(engine, polygon, path, { keepMeshData: true, pathSegments: 5 }) ], [ "extrudedPolygon", @@ -141,31 +141,31 @@ const creators: [string, () => ModelMesh][] = [ ] }, 1, - { keepCPUData: true, bevelWidth: 0.05, bevelDepth: 0.1, contourOffset: -0.05, depthSegments: 1 } + { keepMeshData: true, bevelWidth: 0.05, bevelDepth: 0.1, contourOffset: -0.05, depthSegments: 1 } ) ], [ "torusKnot", () => - PrimitiveMesh.createTorusKnot(engine, 0.5, 0.1, 2, 3, { keepCPUData: true, pathSegments: 32, radialSegments: 8 }) + 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, { - keepCPUData: true, + keepMeshData: true, pathSegments: 32, radialSegments: 8 }) ], [ "roundedCuboid", - () => PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.15, { keepCPUData: true, roundingSegments: 3 }) + () => PrimitiveMesh.createRoundedCuboid(engine, 1, 1, 1, 0.15, { keepMeshData: true, roundingSegments: 3 }) ] ]; describe("primitive mesh defaults", () => { - const options = { keepCPUData: true }; + const options = { keepMeshData: true }; const profile = [new Vector2(0, -1), new Vector2(1, 0), new Vector2(0, 1)]; const cases: [string, () => ModelMesh, () => ModelMesh][] = [ [ @@ -346,7 +346,7 @@ describe("procedural mesh geometry", () => { const frustum = PrimitiveMesh.createTruncatedCone(engine, 0.5, 1.5, 4); const topOnly = PrimitiveMesh.createCylinder(engine, 1, 3, { caps: PrimitiveMeshCapMode.Top, - keepCPUData: true, + keepMeshData: true, radialSegments: 8, heightSegments: 1 }); @@ -363,7 +363,7 @@ describe("procedural mesh geometry", () => { } }); - const cylinderOptions = { keepCPUData: true, radialSegments: 4, heightSegments: 2 }; + const cylinderOptions = { keepMeshData: true, radialSegments: 4, heightSegments: 2 }; it.each([ { name: "cylinder", topRadius: 2, create: () => PrimitiveMesh.createCylinder(engine, 2, 3, cylinderOptions) }, { @@ -456,10 +456,10 @@ describe("procedural mesh geometry", () => { const fromContours = PrimitiveMesh.createPolygon( engine, { points: polygon.points, holes: polygon.holes }, - { keepCPUData: true } + { keepMeshData: true } ); - const fromShape = PrimitiveMesh.createPolygon(engine, polygon, { keepCPUData: true }); - const withoutHoles = PrimitiveMesh.createPolygon(engine, polygon.points, { keepCPUData: 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); @@ -472,7 +472,7 @@ describe("procedural mesh geometry", () => { it("honors offset angular ranges for torus sections", () => { const mesh = PrimitiveMesh.createTorus(engine, 1, 0.25, { - keepCPUData: true, + keepMeshData: true, ringAngleRange: new Vector2(90, 180), ringSegments: 8, radialSegments: 6 @@ -498,7 +498,7 @@ describe("procedural mesh geometry", () => { ({ axisTurns, crossSectionTurns, expected }) => { const radialSegments = 8; const mesh = PrimitiveMesh.createTorusKnot(engine, 2, 0.2, axisTurns, crossSectionTurns, { - keepCPUData: true, + keepMeshData: true, pathSegments: 48, radialSegments }); @@ -530,7 +530,7 @@ describe("procedural mesh geometry", () => { "centers capsule pole UVs with $radialSegments radial segments", ({ radialSegments, capSegments, heightSegments }) => { const mesh = PrimitiveMesh.createCapsule(engine, 1, 2, { - keepCPUData: true, + keepMeshData: true, radialSegments, capSegments, heightSegments @@ -584,7 +584,7 @@ describe("procedural mesh geometry", () => { } ])("preserves $segments segment(s) in a partial lathe", ({ segments, crossSection }) => { const mesh = PrimitiveMesh.createLathe(engine, [new Vector2(1, -1), new Vector2(1, 1)], { - keepCPUData: true, + keepMeshData: true, angleRange: new Vector2(0, 90), segments }); @@ -616,7 +616,7 @@ describe("procedural mesh geometry", () => { const sizes = { x: 2, y: 3, z: 4 }; const radius = 0.25; const mesh = PrimitiveMesh.createRoundedCuboid(engine, sizes.x, sizes.y, sizes.z, radius, { - keepCPUData: true, + keepMeshData: true, separateMaterialSlots: true, roundingSegments: segments }); @@ -661,7 +661,7 @@ describe("procedural mesh geometry", () => { }); it("handles rounded cuboid radius and segment limits without changing the cuboid fallback", () => { - const options = { keepCPUData: true, separateMaterialSlots: true }; + const options = { keepMeshData: true, separateMaterialSlots: true }; const meshes = [ PrimitiveMesh.createCuboid(engine, 2, 3, 4, { ...options, @@ -698,7 +698,7 @@ describe("procedural mesh geometry", () => { ])("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, { - keepCPUData: true, + keepMeshData: true, roundingSegments: 4 }); try { @@ -727,13 +727,13 @@ describe("procedural mesh geometry", () => { } }); - it.each([false, true])("controls all generated vertex data through keepCPUData=%s", (keepCPUData) => { - const mesh = PrimitiveMesh.createSphere(engine, 0.5, { keepCPUData, subdivisionLevel: 1 }); + 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(keepCPUData); + expect(binding!.buffer.readable).toBe(keepMeshData); } - if (keepCPUData) { + if (keepMeshData) { expect(mesh.getPositions()).toHaveLength(mesh.vertexCount); expect(mesh.getNormals()).toHaveLength(mesh.vertexCount); expect(mesh.getTangents()).toHaveLength(mesh.vertexCount); @@ -792,7 +792,7 @@ describe("procedural mesh geometry", () => { }); it("keeps sphere tangents perpendicular at non-unit radii", () => { - const mesh = PrimitiveMesh.createSphere(engine, 2, { keepCPUData: true, subdivisionLevel: 3 }); + const mesh = PrimitiveMesh.createSphere(engine, 2, { keepMeshData: true, subdivisionLevel: 3 }); try { expect(mesh.vertexCount).toBe(417); expect(mesh.getIndices()!.length / 3).toBe(768); @@ -810,7 +810,7 @@ describe("procedural mesh geometry", () => { it("supports a northern hemisphere", () => { const mesh = PrimitiveMesh.createSphere(engine, 0.5, { - keepCPUData: true, + keepMeshData: true, verticalAngleRange: new Vector2(0, 90), subdivisionLevel: 2 }); @@ -831,7 +831,7 @@ describe("procedural mesh geometry", () => { ])("clips a sphere to $horizontal and $vertical without cracks", ({ horizontal, vertical }) => { const radius = 2; const mesh = PrimitiveMesh.createSphere(engine, radius, { - keepCPUData: true, + keepMeshData: true, horizontalAngleRange: new Vector2(horizontal[0], horizontal[1]), verticalAngleRange: new Vector2(vertical[0], vertical[1]), subdivisionLevel: 3 @@ -904,9 +904,9 @@ describe("procedural mesh geometry", () => { }); it("rotates complete spheres without changing topology", () => { - const original = PrimitiveMesh.createSphere(engine, 1, { keepCPUData: true, subdivisionLevel: 2 }); + const original = PrimitiveMesh.createSphere(engine, 1, { keepMeshData: true, subdivisionLevel: 2 }); const rotated = PrimitiveMesh.createSphere(engine, 1, { - keepCPUData: true, + keepMeshData: true, horizontalAngleRange: new Vector2(90, 450), subdivisionLevel: 2 }); @@ -948,7 +948,7 @@ describe("procedural mesh geometry", () => { it("omits cylinder caps and makes material groups opt-in", () => { const open = PrimitiveMesh.createCylinder(engine, 0.5, 2, { - keepCPUData: true, + keepMeshData: true, caps: PrimitiveMeshCapMode.None, radialSegments: 8, heightSegments: 1 @@ -978,7 +978,7 @@ describe("procedural mesh geometry", () => { it("orders cuboid material slots by face direction", () => { const mesh = PrimitiveMesh.createCuboid(engine, 1, 2, 3, { - keepCPUData: true, + keepMeshData: true, separateMaterialSlots: true, widthSegments: 1, heightSegments: 1, @@ -1005,7 +1005,7 @@ describe("procedural mesh geometry", () => { name: "cylinder with both caps", create: () => PrimitiveMesh.createCylinder(engine, 1, 2, { - keepCPUData: true, + keepMeshData: true, separateMaterialSlots: true, radialSegments: 8, heightSegments: 1 @@ -1016,7 +1016,7 @@ describe("procedural mesh geometry", () => { name: "cylinder with only its top cap", create: () => PrimitiveMesh.createCylinder(engine, 1, 2, { - keepCPUData: true, + keepMeshData: true, separateMaterialSlots: true, caps: PrimitiveMeshCapMode.Top, radialSegments: 8, @@ -1028,7 +1028,7 @@ describe("procedural mesh geometry", () => { name: "cylinder with only its bottom cap", create: () => PrimitiveMesh.createCylinder(engine, 1, 2, { - keepCPUData: true, + keepMeshData: true, separateMaterialSlots: true, caps: PrimitiveMeshCapMode.Bottom, radialSegments: 8, @@ -1040,7 +1040,7 @@ describe("procedural mesh geometry", () => { name: "cylinder without caps", create: () => PrimitiveMesh.createCylinder(engine, 1, 2, { - keepCPUData: true, + keepMeshData: true, separateMaterialSlots: true, caps: PrimitiveMeshCapMode.None, radialSegments: 8, @@ -1052,7 +1052,7 @@ describe("procedural mesh geometry", () => { name: "truncated cone with a zero top radius", create: () => PrimitiveMesh.createTruncatedCone(engine, 0, 1, 2, { - keepCPUData: true, + keepMeshData: true, separateMaterialSlots: true, radialSegments: 8, heightSegments: 1 @@ -1063,7 +1063,7 @@ describe("procedural mesh geometry", () => { name: "truncated cone with a zero bottom radius", create: () => PrimitiveMesh.createTruncatedCone(engine, 1, 0, 2, { - keepCPUData: true, + keepMeshData: true, separateMaterialSlots: true, radialSegments: 8, heightSegments: 1 @@ -1074,7 +1074,7 @@ describe("procedural mesh geometry", () => { name: "cone with its bottom cap", create: () => PrimitiveMesh.createCone(engine, 1, 2, { - keepCPUData: true, + keepMeshData: true, separateMaterialSlots: true, radialSegments: 8, heightSegments: 1 @@ -1085,7 +1085,7 @@ describe("procedural mesh geometry", () => { name: "cone without its bottom cap", create: () => PrimitiveMesh.createCone(engine, 1, 2, { - keepCPUData: true, + keepMeshData: true, separateMaterialSlots: true, cap: false, radialSegments: 8, @@ -1111,7 +1111,7 @@ describe("procedural mesh geometry", () => { 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, { keepCPUData: true, separateMaterialSlots: true }); + const mesh = PrimitiveMesh.createPolygon(engine, shapes, { keepMeshData: true, separateMaterialSlots: true }); try { const indices = mesh.getIndices()!; const positions = mesh.getPositions()!; @@ -1128,7 +1128,7 @@ describe("procedural mesh geometry", () => { 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, { - keepCPUData: true, + keepMeshData: true, separateMaterialSlots: true, depthSegments: 1 }); @@ -1149,7 +1149,13 @@ describe("procedural mesh geometry", () => { }); it.each([0.2, -0.2])("offsets extrusion walls and bevels by %s and restores their geometry", (contourOffset) => { - const options = { keepCPUData: true, separateMaterialSlots: true, bevelWidth: 0.1, bevelDepth: 0.2, 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; @@ -1189,7 +1195,7 @@ describe("procedural mesh geometry", () => { it.each([0.2, -0.2])("offsets extrusion contours by %s without adding bevels", (contourOffset) => { const mesh = PrimitiveMesh.createExtrudedPolygon(engine, polygon, 2, { - keepCPUData: true, + keepMeshData: true, contourOffset, depthSegments: 1 }); @@ -1215,7 +1221,7 @@ describe("procedural mesh geometry", () => { }); it("triangulates holes without filling their interiors", () => { - const mesh = PrimitiveMesh.createPolygon(engine, polygon, { keepCPUData: true }); + const mesh = PrimitiveMesh.createPolygon(engine, polygon, { keepMeshData: true }); try { const positions = mesh.getPositions()!; const indices = mesh.getIndices()!; @@ -1296,7 +1302,7 @@ describe("procedural mesh geometry", () => { points: reversed ? points.slice().reverse() : points, holes: holes.map((hole) => (reversed ? hole : hole.slice().reverse())) }; - const mesh = PrimitiveMesh.createPolygon(engine, shape, { keepCPUData: true }); + const mesh = PrimitiveMesh.createPolygon(engine, shape, { keepMeshData: true }); try { const positions = mesh.getPositions()!; const indices = mesh.getIndices()!; @@ -1335,7 +1341,7 @@ describe("procedural mesh geometry", () => { it("preserves multiple holes in extrusion caps and restored buffers", () => { const { points, holes, area } = triangulationCases[1]; const mesh = PrimitiveMesh.createExtrudedPolygon(engine, { points, holes }, 3, { - keepCPUData: true, + keepMeshData: true, depthSegments: 1 }); try { @@ -1370,7 +1376,7 @@ describe("procedural mesh geometry", () => { it("restores captured geometry after caller-owned inputs and buffers change", () => { const points = [new Vector3(0, 0, 0), new Vector3(0, 1, 1), new Vector3(1, 2, 2)]; const mesh = PrimitiveMesh.createTube(engine, points, 0.5, { - keepCPUData: true, + keepMeshData: true, pathSegments: 8, radialSegments: 8 }); @@ -1391,16 +1397,16 @@ describe("procedural mesh geometry", () => { }); it.each([ - { type: "tube", tubeRadius: 0.5, keepCPUData: false }, - { type: "tube", tubeRadius: 0.5, keepCPUData: true }, - { type: "extrudedPolygon", extrudedPolygonDepth: 1, keepCPUData: false }, - { type: "extrudedPolygon", extrudedPolygonDepth: 1, keepCPUData: true } - ])("copies $type path points for device restoration with keepCPUData=$keepCPUData", ({ type, keepCPUData }) => { + { 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, { keepCPUData, pathSegments: 12, radialSegments: 8 }) - : PrimitiveMesh.createExtrudedPolygon(engine, polygon, points, { keepCPUData, pathSegments: 12 }); + ? 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); @@ -1435,8 +1441,8 @@ describe("procedural mesh geometry", () => { it("restores spheres independently after interleaved creation", () => { const meshes = [ - PrimitiveMesh.createSphere(engine, 0.5, { keepCPUData: true, subdivisionLevel: 2 }), - PrimitiveMesh.createSphere(engine, 2, { keepCPUData: true, subdivisionLevel: 4 }) + 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(), @@ -1460,7 +1466,7 @@ describe("procedural mesh geometry", () => { it("uses 32-bit indices for subdivided meshes beyond 65535 vertices", () => { const mesh = PrimitiveMesh.createPlane(engine, 1, 1, { - keepCPUData: true, + keepMeshData: true, widthSegments: 256, depthSegments: 256 }); @@ -1474,7 +1480,7 @@ describe("procedural mesh geometry", () => { 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, { - keepCPUData: true, + keepMeshData: true, closedPath: true, pathSegments: segments, radialSegments: 8 @@ -1498,7 +1504,7 @@ describe("procedural mesh geometry", () => { it.each([1, 2])("keeps torus-knot cross-sections with %s longitudinal segments", (segments) => { const mesh = PrimitiveMesh.createTorusKnot(engine, 1, 0.2, 2, 3, { - keepCPUData: true, + keepMeshData: true, pathSegments: segments, radialSegments: 8 }); @@ -1529,7 +1535,7 @@ describe("procedural mesh geometry", () => { return new Vector3(Math.cos(angle), Math.sin(angle), Math.sin(angle * 2) / 3); }); const mesh = PrimitiveMesh.createTube(engine, points, 0.5, { - keepCPUData: true, + keepMeshData: true, closedPath: true, pathSegments: 40, radialSegments @@ -1554,7 +1560,7 @@ describe("procedural mesh geometry", () => { }); 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 = { keepCPUData: true, closedPath: true }; + 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, @@ -1604,7 +1610,7 @@ describe("procedural mesh geometry", () => { ]; 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, { - keepCPUData: true, + keepMeshData: true, separateMaterialSlots: true, closedPath: true, pathSegments: 16 @@ -1622,8 +1628,8 @@ describe("procedural mesh geometry", () => { }); it("ignores settings from the inactive extrusion mode", () => { - const linearOptions = { keepCPUData: true, depthSegments: 2, bevelWidth: 0.1, separateMaterialSlots: true }; - const pathOptions = { keepCPUData: true, pathSegments: 5, separateMaterialSlots: true }; + 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, @@ -1665,7 +1671,7 @@ describe("procedural mesh geometry", () => { 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, { keepCPUData: true, closedPath: true }); + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, profile, points, { keepMeshData: true, closedPath: true }); try { const positions = mesh.getPositions()!; const indices = mesh.getIndices()!; @@ -1687,7 +1693,7 @@ describe("procedural mesh geometry", () => { 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, { - keepCPUData: true, + keepMeshData: true, pathSegments: 4, radialSegments }); @@ -1717,7 +1723,7 @@ describe("procedural mesh geometry", () => { "keeps %s UVs within the shortest longitudinal interval", (create) => { for (const segments of [1, 2, 3]) { - const mesh = PrimitiveMesh[create](engine, 1, { edgeSegments: segments, keepCPUData: true }); + const mesh = PrimitiveMesh[create](engine, 1, { edgeSegments: segments, keepMeshData: true }); try { const uvs = mesh.getUVs()!; const indices = mesh.getIndices()!; @@ -1770,7 +1776,7 @@ describe("procedural mesh geometry", () => { const restoredEngine = await WebGLEngine.create({ canvas: document.createElement("canvas") }); const released = PrimitiveMesh.createSphere(restoredEngine, 1, { subdivisionLevel: 1 }); const mesh = PrimitiveMesh.createCuboid(restoredEngine, 1, 1, 1, { - keepCPUData: true, + keepMeshData: true, separateMaterialSlots: true, widthSegments: 1, heightSegments: 1, @@ -1825,7 +1831,7 @@ describe("procedural mesh geometry", () => { it("restores released tangents from edited primitive UVs", () => { const mesh = PrimitiveMesh.createPlane(engine, 2, 3, { - keepCPUData: true, + keepMeshData: true, widthSegments: 1, depthSegments: 1 }); @@ -1850,7 +1856,7 @@ describe("procedural mesh geometry", () => { const mesh = PrimitiveMesh.createPlane(engine, 1, 1, { widthSegments: 2, depthSegments: 1, - keepCPUData: true + keepMeshData: true }); try { mesh.setPositions([ @@ -1887,7 +1893,7 @@ describe("procedural mesh geometry", () => { it.each([1, 1e-8])("normalizes tangents for a plane of size %s", (size) => { const mesh = PrimitiveMesh.createPlane(engine, size, size, { - keepCPUData: true, + keepMeshData: true, widthSegments: 1, depthSegments: 1 }); @@ -1918,7 +1924,7 @@ describe("procedural mesh geometry", () => { }); it.each([false, true])("preserves tangent data when adding a vertex channel after reading: %s", (readTangents) => { - const mesh = PrimitiveMesh.createSphere(engine, 0.5, { keepCPUData: true, subdivisionLevel: 2 }); + const mesh = PrimitiveMesh.createSphere(engine, 0.5, { keepMeshData: true, subdivisionLevel: 2 }); try { const original = MeshTestUtils.readBuffer(mesh.vertexBufferBindings[1]!.buffer); if (readTangents) { @@ -1945,7 +1951,7 @@ describe("procedural mesh geometry", () => { }); it("uses standard tangent access and mutation for primitives", () => { - const mesh = PrimitiveMesh.createPlane(engine, 1, 1, { keepCPUData: true }); + 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)); @@ -1973,7 +1979,7 @@ describe("procedural mesh geometry", () => { }); it("releases primitive tangent data through the ModelMesh buffer lifecycle", () => { - const mesh = PrimitiveMesh.createPlane(engine, 1, 1, { keepCPUData: true }); + const mesh = PrimitiveMesh.createPlane(engine, 1, 1, { keepMeshData: true }); try { const tangentBuffer = mesh.vertexBufferBindings[1]!.buffer; expect(tangentBuffer.readable).toBe(true); @@ -2007,7 +2013,7 @@ describe("procedural mesh geometry", () => { const angle = (i * Math.PI * 2) / 256; return new Vector2(Math.cos(angle), Math.sin(angle)); }); - const mesh = PrimitiveMesh.createExtrudedPolygon(engine, contour, 1, { keepCPUData: true, depthSegments: 43 }); + const mesh = PrimitiveMesh.createExtrudedPolygon(engine, contour, 1, { keepMeshData: true, depthSegments: 43 }); try { const indices = mesh.getIndices()!; expect(mesh.vertexCount).toBeGreaterThan(65535); @@ -2032,7 +2038,7 @@ describe("procedural mesh geometry", () => { ] }, 1, - { keepCPUData: true, bevelWidth: 0.1, depthSegments: 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); diff --git a/tests/src/core/physics/ColliderLayer.test.ts b/tests/src/core/physics/ColliderLayer.test.ts index ce23389fcd..e9dd2e1b2b 100644 --- a/tests/src/core/physics/ColliderLayer.test.ts +++ b/tests/src/core/physics/ColliderLayer.test.ts @@ -102,7 +102,7 @@ describe("Collider layer initialization", () => { expect(attach.mock.calls.length).toBe(1); const mesh = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { - keepCPUData: true, + keepMeshData: true, widthSegments: 1, heightSegments: 1, depthSegments: 1 diff --git a/tests/src/core/physics/MeshColliderLayer.test.ts b/tests/src/core/physics/MeshColliderLayer.test.ts index 9b6c84dab6..2196fce054 100644 --- a/tests/src/core/physics/MeshColliderLayer.test.ts +++ b/tests/src/core/physics/MeshColliderLayer.test.ts @@ -26,7 +26,7 @@ describe("Mesh collider collision layers", () => { engine = await WebGLEngine.create({ canvas: document.createElement("canvas"), physics: createPhysics() }); physics = engine.sceneManager.activeScene.physics; mesh = PrimitiveMesh.createCuboid(engine, 10, 1, 10, { - keepCPUData: true, + keepMeshData: true, widthSegments: 1, heightSegments: 1, depthSegments: 1 diff --git a/tests/src/loader/PrimitiveMeshLoader.test.ts b/tests/src/loader/PrimitiveMeshLoader.test.ts index 8547b09a36..50ac0b58f8 100644 --- a/tests/src/loader/PrimitiveMeshLoader.test.ts +++ b/tests/src/loader/PrimitiveMeshLoader.test.ts @@ -59,8 +59,8 @@ 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 = { keepCPUData: true }; -const groupedOptions = { keepCPUData: true, separateMaterialSlots: true }; +const options = { keepMeshData: true }; +const groupedOptions = { keepMeshData: true, separateMaterialSlots: true }; const mixedLinearOptions = { ...groupedOptions, depthSegments: 2, closedPath: true }; const mixedPathOptions = { ...groupedOptions, @@ -616,7 +616,7 @@ describe("PrimitiveMeshLoader", () => { } }); - it.each([{}, { subdivisionLevel: 1, keepCPUData: true }])( + it.each([{}, { subdivisionLevel: 1, keepMeshData: true }])( "reuses serialized options without angle ranges: %j", async (sphereOptions) => { const data: PrimitiveMeshAsset = { type: "sphere", sphereRadius: 0.5, sphereOptions }; @@ -682,7 +682,7 @@ describe("PrimitiveMeshLoader", () => { ? { type, cylinderRadius: 0.5, cylinderHeight: 2 } : { type, truncatedConeTopRadius: 0.25, truncatedConeBottomRadius: 0.5, truncatedConeHeight: 2 }; const data = JSON.parse( - JSON.stringify({ ...shape, [optionsKey]: { caps, keepCPUData: true, separateMaterialSlots: true } }) + JSON.stringify({ ...shape, [optionsKey]: { caps, keepMeshData: true, separateMaterialSlots: true } }) ); expect(data[optionsKey].caps).toBe(value); request.mockReturnValue(AssetPromise.resolve(data) as any); From 085211212e5cc73e2b4384443e91279183083d4b Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sun, 15 Nov 2026 02:59:34 +0800 Subject: [PATCH 21/24] fix(core): simplify primitive restoration and mesh edge cases --- docs/en/graphics/mesh/primitiveMesh.mdx | 5 +- docs/zh/graphics/mesh/primitiveMesh.mdx | 5 +- packages/core/src/mesh/MeshTangentUtils.ts | 2 +- .../core/src/mesh/primitive/PolygonUtils.ts | 4 +- .../mesh/primitive/PrimitiveMeshRestorer.ts | 37 +-- tests/src/core/mesh/PrimitiveMesh.test.ts | 19 +- tests/src/core/mesh/ProceduralMesh.test.ts | 223 +++++++----------- 7 files changed, 121 insertions(+), 174 deletions(-) diff --git a/docs/en/graphics/mesh/primitiveMesh.mdx b/docs/en/graphics/mesh/primitiveMesh.mdx index 9bb3c3022f..2abeb604f1 100644 --- a/docs/en/graphics/mesh/primitiveMesh.mdx +++ b/docs/en/graphics/mesh/primitiveMesh.mdx @@ -229,6 +229,8 @@ const sixMaterials = PrimitiveMesh.createCuboid(engine, 1, 1, 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. It does not guarantee preservation of mesh edits made after creation. + `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 | @@ -266,7 +268,8 @@ Each `type` selects the matching `PrimitiveMesh.createX` method. Type-prefixed f | `sphere`, `circle` | `Radius` | | `cuboid` | `cuboidWidth`, `cuboidHeight`, `cuboidDepth` | | `plane` | `planeWidth`, `planeDepth` | -| `cylinder`, `cone`, `capsule` | `Radius`, `Height` | +| `cylinder`, `cone` | `Radius`, `Height` | +| `capsule` | `capsuleRadius`, `capsuleCylinderHeight` | | `truncatedCone` | `truncatedConeTopRadius`, `truncatedConeBottomRadius`, `truncatedConeHeight` | | `torus` | `torusRadius`, `torusTubeRadius` | | `ring` | `ringOuterRadius`, `ringInnerRadius` | diff --git a/docs/zh/graphics/mesh/primitiveMesh.mdx b/docs/zh/graphics/mesh/primitiveMesh.mdx index a1094e3d21..af6ef03cfd 100644 --- a/docs/zh/graphics/mesh/primitiveMesh.mdx +++ b/docs/zh/graphics/mesh/primitiveMesh.mdx @@ -235,6 +235,8 @@ const sixMaterials = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { `keepMeshData` 默认关闭,设为 `true` 时保留顶点属性和索引,供上传后读取或修改。 +设备自动恢复使用初始创建参数,不保证保留创建后的网格修改。 + `separateMaterialSlots` 适用于长方体、圆柱、圆台、圆锥、多边形、挤出和圆角长方体。默认关闭,生成一个 SubMesh;开启后,生成的 SubMesh 按以下顺序对应材质槽: | 几何体 | 材质槽顺序 | @@ -272,7 +274,8 @@ const asset = { | `sphere`、`circle` | `Radius` | | `cuboid` | `cuboidWidth`、`cuboidHeight`、`cuboidDepth` | | `plane` | `planeWidth`、`planeDepth` | -| `cylinder`、`cone`、`capsule` | `Radius`、`Height` | +| `cylinder`、`cone` | `Radius`、`Height` | +| `capsule` | `capsuleRadius`、`capsuleCylinderHeight` | | `truncatedCone` | `truncatedConeTopRadius`、`truncatedConeBottomRadius`、`truncatedConeHeight` | | `torus` | `torusRadius`、`torusTubeRadius` | | `ring` | `ringOuterRadius`、`ringInnerRadius` | diff --git a/packages/core/src/mesh/MeshTangentUtils.ts b/packages/core/src/mesh/MeshTangentUtils.ts index 3df94c5708..5a4bab9729 100644 --- a/packages/core/src/mesh/MeshTangentUtils.ts +++ b/packages/core/src/mesh/MeshTangentUtils.ts @@ -28,7 +28,7 @@ export class MeshTangentUtils { const indexCount = indices ? indices.length : vertexCount; // Accumulate the tangent basis in double precision const basis = new Float64Array(vertexCount * 6); - for (let i = 0; i < indexCount; i += 3) { + 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; diff --git a/packages/core/src/mesh/primitive/PolygonUtils.ts b/packages/core/src/mesh/primitive/PolygonUtils.ts index ec9c9d5172..30c9187b0f 100644 --- a/packages/core/src/mesh/primitive/PolygonUtils.ts +++ b/packages/core/src/mesh/primitive/PolygonUtils.ts @@ -41,7 +41,9 @@ export class PolygonUtils { if (i > 0) { holes.push(points.length); } - points.push(...contours[i]); + for (const point of contours[i]) { + points.push(point); + } } const coordinates = new Float64Array(points.length * 2); for (let i = 0; i < points.length; i++) { diff --git a/packages/core/src/mesh/primitive/PrimitiveMeshRestorer.ts b/packages/core/src/mesh/primitive/PrimitiveMeshRestorer.ts index b2bf1a5ee2..20207070a9 100644 --- a/packages/core/src/mesh/primitive/PrimitiveMeshRestorer.ts +++ b/packages/core/src/mesh/primitive/PrimitiveMeshRestorer.ts @@ -25,43 +25,22 @@ export class PrimitiveMeshRestorer extends ContentRestorer< override restoreContent(): void { const mesh = this.resource; - const vertexBuffer = this._vertexBuffer; - const indexBuffer = mesh._primitive.indexBufferBinding?._buffer; - const indices = mesh.accessible ? mesh.getIndices() : null; - let generated: PrimitiveMeshBuilder | undefined; - // Only regenerate owned buffers; readable data includes changes made after creation + const data = this._generate(...this._args); + data.trim(); for (const binding of mesh.vertexBufferBindings) { const buffer = binding?.buffer; if (!buffer) { continue; } - if (buffer.readable) { - buffer.setData(buffer.data!); - } else if (buffer === vertexBuffer) { - generated ??= this._generateData(); - buffer.setData(generated.vertices); + if (buffer === this._vertexBuffer) { + buffer.setData(data.vertices); } else if (buffer === this._tangentBuffer) { - const vertexData = vertexBuffer.readable ? vertexBuffer.data : null; - const vertices = vertexData - ? new Float32Array(vertexData.buffer, vertexData.byteOffset, vertexBuffer.byteLength / 4) - : (generated ??= this._generateData()).vertices; - const tangentIndices = indexBuffer ? (indices ?? (generated ??= this._generateData()).indices) : null; - buffer.setData(MeshTangentUtils.calculateTangentsFromBuffer(vertices, tangentIndices)); + buffer.setData(MeshTangentUtils.calculateTangentsFromBuffer(data.vertices, data.indices)); } } - if (indexBuffer) { - if (indices) { - indexBuffer.setData(indices); - } else if (indexBuffer === this._indexBuffer) { - generated ??= this._generateData(); - indexBuffer.setData(generated.indices); - } + const indexBuffer = mesh._primitive.indexBufferBinding?._buffer; + if (indexBuffer === this._indexBuffer) { + indexBuffer.setData(data.indices); } } - - private _generateData(): PrimitiveMeshBuilder { - const data = this._generate(...this._args); - data.trim(); - return data; - } } diff --git a/tests/src/core/mesh/PrimitiveMesh.test.ts b/tests/src/core/mesh/PrimitiveMesh.test.ts index 5dbb1be8a1..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 { Vector2, Vector3 } from "@galacean/engine-math"; -import { describe, beforeAll, expect, it } from "vitest"; +import { describe, beforeAll, expect, it, vi } from "vitest"; describe("PrimitiveMesh", () => { let engine: WebGLEngine; @@ -197,7 +197,22 @@ describe("PrimitiveMesh", () => { widthSegments: segments, depthSegments: segments }) - ).throw("The vertex count is out of range."); + ).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 index a9b9b243f3..b4188e1c46 100644 --- a/tests/src/core/mesh/ProceduralMesh.test.ts +++ b/tests/src/core/mesh/ProceduralMesh.test.ts @@ -1373,29 +1373,6 @@ describe("procedural mesh geometry", () => { } }); - it("restores captured geometry after caller-owned inputs and buffers change", () => { - const points = [new Vector3(0, 0, 0), new Vector3(0, 1, 1), new Vector3(1, 2, 2)]; - const mesh = PrimitiveMesh.createTube(engine, points, 0.5, { - keepMeshData: true, - pathSegments: 8, - radialSegments: 8 - }); - try { - const before = mesh.getPositions()!.map((p) => p.toJSON()); - const indices = Array.from(mesh.getIndices()!); - points[1].set(100, 200, 300); - const buffer = mesh.vertexBufferBindings[0]!.buffer; - MeshTestUtils.clearBuffer(buffer); - const restorers = (engine.resourceManager as any)._contentRestorerPool; - restorers[mesh.instanceId].restoreContent(); - expect(mesh.getPositions()!.map((p) => p.toJSON())).toEqual(before); - expect(Array.from(mesh.getIndices()!)).toEqual(indices); - expect(mesh.vertexBufferBindings[0]!.buffer).toBe(buffer); - } finally { - mesh.destroy(); - } - }); - it.each([ { type: "tube", tubeRadius: 0.5, keepMeshData: false }, { type: "tube", tubeRadius: 0.5, keepMeshData: true }, @@ -1772,124 +1749,55 @@ describe("procedural mesh geometry", () => { } }); - it("preserves edited primitive data and material groups after device restoration", async () => { - const restoredEngine = await WebGLEngine.create({ canvas: document.createElement("canvas") }); - const released = PrimitiveMesh.createSphere(restoredEngine, 1, { subdivisionLevel: 1 }); - const mesh = PrimitiveMesh.createCuboid(restoredEngine, 1, 1, 1, { - keepMeshData: true, - separateMaterialSlots: true, - widthSegments: 1, - heightSegments: 1, - depthSegments: 1 - }); - try { - const uvs = mesh.getUVs()!.map((uv) => new Vector2(uv.x * 2 + 0.25, uv.y * 3 - 0.5)); - const secondaryUVs = uvs.map((uv) => uv.clone().scale(0.5)); - mesh.setUVs(uvs); - mesh.setUVs(secondaryUVs, 1); - mesh.calculateTangents(); - mesh.setIndices(mesh.getIndices()!.slice(0, 6)); - mesh.clearSubMesh(); - const subMesh = mesh.addSubMesh(0, 6); - mesh.bounds.min.set(-2, -3, -4); - mesh.bounds.max.set(2, 3, 4); - mesh.uploadData(false); - const bindings = mesh.vertexBufferBindings.map((binding) => binding!.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 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.getUVs()!.map((uv) => uv.toJSON())).toEqual(uvs.map((uv) => uv.toJSON())); - expect(mesh.getUVs(1)!.map((uv) => uv.toJSON())).toEqual(secondaryUVs.map((uv) => uv.toJSON())); - expect(mesh.getIndices()!).toHaveLength(6); - expect(mesh.subMeshes).toHaveLength(1); - expect(mesh.subMeshes[0]).toBe(subMesh); - expect(mesh.bounds.min.toJSON()).toEqual({ x: -2, y: -3, z: -4 }); - expect(mesh.bounds.max.toJSON()).toEqual({ x: 2, y: 3, z: 4 }); - bindings.forEach((buffer, index) => { - expect(mesh.vertexBufferBindings[index]!.buffer).toBe(buffer); - expect(MeshTestUtils.readBuffer(buffer)).toEqual(buffers[index]); - }); - releasedBindings.forEach((buffer, index) => { - expect(MeshTestUtils.readBuffer(buffer)).toEqual(releasedBuffers[index]); - }); - } finally { - restoredEngine.destroy(); - } - }); - - it("restores released tangents from edited primitive UVs", () => { - const mesh = PrimitiveMesh.createPlane(engine, 2, 3, { - keepMeshData: true, - widthSegments: 1, - depthSegments: 1 - }); - try { - mesh.setUVs(mesh.getUVs()!.map((uv) => new Vector2(uv.y, uv.x))); - mesh.calculateTangents(); - mesh.uploadData(true); - const bindings = mesh.vertexBufferBindings.map((binding) => binding!.buffer); - bindings.push(mesh._primitive.indexBufferBinding!._buffer); - const original = bindings.map((buffer) => MeshTestUtils.readBuffer(buffer)); - bindings.forEach((buffer) => MeshTestUtils.clearBuffer(buffer)); - (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); - bindings.forEach((buffer, index) => { - expect(MeshTestUtils.readBuffer(buffer)).toEqual(original[index]); + 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 }); - } finally { - mesh.destroy(); - } - }); - - it.each([false, true])("restores non-indexed primitive tangents with released data: %s", (releaseData) => { - const mesh = PrimitiveMesh.createPlane(engine, 1, 1, { - widthSegments: 2, - depthSegments: 1, - keepMeshData: true - }); - try { - mesh.setPositions([ - new Vector3(0, 0, 0), - new Vector3(1, 0, 0), - new Vector3(0, 1, 0), - new Vector3(2, 0, 0), - new Vector3(3, 0, 0), - new Vector3(2, 1, 0) - ]); - mesh.setNormals(Array.from({ length: 6 }, () => new Vector3(0, 0, 1))); - mesh.setUVs([ - new Vector2(0, 0), - new Vector2(1, 0), - new Vector2(0, 1), - new Vector2(0, 0), - new Vector2(0, 1), - new Vector2(1, 0) - ]); - mesh.setIndices(null); - mesh.clearSubMesh(); - mesh.addSubMesh(0, 6); - mesh.calculateTangents(); - mesh.uploadData(releaseData); - const tangentBuffer = mesh.vertexBufferBindings[1]!.buffer; - const original = MeshTestUtils.readBuffer(tangentBuffer); - MeshTestUtils.clearBuffer(tangentBuffer); - (engine.resourceManager as any)._contentRestorerPool[mesh.instanceId].restoreContent(); - expect(MeshTestUtils.readBuffer(tangentBuffer)).toEqual(original); - } finally { - mesh.destroy(); + 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, { @@ -2008,6 +1916,43 @@ describe("procedural mesh geometry", () => { } }); + 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; From 8b635f8a2fa7f8c3551568436903dc0608381e79 Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sun, 15 Nov 2026 13:27:06 +0800 Subject: [PATCH 22/24] docs: clarify primitive mesh usage and script guidance --- docs/en/graphics/background/sky.mdx | 4 +- docs/en/graphics/mesh/primitiveMesh.mdx | 56 +++++++++++-- docs/zh/graphics/background/sky.mdx | 2 +- docs/zh/graphics/mesh/primitiveMesh.mdx | 64 +++++++++++--- packages/core/src/mesh/ModelMesh.ts | 2 +- packages/core/src/mesh/PrimitiveMesh.ts | 40 ++++++++- .../core/src/mesh/PrimitiveMeshOptions.ts | 2 +- .../galacean/skills/engine-knowledge/SKILL.md | 2 +- .../references/mesh-geometry.md | 83 +++++++------------ packages/loader/src/PrimitiveMeshAsset.ts | 15 ++++ 10 files changed, 191 insertions(+), 79 deletions(-) diff --git a/docs/en/graphics/background/sky.mdx b/docs/en/graphics/background/sky.mdx index dfaf6bff67..e30ce0b8d6 100644 --- a/docs/en/graphics/background/sky.mdx +++ b/docs/en/graphics/background/sky.mdx @@ -43,9 +43,9 @@ 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; diff --git a/docs/en/graphics/mesh/primitiveMesh.mdx b/docs/en/graphics/mesh/primitiveMesh.mdx index 2abeb604f1..af8eeb8027 100644 --- a/docs/en/graphics/mesh/primitiveMesh.mdx +++ b/docs/en/graphics/mesh/primitiveMesh.mdx @@ -36,7 +36,7 @@ Built-in geometries not meeting your needs? You can create a `Mesh` asset in the ## 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** @@ -134,7 +134,7 @@ renderer.setMaterial(material); 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 unitSphere = PrimitiveMesh.createSphere(engine, 0.5); +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); @@ -147,7 +147,7 @@ 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. +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 | | --- | --- | @@ -178,7 +178,11 @@ Cylinder and frustum `caps` use `PrimitiveMeshCapMode`: `Both` (default), `Top`, ### Contours and paths -Contours and lathe profiles use `Vector2` arrays, and path points use `Vector3` 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. Closing points need not be repeated. +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. + +`createLathe` 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; end caps are not added automatically. Path points for tubes and extrusions use `Vector3` arrays in local coordinates. ```ts import { Vector2, Vector3 } from "@galacean/engine"; @@ -213,6 +217,42 @@ For tubes and path extrusions, `closedPath` defaults to `false`. Set it to `true `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. | +| Lathe | 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: @@ -229,7 +269,7 @@ const sixMaterials = PrimitiveMesh.createCuboid(engine, 1, 1, 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. It does not guarantee preservation of mesh edits made after creation. +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: @@ -263,6 +303,8 @@ const asset = { 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` | @@ -311,6 +353,6 @@ Profiles and polygon contours store `{ x, y }` points; paths store `{ x, y, z }` } ``` -Path extrusion uses the required `extrudedPolygonPath` field instead of `extrudedPolygonDepth` and ignores bevel settings. Set `extrudedPolygonOptions.closedPath` to `true` for a closed path without end caps. Save path points as `{ x, y, z }`. +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 }`. -The type-prefixed fields, including `Options`, pass through the Editor's primitive asset bundler. Editor previews should select the same creation method and parameters as the saved asset. +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 fbd1d1919b..cc4bf4c72b 100644 --- a/docs/zh/graphics/background/sky.mdx +++ b/docs/zh/graphics/background/sky.mdx @@ -45,7 +45,7 @@ label: Graphics/Background ```typescript // 创建大气散射材质 const skyMaterial = new SkyProceduralMaterial(engine); -// 设置天空盒 +// 设置程序化天空背景 const background = scene.background; background.mode = BackgroundMode.Sky; background.sky.material = skyMaterial; diff --git a/docs/zh/graphics/mesh/primitiveMesh.mdx b/docs/zh/graphics/mesh/primitiveMesh.mdx index af6ef03cfd..0dcf9a0346 100644 --- a/docs/zh/graphics/mesh/primitiveMesh.mdx +++ b/docs/zh/graphics/mesh/primitiveMesh.mdx @@ -36,9 +36,9 @@ label: Graphics/Mesh ## 脚本使用 -目前提供的几何体如下: +以下展示常见几何体的用法,完整创建方法见[程序化几何](#程序化几何)。 -- [createCuboid](/apis/core/#PrimitiveMesh-createCuboid) **立方体** +- [createCuboid](/apis/core/#PrimitiveMesh-createCuboid) **长方体** ```typescript const entity = rootEntity.createChild("cuboid"); @@ -90,7 +90,7 @@ 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"); @@ -134,7 +134,7 @@ renderer.setMaterial(material); 每个工厂方法先接收必填的形状参数,再接收可选的具名配置对象。尺寸、半径、轮廓和路径必须明确指定;细分、角度范围和网格设置保留在 options 中,省略时使用注释说明的默认值。例如,`createSphere` 先接收半径,再接收 `SphereMeshOptions`: ```ts -const unitSphere = PrimitiveMesh.createSphere(engine, 0.5); +const smallSphere = PrimitiveMesh.createSphere(engine, 0.5); const sphere = PrimitiveMesh.createSphere(engine, 1); const smoothSphere = PrimitiveMesh.createSphere(engine, 1, { subdivisionLevel: 4 }); @@ -151,19 +151,19 @@ const mirroredKnot = PrimitiveMesh.createTorusKnot(engine, 1, 0.1, 2, -3); 尺寸必须显式传入;分段和网格设置使用具名字段,可以只指定需要调整的可选项。 -环面结的 `axisTurns` 表示绕中心轴的圈数,`crossSectionTurns` 表示绕环面截面的圈数。两者都是有符号整数,与网格分段数无关。负值反转对应方向的缠绕,`0` 表示该方向的角度保持不变。 +环面结的 `axisTurns` 表示绕中心轴的圈数,`crossSectionTurns` 表示绕环面截面的圈数。两者都是有符号整数,与网格分段数无关。负值反转对应方向的缠绕,`0` 表示该方向的角度保持不变,两者至少有一个非零。 | 能力 | 创建方法 | | --- | --- | | 平面、长方体、球 | `createPlane`、`createCuboid`、`createSphere` | | 圆柱、圆台、圆锥、胶囊 | `createCylinder`、`createTruncatedCone`、`createCone`、`createCapsule` | -| 圆盘、圆环面、圆环体、环面结 | `createCircle`、`createRing`、`createTorus`、`createTorusKnot` | +| 圆盘、平面圆环、环面、环面结 | `createCircle`、`createRing`、`createTorus`、`createTorusKnot` | | 四面体、八面体、二十面体、十二面体 | `createTetrahedron`、`createOctahedron`、`createIcosahedron`、`createDodecahedron` | | 旋转体、路径管道、平面多边形、挤出多边形、圆角长方体 | `createLathe`、`createTube`、`createPolygon`、`createExtrudedPolygon`、`createRoundedCuboid` | ### 分段、角度和端盖 -管道和环面结用 `pathSegments` 控制沿路径的分段,圆环用 `ringSegments` 控制环向分段,`radialSegments` 控制管截面的周向分段。胶囊的 `capSegments` 控制每个半球从极点到赤道的分段,`cylinderHeight` 表示直筒部分的高度。正多面体用 `edgeSegments`,圆角长方体用 `roundingSegments`。 +管道和环面结用 `pathSegments` 控制沿路径的分段,环面用 `ringSegments` 控制环向分段,`radialSegments` 控制管截面的周向分段。胶囊的 `capSegments` 控制每个半球从极点到赤道的分段,`cylinderHeight` 表示直筒部分的高度。正多面体用 `edgeSegments`,圆角长方体用 `roundingSegments`。 角度范围统一放在配置对象中。所有角度均使用**度数**,范围使用 `Vector2`,`x` 表示起始角,`y` 表示结束角。跨越 360 度时使用连续角度,例如 `new Vector2(350, 370)`。圆柱、圆台和圆锥围绕 Y 轴,从 -Z 朝 -X 方向开始;旋转体从 +Z 朝 +X 方向开始。球体的垂直角度从 +Y 极点开始。 @@ -182,7 +182,11 @@ const halfRing = PrimitiveMesh.createRing(engine, 1, 0.5, { angleRange: new Vect ### 轮廓与路径 -轮廓和旋转体截面使用 `Vector2` 数组,路径点使用 `Vector3` 数组。一个简单多边形直接传入点数组;有孔洞时使用 `{ points, holes }`,多个多边形使用这种对象的数组。首尾点不必重复。 +多边形轮廓使用 `Vector2` 数组。一个简单多边形直接传入点数组;有孔洞时使用 `{ points, holes }`,多个多边形使用这种对象的数组。多边形轮廓会自动闭合,不必重复首点。 + +`createPolygon` 创建位于 XY 平面、正面朝 +Z 的零厚度表面,不生成侧壁。`createExtrudedPolygon` 为轮廓增加厚度或沿路径挤出,生成侧壁和相应的端盖。 + +`createLathe` 将 `Vector2` 截面绕 Y 轴旋转:`x` 表示到 Y 轴的半径,`y` 表示高度,两者均使用局部单位。相邻截面点按输入顺序连接,不会自动添加端盖。管道和挤出的路径点使用局部坐标下的 `Vector3` 数组。 ```ts import { Vector2, Vector3 } from "@galacean/engine"; @@ -219,6 +223,42 @@ const closedPath = PrimitiveMesh.createExtrudedPolygon(engine, outline, loop, { `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,这些映射不会按形状包围盒归一化。 + ### 网格数据和材质 网格设置与分段设置放在同一个可选配置对象中: @@ -235,7 +275,7 @@ const sixMaterials = PrimitiveMesh.createCuboid(engine, 1, 1, 1, { `keepMeshData` 默认关闭,设为 `true` 时保留顶点属性和索引,供上传后读取或修改。 -设备自动恢复使用初始创建参数,不保证保留创建后的网格修改。 +设备自动恢复使用初始创建参数。即使 `keepMeshData` 为 `true`,也不会额外备份创建后的网格修改。 `separateMaterialSlots` 适用于长方体、圆柱、圆台、圆锥、多边形、挤出和圆角长方体。默认关闭,生成一个 SubMesh;开启后,生成的 SubMesh 按以下顺序对应材质槽: @@ -269,6 +309,8 @@ const asset = { 每个 `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` | @@ -317,6 +359,6 @@ const asset = { } ``` -沿路径拉伸通过必填的 `extrudedPolygonPath` 代替 `extrudedPolygonDepth`,并忽略倒角设置。`extrudedPolygonOptions.closedPath` 设为 `true` 时闭合路径且不生成端盖。路径点保存为 `{ x, y, z }`。 +沿路径挤出通过必填的 `extrudedPolygonPath` 代替 `extrudedPolygonDepth`。可选设置遵循 `PathExtrudedPolygonMeshOptions`,倒角设置仅属于直线挤出。`extrudedPolygonOptions.closedPath` 设为 `true` 时闭合路径且不生成端盖。路径点保存为 `{ x, y, z }`。 -以上类型前缀字段及 `Options` 都能经过 Editor 现有的基础网格打包过滤。Editor 预览应使用与保存资产相同的创建方法和参数。 +编辑器对接时,需要使用包含这些 API 的 Engine 包版本。预览应使用与保存资产相同的创建方法和参数。 diff --git a/packages/core/src/mesh/ModelMesh.ts b/packages/core/src/mesh/ModelMesh.ts index 15b02319ca..467fd7c15c 100644 --- a/packages/core/src/mesh/ModelMesh.ts +++ b/packages/core/src/mesh/ModelMesh.ts @@ -671,7 +671,7 @@ export class ModelMesh extends Mesh { * Calculate tangents from readable positions, normals and UVs. * @remarks * Without indices, every three consecutive vertices form a triangle. - * Triangles with zero UV area are ignored. + * Incomplete trailing triangles and triangles with zero UV area are ignored. * @see http://foundationsofgameenginedev.com/FGED2-sample.pdf */ calculateTangents(): void { diff --git a/packages/core/src/mesh/PrimitiveMesh.ts b/packages/core/src/mesh/PrimitiveMesh.ts index 4cbcee704d..1e7dd4ebaa 100644 --- a/packages/core/src/mesh/PrimitiveMesh.ts +++ b/packages/core/src/mesh/PrimitiveMesh.ts @@ -38,6 +38,7 @@ import { SubdivisionUtils } from "./primitive/SubdivisionUtils"; * 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 readonly _sphereSeedPositions = new Float32Array([ @@ -176,6 +177,8 @@ export class PrimitiveMesh { /** * 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 @@ -202,6 +205,10 @@ export class PrimitiveMesh { /** * 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 @@ -229,6 +236,7 @@ export class PrimitiveMesh { /** * 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 @@ -248,6 +256,8 @@ export class PrimitiveMesh { /** * 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 @@ -281,6 +291,8 @@ export class PrimitiveMesh { /** * 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 @@ -321,6 +333,8 @@ export class PrimitiveMesh { /** * 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 @@ -343,6 +357,8 @@ export class PrimitiveMesh { /** * 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` @@ -368,6 +384,7 @@ export class PrimitiveMesh { /** * 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 @@ -400,6 +417,7 @@ export class PrimitiveMesh { /** * 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 @@ -419,6 +437,7 @@ export class PrimitiveMesh { /** * 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 @@ -440,6 +459,8 @@ export class PrimitiveMesh { /** * 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 @@ -457,6 +478,8 @@ export class PrimitiveMesh { /** * 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 @@ -474,6 +497,8 @@ export class PrimitiveMesh { /** * 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 @@ -491,6 +516,8 @@ export class PrimitiveMesh { /** * 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 @@ -508,6 +535,8 @@ export class PrimitiveMesh { /** * Revolve a radius-height profile around Y. + * No end caps are added automatically. + * 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 radius-height profile, with at least two points; X is radius and Y is height * @param options - Optional mesh generation settings @@ -526,7 +555,8 @@ export class PrimitiveMesh { } /** - * Sweep a circular cross-section along a path. + * 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 @@ -547,6 +577,7 @@ export class PrimitiveMesh { /** * 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 @@ -567,6 +598,8 @@ export class PrimitiveMesh { /** * 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 @@ -583,6 +616,8 @@ export class PrimitiveMesh { * 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 @@ -632,6 +667,7 @@ export class PrimitiveMesh { /** * 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 @@ -661,7 +697,7 @@ export class PrimitiveMesh { /** * Create an axis-aligned cuboid with rounded edges and corners. * @remarks - * UVs preserve the cuboid's face orientations and account for rounded edge length. + * 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 diff --git a/packages/core/src/mesh/PrimitiveMeshOptions.ts b/packages/core/src/mesh/PrimitiveMeshOptions.ts index 1e191ad764..ab94b39b2b 100644 --- a/packages/core/src/mesh/PrimitiveMeshOptions.ts +++ b/packages/core/src/mesh/PrimitiveMeshOptions.ts @@ -6,7 +6,7 @@ import type { PrimitiveMeshCapMode } from "./enums/PrimitiveMeshCapMode"; */ export interface PrimitiveMeshOptions { /** - * Whether to retain readable mesh data after uploading it to the GPU. + * Whether to retain readable vertex attributes and indices after mesh creation. * @defaultValue `false` */ keepMeshData?: boolean; diff --git a/packages/galacean/skills/engine-knowledge/SKILL.md b/packages/galacean/skills/engine-knowledge/SKILL.md index 39c5480215..19c014d995 100644 --- a/packages/galacean/skills/engine-knowledge/SKILL.md +++ b/packages/galacean/skills/engine-knowledge/SKILL.md @@ -16,7 +16,7 @@ Choose the reference for the current runtime decision; follow links only when an - 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). +- Runtime mesh 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 ffeb53c8e0..c5fc8166a3 100644 --- a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md +++ b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md @@ -1,35 +1,44 @@ # 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 generate, share, or update geometry at runtime. Read the installed factory and mesh declarations for exact inputs, units, UV mapping and material-slot order. -Dimensions are required factory arguments, expressed in local units. The table assumes an entity scale of `(1, 1, 1)`. +## Generate from runtime input -| Primitive | Local extent | Local orientation | -| --------- | ----------------------------------------------------------- | ---------------------------- | -| Cuboid | `width`, `height`, `depth` | centered at the origin | -| Sphere | diameter `2 * radius` | centered at the origin | -| Plane | X size `width`, Z size `depth` | lies in XZ and faces +Y | -| Cylinder | radius `radius`, Y size `height` | centered on Y | -| Cone | base radius `radius`, Y size `height` | centered on Y, tip toward +Y | -| Capsule | radius `radius`, total Y size `cylinderHeight + 2 * radius` | centered on Y | -| Torus | outer radius `radius + tubeRadius`, Z size `2 * tubeRadius` | lies in XY around the Z axis | +Reuse a configured mesh when its geometry already meets the task. Generate a mesh when its shape depends on runtime data, such as a path chosen during play. Keep that mesh while the geometry is unchanged; use Entity transforms for placement, rotation and per-instance scaling. -## Placement consequences +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. -- A centered primitive rests on a horizontal surface when its center is raised by its scaled half-height. -- A Plane is already horizontal; rotating it as if it were an XY plane changes the intended ground orientation. -- Capsule `cylinderHeight` 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. +```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. -## Visual and collision geometry +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). -Primitive meshes and collider shapes own independent dimensions. Set collider dimensions from the intended collision geometry; the assigned mesh does not configure them. Collider dimensions are then affected by the Entity's world scale. +## Update existing vertex data -Exact argument meanings, option fields and defaults remain declaration-owned. +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. -## Draw-ready custom mesh +If topology changes, keep indices and SubMesh draw ranges consistent with the vertex arrays. -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). +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 + +Compare rendered bounds in a common space when aligning runtime pieces. Non-uniform Entity scale changes their rendered extents. 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. + +## Supply custom vertex geometry + +Use `ModelMesh` when the Script supplies vertices and topology. A drawable mesh also needs uploaded data, bounds and a SubMesh draw range. The minimal triangle below assumes an unlit, untextured material on the supplied Renderer; supply any additional attributes required by other materials. ```ts import { Engine, MeshRenderer, ModelMesh, Vector3 } from "@galacean/engine"; @@ -46,35 +55,3 @@ export function createTriangle(engine: Engine, renderer: MeshRenderer): void { renderer.mesh = mesh; } ``` - -## Procedural generators - -Each factory takes required shape inputs followed by one optional named settings object. Dimensions, radii, contours and paths have no API defaults. Subdivision counts, angular ranges and mesh settings remain optional. Every shape has a public options type, such as `SphereMeshOptions`; the four regular polyhedra share `RegularPolyhedronMeshOptions`. Query the factory and its options type for argument meanings, units and option defaults. - -For example, `createSphere(engine, 1, { subdivisionLevel: 3 })` specifies the radius and subdivision level. `createCuboid(engine, 2, 3, 4)` requires all three dimensions. `createPlane(engine, 2, 3)` specifies its X and Z sizes. Later plane/cuboid subdivision counts use the first direction by default. - -`createCylinder(engine, radius, height)` creates equal end radii. Use `createTruncatedCone(engine, topRadius, bottomRadius, height)` for different radii. Tubes take a required `Vector3` path and radius followed by `TubeMeshOptions`; lathe profiles take a required `Vector2` array followed by `LatheMeshOptions`. - -Torus-knot `axisTurns` counts revolutions around the central axis; `crossSectionTurns` counts revolutions around the torus cross-section. Both are required signed integers, independent of mesh subdivisions. Negative values reverse the corresponding winding direction; zero keeps that angle fixed. - -Angles use degrees. Ranges use `Vector2`, with `x` as the start angle and `y` as the end angle, such as `new Vector2(30, 180)`. Spherical sections use `horizontalAngleRange` and `verticalAngleRange` in their options. Cylinder and frustum `caps` use the exported `PrimitiveMeshCapMode` enum: `Both` (default), `Top`, `Bottom`, `None`. Top faces +Y and bottom faces -Y; angular cut boundaries remain open. Cones use a boolean `cap`. Plane is in XZ facing +Y; circles, rings and polygons are in XY facing +Z. Capsule `cylinderHeight` excludes its hemispheres. - -`createSphere(engine, radius, { subdivisionLevel, horizontalAngleRange, verticalAngleRange })` projects a subdivided cube onto a sphere. The subdivision level defaults to 3 and is clamped to 1 through 6. It accepts `horizontalAngleRange` and `verticalAngleRange`. These clip the subdivided surface and leave open boundaries. Horizontal angles start at -X towards +Z, and vertical angles start at +Y. Continuous horizontal intervals such as `new Vector2(350, 370)` cross the seam. Complete spheres and sections use the same subdivision level. - -Additional generators include circle, ring, four regular polyhedra, lathe, tube, polygon, extrusion, torus knot and rounded cuboid. Angle ranges belong to options. Rings require the outer radius first, followed by the inner radius. Contours and lathe profiles use `Vector2` arrays; paths accept `Vector3` arrays and are sampled at equal distances along their line segments. Sample curves into points outside the mesh API. A simple polygon is a point array; holes use `{ points, holes }`. Extrusion has two overloads: a required numeric `depth` followed by `LinearExtrudedPolygonMeshOptions`, or a required `Vector3` array `path` followed by `PathExtrudedPolygonMeshOptions`. The depth overload extrudes along +Z and uses `depthSegments`; the path overload uses `pathSegments` and `closedPath`. Each overload declares its own parameter names, comments and optional settings. Open extrusions have both end caps; closed paths join their end cross-sections without caps. Straight extrusion defaults to no bevel; a positive `bevelWidth` enables it, with `bevelDepth` defaulting to the same value. Path extrusion has no bevels. - -For straight extrusion, `contourOffset` shifts the side-wall outline and defaults to `0`. Positive values expand the solid and contract holes; negative values do the reverse. The offset also applies when `bevelWidth` is `0`. Bevels are cut into the shifted outline and included in the total `depth`. - -For tubes and path extrusions, `closedPath` defaults to `false`. When enabled, the path ends join with matching cross-sections, and the closing point need not be repeated. Closed extrusions use at least three path segments and have no end caps. Open extrusions have both end caps; tubes have no end caps in either mode. - -Mesh settings share the same options object. `keepMeshData` retains vertex attributes and indices for reading or editing after upload and defaults to false. `separateMaterialSlots` defaults to false and is only available for cuboids, cylinders, truncated cones, cones, polygons, extrusions and rounded cuboids. With it enabled, cuboid slots follow +Y, -Y, -X, +X, +Z, -Z; cylinders use side, top, bottom; cones use side, bottom. Disabled or zero-radius caps do not reserve slots. Polygon slots follow shape order, with holes sharing the outer contour's slot. Each open extrusion shape contributes two consecutive slots: both caps, then all walls and bevels. Closed path extrusions contribute one wall slot per shape. Rebuilding a mesh with different parts requires matching the material array to its new slot order. Input values are captured at creation for deterministic device restoration. - -## Serializable primitive assets - -`PrimitiveMeshAsset` is exported from `@galacean/engine` and `@galacean/engine-loader` and covers every `PrimitiveMesh.createX` method. Each asset `type` uses the matching lower-camel name: `sphere`, `cuboid`, `plane`, `cylinder`, `truncatedCone`, `cone`, `capsule`, `torus`, `circle`, `ring`, `tetrahedron`, `octahedron`, `icosahedron`, `dodecahedron`, `lathe`, `tube`, `polygon`, `extrudedPolygon`, `torusKnot`, `roundedCuboid`. - -JSON keeps the type prefix for required geometry inputs and the optional settings object: `{ type: "sphere", sphereRadius: 1, sphereOptions: { subdivisionLevel: 3, keepMeshData: true } }`. Each `Options` uses the factory's named configuration fields and omitted defaults. Angular ranges store `Vector2` components as `{ x, y }`, for example `{ type: "circle", circleRadius: 1, circleOptions: { angleRange: { x: 30, y: 180 } } }`. `sphere` uses the subdivided-cube algorithm; `sphereOptions.subdivisionLevel` sets its subdivision level. `cylinderRadius` controls both end radii; unequal radii use `truncatedConeTopRadius` and `truncatedConeBottomRadius`. - -TypeScript assets use `PrimitiveMeshCapMode` for `caps`; JSON stores its string values `"both"`, `"top"`, `"bottom"`, `"none"`. - -Serialized profiles and contours use `{ x, y }`; paths use `{ x, y, z }`. `polygonShapes` and `extrudedPolygonShapes` are arrays of `{ points, holes? }`. Straight extrusion requires `extrudedPolygonDepth`; path extrusion requires `extrudedPolygonPath` and ignores bevel settings. Set `extrudedPolygonOptions.closedPath` to `true` for a closed path without end caps. Editor previews and saved assets must select the same factory and parameters. diff --git a/packages/loader/src/PrimitiveMeshAsset.ts b/packages/loader/src/PrimitiveMeshAsset.ts index cb331bbdc2..9e537444e5 100644 --- a/packages/loader/src/PrimitiveMeshAsset.ts +++ b/packages/loader/src/PrimitiveMeshAsset.ts @@ -193,11 +193,17 @@ export type PrimitiveMeshAsset = } | { type: "lathe"; + /** + * The profile points in local units; x is the radius from the Y axis and y is the height. + */ latheProfile: SerializedPrimitiveMeshData; latheOptions?: SerializedPrimitiveMeshData; } | { type: "tube"; + /** + * The centerline points in local coordinates. + */ tubePath: SerializedPrimitiveMeshData; /** * The radius of the cross-section in local units. @@ -207,6 +213,9 @@ export type PrimitiveMeshAsset = } | { type: "polygon"; + /** + * The polygons in the XY plane, including any holes. + */ polygonShapes: readonly SerializedPrimitiveMeshData[]; polygonOptions?: PolygonMeshOptions; } @@ -216,6 +225,9 @@ export type PrimitiveMeshAsset = * 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; } @@ -225,6 +237,9 @@ export type PrimitiveMeshAsset = * The path points in local coordinates. */ extrudedPolygonPath: SerializedPrimitiveMeshData; + /** + * The cross-section contours and optional holes in local XY coordinates. + */ extrudedPolygonShapes: readonly SerializedPrimitiveMeshData[]; extrudedPolygonOptions?: PathExtrudedPolygonMeshOptions; } From b07f252fd3ba903fa0c94bf7c69675fadeb6dc8d Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sun, 15 Nov 2026 14:17:12 +0800 Subject: [PATCH 23/24] docs: clarify engine script knowledge boundaries --- .../galacean/skills/engine-knowledge/SKILL.md | 14 ++++--- .../references/mesh-geometry.md | 38 +++++++++++-------- 2 files changed, 31 insertions(+), 21 deletions(-) diff --git a/packages/galacean/skills/engine-knowledge/SKILL.md b/packages/galacean/skills/engine-knowledge/SKILL.md index 19c014d995..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). -- Runtime mesh generation, sharing and vertex updates: [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 c5fc8166a3..e04c859150 100644 --- a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md +++ b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md @@ -1,10 +1,12 @@ # Mesh Geometry -Use this reference when scripts generate, share, or update geometry at runtime. Read the installed factory and mesh declarations for exact inputs, units, UV mapping and material-slot order. +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. -## Generate from runtime input +## Initialize or generate geometry -Reuse a configured mesh when its geometry already meets the task. Generate a mesh when its shape depends on runtime data, such as a path chosen during play. Keep that mesh while the geometry is unchanged; use Entity transforms for placement, rotation and per-instance scaling. +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. + +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. 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. @@ -34,24 +36,30 @@ Update bounds after position changes so culling matches the new geometry. Keep n ## Place geometry and configure collision -Compare rendered bounds in a common space when aligning runtime pieces. Non-uniform Entity scale changes their rendered extents. 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. +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. + +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. ## Supply custom vertex geometry -Use `ModelMesh` when the Script supplies vertices and topology. A drawable mesh also needs uploaded data, bounds and a SubMesh draw range. The minimal triangle below assumes an unlit, untextured material on the supplied Renderer; supply any additional attributes required by other materials. +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"; - -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); +import { BoundingBox, MeshRenderer, ModelMesh, Vector3 } from "@galacean/engine"; + +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; } ``` From d1456966d060c6a6bc924fe74ed48d9965e3a8cd Mon Sep 17 00:00:00 2001 From: "chenmo.gl" Date: Sun, 15 Nov 2026 15:29:57 +0800 Subject: [PATCH 24/24] refactor(core): name revolved surface creation explicitly --- docs/en/graphics/mesh/primitiveMesh.mdx | 13 +++++++----- docs/zh/graphics/mesh/primitiveMesh.mdx | 13 +++++++----- e2e/case/primitive-all.ts | 5 ++++- e2e/case/primitive-sections.ts | 8 ++++---- e2e/case/primitive-topology.ts | 14 ++++++++----- .../originImage/Primitive_primitive-all.jpg | 4 ++-- .../Primitive_primitive-sections.jpg | 4 ++-- .../Primitive_primitive-topology.jpg | 4 ++-- e2e/primitive-mesh.md | 2 +- packages/core/src/mesh/PrimitiveMesh.ts | 19 +++++++++++------- .../core/src/mesh/PrimitiveMeshOptions.ts | 4 ++-- packages/core/src/mesh/index.ts | 2 +- .../references/mesh-geometry.md | 2 ++ packages/loader/src/PrimitiveMeshAsset.ts | 8 ++++---- packages/loader/src/PrimitiveMeshLoader.ts | 8 ++++---- .../fixtures/PrimitiveMeshApi.ts | 20 +++++++++++-------- tests/src/core/mesh/ProceduralMesh.test.ts | 14 ++++++------- tests/src/loader/PrimitiveMeshLoader.test.ts | 16 +++++++-------- 18 files changed, 92 insertions(+), 68 deletions(-) diff --git a/docs/en/graphics/mesh/primitiveMesh.mdx b/docs/en/graphics/mesh/primitiveMesh.mdx index af8eeb8027..a19599b16f 100644 --- a/docs/en/graphics/mesh/primitiveMesh.mdx +++ b/docs/en/graphics/mesh/primitiveMesh.mdx @@ -155,13 +155,13 @@ For torus knots, `axisTurns` counts revolutions around the central axis and `cro | Cylinder, frustum, cone, capsule | `createCylinder`, `createTruncatedCone`, `createCone`, `createCapsule` | | Disk, annulus, torus, torus knot | `createCircle`, `createRing`, `createTorus`, `createTorusKnot` | | Regular polyhedra | `createTetrahedron`, `createOctahedron`, `createIcosahedron`, `createDodecahedron` | -| Revolved profile, path tube, polygon, extruded polygon, rounded cuboid | `createLathe`, `createTube`, `createPolygon`, `createExtrudedPolygon`, `createRoundedCuboid` | +| 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; lathes start from +Z towards +X. A sphere's vertical angle starts at +Y. +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"; @@ -182,11 +182,14 @@ Polygon contours use `Vector2` arrays. Pass a point array for a simple polygon. `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. -`createLathe` 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; end caps are not added automatically. Path points for tubes and extrusions use `Vector3` arrays in local coordinates. +`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] }); @@ -232,7 +235,7 @@ The directions below describe increasing UV0 values in local space, assuming pos | 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. | -| Lathe | U spans the revolution from 0 to 1. V advances from 0 to 1 in equal steps per profile point, following input order. | +| 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. | @@ -316,7 +319,7 @@ TypeScript assets use `PrimitiveMeshCapMode` for cylinder and frustum `caps`; JS | `torus` | `torusRadius`, `torusTubeRadius` | | `ring` | `ringOuterRadius`, `ringInnerRadius` | | `tetrahedron`, `octahedron`, `icosahedron`, `dodecahedron` | `Radius` | -| `lathe` | `latheProfile` | +| `revolvedSurface` | `revolvedSurfaceProfile` | | `tube` | `tubePath`, `tubeRadius` | | `polygon` | `polygonShapes` | | `extrudedPolygon` | `extrudedPolygonShapes`, plus `extrudedPolygonDepth` or `extrudedPolygonPath` | diff --git a/docs/zh/graphics/mesh/primitiveMesh.mdx b/docs/zh/graphics/mesh/primitiveMesh.mdx index 0dcf9a0346..34b322c775 100644 --- a/docs/zh/graphics/mesh/primitiveMesh.mdx +++ b/docs/zh/graphics/mesh/primitiveMesh.mdx @@ -159,13 +159,13 @@ const mirroredKnot = PrimitiveMesh.createTorusKnot(engine, 1, 0.1, 2, -3); | 圆柱、圆台、圆锥、胶囊 | `createCylinder`、`createTruncatedCone`、`createCone`、`createCapsule` | | 圆盘、平面圆环、环面、环面结 | `createCircle`、`createRing`、`createTorus`、`createTorusKnot` | | 四面体、八面体、二十面体、十二面体 | `createTetrahedron`、`createOctahedron`、`createIcosahedron`、`createDodecahedron` | -| 旋转体、路径管道、平面多边形、挤出多边形、圆角长方体 | `createLathe`、`createTube`、`createPolygon`、`createExtrudedPolygon`、`createRoundedCuboid` | +| 旋转曲面、路径管道、平面多边形、挤出多边形、圆角长方体 | `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 极点开始。 +角度范围统一放在配置对象中。所有角度均使用**度数**,范围使用 `Vector2`,`x` 表示起始角,`y` 表示结束角。跨越 360 度时使用连续角度,例如 `new Vector2(350, 370)`。圆柱、圆台和圆锥围绕 Y 轴,从 -Z 朝 -X 方向开始;旋转曲面从 +Z 朝 +X 方向开始。球体的垂直角度从 +Y 极点开始。 ```ts import { PrimitiveMeshCapMode, Vector2 } from "@galacean/engine"; @@ -186,11 +186,14 @@ const halfRing = PrimitiveMesh.createRing(engine, 1, 0.5, { angleRange: new Vect `createPolygon` 创建位于 XY 平面、正面朝 +Z 的零厚度表面,不生成侧壁。`createExtrudedPolygon` 为轮廓增加厚度或沿路径挤出,生成侧壁和相应的端盖。 -`createLathe` 将 `Vector2` 截面绕 Y 轴旋转:`x` 表示到 Y 轴的半径,`y` 表示高度,两者均使用局部单位。相邻截面点按输入顺序连接,不会自动添加端盖。管道和挤出的路径点使用局部坐标下的 `Vector3` 数组。 +`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] }); @@ -238,7 +241,7 @@ const closedPath = PrimitiveMesh.createExtrudedPolygon(engine, outline, loop, { | 环面 | 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 沿旋转方向从 0 到 1;V 按轮廓点的输入顺序等步长从 0 到 1。 | | 管道 | U 为归一化的路径距离;V 沿生成截面的周向从 0 到 1。 | | 环面结 | U 沿环面结的曲线参数从 0 到 1;V 沿生成截面的周向从 0 到 1。 | | 平面多边形 | U = 局部 X、V = 局部 Y,不做归一化。 | @@ -322,7 +325,7 @@ TypeScript 资产使用 `PrimitiveMeshCapMode` 表达圆柱和圆台的 `caps` | `torus` | `torusRadius`、`torusTubeRadius` | | `ring` | `ringOuterRadius`、`ringInnerRadius` | | `tetrahedron`、`octahedron`、`icosahedron`、`dodecahedron` | `Radius` | -| `lathe` | `latheProfile` | +| `revolvedSurface` | `revolvedSurfaceProfile` | | `tube` | `tubePath`、`tubeRadius` | | `polygon` | `polygonShapes` | | `extrudedPolygon` | `extrudedPolygonShapes`,以及 `extrudedPolygonDepth` 或 `extrudedPolygonPath` | diff --git a/e2e/case/primitive-all.ts b/e2e/case/primitive-all.ts index caca497d45..b4c0baaf07 100644 --- a/e2e/case/primitive-all.ts +++ b/e2e/case/primitive-all.ts @@ -148,7 +148,10 @@ class PrimitiveMeshGallery { octahedron: { label: "Octahedron", mesh: PrimitiveMesh.createOctahedron(engine, 1) }, icosahedron: { label: "Icosahedron", mesh: PrimitiveMesh.createIcosahedron(engine, 1) }, dodecahedron: { label: "Dodecahedron", mesh: PrimitiveMesh.createDodecahedron(engine, 1) }, - lathe: { label: "Lathe", mesh: PrimitiveMesh.createLathe(engine, profile, { segments: 24 }) }, + 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 }) diff --git a/e2e/case/primitive-sections.ts b/e2e/case/primitive-sections.ts index b2671c52aa..c862bfa016 100644 --- a/e2e/case/primitive-sections.ts +++ b/e2e/case/primitive-sections.ts @@ -83,14 +83,14 @@ class PrimitiveSections { rotation: new Vector3(-25, -28, 0) }, { - label: "Full lathe", + label: "Full revolved surface", detail: "angleRange: [0, 360]", - mesh: PrimitiveMesh.createLathe(engine, profile, { segments: 32 }) + mesh: PrimitiveMesh.createRevolvedSurface(engine, profile, { segments: 32 }) }, { - label: "Partial lathe", + label: "Partial revolved surface", detail: "angleRange: [30, 270]", - mesh: PrimitiveMesh.createLathe(engine, profile, { segments: 32, angleRange: new Vector2(30, 270) }) + mesh: PrimitiveMesh.createRevolvedSurface(engine, profile, { segments: 32, angleRange: new Vector2(30, 270) }) } ], 5 diff --git a/e2e/case/primitive-topology.ts b/e2e/case/primitive-topology.ts index 9b8e76118a..68a788ebf9 100644 --- a/e2e/case/primitive-topology.ts +++ b/e2e/case/primitive-topology.ts @@ -135,12 +135,16 @@ class PrimitiveTopology { rotation: new Vector3() }, { - label: "Lathe / 8 segments", + label: "Revolved surface", detail: "segments: 8", - mesh: PrimitiveMesh.createLathe(engine, [new Vector2(0.4, -1), new Vector2(0.8, 0), new Vector2(0.4, 1)], { - ...keep, - 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", diff --git a/e2e/fixtures/originImage/Primitive_primitive-all.jpg b/e2e/fixtures/originImage/Primitive_primitive-all.jpg index 0db7e8b795..30d83cd03d 100644 --- a/e2e/fixtures/originImage/Primitive_primitive-all.jpg +++ b/e2e/fixtures/originImage/Primitive_primitive-all.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d7ffaf5ec2debdd21f035db54069812ae4dcb14ccd889a80ee754177b3083b07 -size 444193 +oid sha256:c0e23cc74fc32a2a4f0351a438be0f6bb5f76599cbff8310d2dc6f4904a2442b +size 445969 diff --git a/e2e/fixtures/originImage/Primitive_primitive-sections.jpg b/e2e/fixtures/originImage/Primitive_primitive-sections.jpg index b9e53bf708..9ff54b450c 100644 --- a/e2e/fixtures/originImage/Primitive_primitive-sections.jpg +++ b/e2e/fixtures/originImage/Primitive_primitive-sections.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:8f7477bb295eaeb55ae08e7fe22f679a9005ddbae544977d44a79414ff376bb3 -size 639592 +oid sha256:d1d03c70656d8fe30cc0e1d850de9a226a489626be6665b3cbd4de0bea62f3d5 +size 648751 diff --git a/e2e/fixtures/originImage/Primitive_primitive-topology.jpg b/e2e/fixtures/originImage/Primitive_primitive-topology.jpg index e38134e64e..cad8cdd51c 100644 --- a/e2e/fixtures/originImage/Primitive_primitive-topology.jpg +++ b/e2e/fixtures/originImage/Primitive_primitive-topology.jpg @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:968497a7df5b18572acb61d912ead20c443c415631920b6b7e3d334c4fe52319 -size 825397 +oid sha256:c05ec99e093e5e9fa8ea659ae38a25ce26f2afc277224baa044751e862caaff8 +size 824923 diff --git a/e2e/primitive-mesh.md b/e2e/primitive-mesh.md index 47de85af51..64c0e459e5 100644 --- a/e2e/primitive-mesh.md +++ b/e2e/primitive-mesh.md @@ -6,7 +6,7 @@ The suite contains six galleries with 90 examples. Each screenshot fixes the cam | --- | --: | --- | | `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 lathes | +| `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 | diff --git a/packages/core/src/mesh/PrimitiveMesh.ts b/packages/core/src/mesh/PrimitiveMesh.ts index 1e7dd4ebaa..d073ae5396 100644 --- a/packages/core/src/mesh/PrimitiveMesh.ts +++ b/packages/core/src/mesh/PrimitiveMesh.ts @@ -16,7 +16,7 @@ import type { CircleMeshOptions, RingMeshOptions, RegularPolyhedronMeshOptions, - LatheMeshOptions, + RevolvedSurfaceMeshOptions, TubeMeshOptions, PolygonMeshOptions, LinearExtrudedPolygonMeshOptions, @@ -534,21 +534,26 @@ export class PrimitiveMesh { } /** - * Revolve a radius-height profile around Y. + * 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 radius-height profile, with at least two points; X is radius and Y is height + * @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 createLathe(engine: Engine, profile: readonly Vector2[], options?: LatheMeshOptions): ModelMesh { + static createRevolvedSurface( + engine: Engine, + profile: readonly Vector2[], + options?: RevolvedSurfaceMeshOptions + ): ModelMesh { const segments = options?.segments ?? 12; const angleRange = options?.angleRange; const startAngle = angleRange?.x ?? 0; return PrimitiveMesh._createMesh( engine, - PrimitiveMesh._createLatheData, + PrimitiveMesh._createRevolvedSurfaceData, [profile, segments, startAngle, (angleRange?.y ?? 360) - startAngle], options ); @@ -1221,14 +1226,14 @@ export class PrimitiveMesh { return data; } - private static _createLatheData( + private static _createRevolvedSurfaceData( points: readonly Vector2[], segmentCount: number, startAngle: number, arcDegrees: number ): PrimitiveMeshBuilder { if (points.length < 2) { - throw new Error("A lathe profile needs at least two points."); + throw new Error("A revolved surface profile needs at least two points."); } const count = PrimitiveMesh._getSegmentCount(segmentCount); const start = MathUtil.degreeToRadian(startAngle); diff --git a/packages/core/src/mesh/PrimitiveMeshOptions.ts b/packages/core/src/mesh/PrimitiveMeshOptions.ts index ab94b39b2b..1afcda019b 100644 --- a/packages/core/src/mesh/PrimitiveMeshOptions.ts +++ b/packages/core/src/mesh/PrimitiveMeshOptions.ts @@ -290,9 +290,9 @@ export interface RegularPolyhedronMeshOptions extends PrimitiveMeshOptions { } /** - * Settings for revolving a radius-height profile around Y. + * Settings for a surface of revolution generated from a radius-height profile around Y. */ -export interface LatheMeshOptions extends PrimitiveMeshOptions { +export interface RevolvedSurfaceMeshOptions extends PrimitiveMeshOptions { /** * The number of segments along the revolution, rounded down with a minimum of 1. * @defaultValue `12` diff --git a/packages/core/src/mesh/index.ts b/packages/core/src/mesh/index.ts index ebd364f44a..a9163a330f 100644 --- a/packages/core/src/mesh/index.ts +++ b/packages/core/src/mesh/index.ts @@ -17,7 +17,7 @@ export type { CircleMeshOptions, RingMeshOptions, RegularPolyhedronMeshOptions, - LatheMeshOptions, + RevolvedSurfaceMeshOptions, TubeMeshOptions, PolygonMeshOptions, TorusKnotMeshOptions, diff --git a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md index e04c859150..ecf9eb1e4b 100644 --- a/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md +++ b/packages/galacean/skills/engine-knowledge/references/mesh-geometry.md @@ -8,6 +8,8 @@ Reuse a configured mesh when its geometry already meets the task. In Editor-mana 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. +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. + 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. ```ts diff --git a/packages/loader/src/PrimitiveMeshAsset.ts b/packages/loader/src/PrimitiveMeshAsset.ts index 9e537444e5..99711e23b0 100644 --- a/packages/loader/src/PrimitiveMeshAsset.ts +++ b/packages/loader/src/PrimitiveMeshAsset.ts @@ -4,13 +4,13 @@ import type { ConeMeshOptions, CuboidMeshOptions, CylinderMeshOptions, - LatheMeshOptions, LinearExtrudedPolygonMeshOptions, PathExtrudedPolygonMeshOptions, PlaneMeshOptions, PolygonMeshOptions, PolygonShape, RegularPolyhedronMeshOptions, + RevolvedSurfaceMeshOptions, RingMeshOptions, RoundedCuboidMeshOptions, SphereMeshOptions, @@ -192,12 +192,12 @@ export type PrimitiveMeshAsset = dodecahedronOptions?: RegularPolyhedronMeshOptions; } | { - type: "lathe"; + type: "revolvedSurface"; /** * The profile points in local units; x is the radius from the Y axis and y is the height. */ - latheProfile: SerializedPrimitiveMeshData; - latheOptions?: SerializedPrimitiveMeshData; + revolvedSurfaceProfile: SerializedPrimitiveMeshData; + revolvedSurfaceOptions?: SerializedPrimitiveMeshData; } | { type: "tube"; diff --git a/packages/loader/src/PrimitiveMeshLoader.ts b/packages/loader/src/PrimitiveMeshLoader.ts index 718f9e33d3..424857344e 100644 --- a/packages/loader/src/PrimitiveMeshLoader.ts +++ b/packages/loader/src/PrimitiveMeshLoader.ts @@ -84,11 +84,11 @@ class PrimitiveMeshLoader extends Loader { return PrimitiveMesh.createIcosahedron(engine, data.icosahedronRadius, data.icosahedronOptions); case "dodecahedron": return PrimitiveMesh.createDodecahedron(engine, data.dodecahedronRadius, data.dodecahedronOptions); - case "lathe": - return PrimitiveMesh.createLathe( + case "revolvedSurface": + return PrimitiveMesh.createRevolvedSurface( engine, - this._parseVector2s(data.latheProfile), - this._parseRangeOptions(data.latheOptions) + this._parseVector2s(data.revolvedSurfaceProfile), + this._parseRangeOptions(data.revolvedSurfaceOptions) ); case "tube": return PrimitiveMesh.createTube(engine, this._parseVector3s(data.tubePath), data.tubeRadius, data.tubeOptions); diff --git a/tests/package-consumer/fixtures/PrimitiveMeshApi.ts b/tests/package-consumer/fixtures/PrimitiveMeshApi.ts index edb3cf9b02..76ed7b2ed2 100644 --- a/tests/package-consumer/fixtures/PrimitiveMeshApi.ts +++ b/tests/package-consumer/fixtures/PrimitiveMeshApi.ts @@ -5,13 +5,13 @@ import type { ConeMeshOptions, CuboidMeshOptions, CylinderMeshOptions, - LatheMeshOptions, LinearExtrudedPolygonMeshOptions, PathExtrudedPolygonMeshOptions, PlaneMeshOptions, PolygonMeshOptions, PrimitiveMeshOptions, RegularPolyhedronMeshOptions, + RevolvedSurfaceMeshOptions, RingMeshOptions, RoundedCuboidMeshOptions, SphereMeshOptions, @@ -96,7 +96,11 @@ const ringOptions = { keepMeshData: true } satisfies RingMeshOptions; const regularPolyhedronOptions = { edgeSegments: 2, keepMeshData: true } satisfies RegularPolyhedronMeshOptions; -const latheOptions = { segments: 32, angleRange: new Vector2(0, 270), keepMeshData: true } satisfies LatheMeshOptions; +const revolvedSurfaceOptions = { + segments: 32, + angleRange: new Vector2(0, 270), + keepMeshData: true +} satisfies RevolvedSurfaceMeshOptions; const tubeOptions = { pathSegments: 64, radialSegments: 8, @@ -158,8 +162,8 @@ const meshes: ModelMesh[] = [ PrimitiveMesh.createIcosahedron(engine, 1, regularPolyhedronOptions), PrimitiveMesh.createDodecahedron(engine, 0.5), PrimitiveMesh.createDodecahedron(engine, 1, regularPolyhedronOptions), - PrimitiveMesh.createLathe(engine, profile), - PrimitiveMesh.createLathe(engine, profile, latheOptions), + 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), @@ -220,8 +224,8 @@ PrimitiveMesh.createOctahedron(engine); PrimitiveMesh.createIcosahedron(engine); // @ts-expect-error Dodecahedron requires every core shape input PrimitiveMesh.createDodecahedron(engine); -// @ts-expect-error Lathe requires every core shape input -PrimitiveMesh.createLathe(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 @@ -329,8 +333,8 @@ const serializedPath = [ { x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 1 } ]; -// @ts-expect-error Lathe profiles use Vector2 instances -PrimitiveMesh.createLathe(engine, serializedContour); +// @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 diff --git a/tests/src/core/mesh/ProceduralMesh.test.ts b/tests/src/core/mesh/ProceduralMesh.test.ts index b4188e1c46..ae54494374 100644 --- a/tests/src/core/mesh/ProceduralMesh.test.ts +++ b/tests/src/core/mesh/ProceduralMesh.test.ts @@ -94,9 +94,9 @@ const creators: [string, () => ModelMesh][] = [ ["icosahedron", () => PrimitiveMesh.createIcosahedron(engine, 0.5, { keepMeshData: true, edgeSegments: 2 })], ["dodecahedron", () => PrimitiveMesh.createDodecahedron(engine, 0.5, { keepMeshData: true, edgeSegments: 1 })], [ - "lathe", + "revolvedSurface", () => - PrimitiveMesh.createLathe(engine, [new Vector2(0, -1), new Vector2(1, 0), new Vector2(0, 1)], { + PrimitiveMesh.createRevolvedSurface(engine, [new Vector2(0, -1), new Vector2(1, 0), new Vector2(0, 1)], { keepMeshData: true, angleRange: new Vector2(0, 360), segments: 12 @@ -251,9 +251,9 @@ describe("primitive mesh defaults", () => { () => PrimitiveMesh.createDodecahedron(engine, 1, { ...options, edgeSegments: 1 }) ], [ - "lathe", - () => PrimitiveMesh.createLathe(engine, profile, { ...options }), - () => PrimitiveMesh.createLathe(engine, profile, { ...options, segments: 12 }) + "revolvedSurface", + () => PrimitiveMesh.createRevolvedSurface(engine, profile, { ...options }), + () => PrimitiveMesh.createRevolvedSurface(engine, profile, { ...options, segments: 12 }) ], [ "tube", @@ -582,8 +582,8 @@ describe("procedural mesh geometry", () => { [1, 0] ] } - ])("preserves $segments segment(s) in a partial lathe", ({ segments, crossSection }) => { - const mesh = PrimitiveMesh.createLathe(engine, [new Vector2(1, -1), new Vector2(1, 1)], { + ])("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 diff --git a/tests/src/loader/PrimitiveMeshLoader.test.ts b/tests/src/loader/PrimitiveMeshLoader.test.ts index 50ac0b58f8..8a6a254f79 100644 --- a/tests/src/loader/PrimitiveMeshLoader.test.ts +++ b/tests/src/loader/PrimitiveMeshLoader.test.ts @@ -128,9 +128,9 @@ describe("PrimitiveMeshLoader", () => { data: { type: "dodecahedron", dodecahedronRadius: 0.5 }, create: () => PrimitiveMesh.createDodecahedron(engine, 0.5) }, - lathe: { - data: { type: "lathe", latheProfile: profile }, - create: () => PrimitiveMesh.createLathe(engine, profileVectors) + revolvedSurface: { + data: { type: "revolvedSurface", revolvedSurfaceProfile: profile }, + create: () => PrimitiveMesh.createRevolvedSurface(engine, profileVectors) }, tube: { data: { type: "tube", tubeRadius: 0.5, tubePath: path }, @@ -400,14 +400,14 @@ describe("PrimitiveMeshLoader", () => { create: () => PrimitiveMesh.createDodecahedron(engine, 1.5, { ...options, edgeSegments: 2 }) }, { - name: "lathe profile and range", + name: "revolved surface profile and range", data: { - type: "lathe", - latheProfile: profile, - latheOptions: { ...options, angleRange: { x: 30, y: 270 }, segments: 16 } + type: "revolvedSurface", + revolvedSurfaceProfile: profile, + revolvedSurfaceOptions: { ...options, angleRange: { x: 30, y: 270 }, segments: 16 } }, create: () => - PrimitiveMesh.createLathe(engine, profileVectors, { + PrimitiveMesh.createRevolvedSurface(engine, profileVectors, { ...options, angleRange: new Vector2(30, 270), segments: 16