diff --git a/EngineErrorMap.md b/EngineErrorMap.md index 4b0e8df27b..7d755dcadf 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -3234,3 +3234,11 @@ The primitiveIndex is out of range. ### 14300 Can not keep world transform due to the zero scaling of parent node + +### 14400 + +Spline error: less than 2 knots. + +### 14401 + +Spline error: less than 4 knots or not a multiple of 4. diff --git a/cc.config.json b/cc.config.json index a21678aef1..9f469ddc3b 100644 --- a/cc.config.json +++ b/cc.config.json @@ -21,6 +21,7 @@ "intersection-2d": { "modules": [ "intersection-2d" ] }, "primitive": { "modules": [ "primitive" ] }, "profiler": { "modules": [ "profiler" ] }, + "geometry-renderer": { "modules": [ "geometry-renderer" ] }, "audio": { "modules": [ "audio" ] }, "video": { "modules": [ "video" ] }, "terrain": { "modules": [ "terrain" ] }, diff --git a/cocos/core/geometry/enums.ts b/cocos/core/geometry/enums.ts index e954a0e541..de211f3cc8 100644 --- a/cocos/core/geometry/enums.ts +++ b/cocos/core/geometry/enums.ts @@ -45,4 +45,5 @@ export default { SHAPE_FRUSTUM: (1 << 7), SHAPE_FRUSTUM_ACCURATE: (1 << 8), SHAPE_CAPSULE: (1 << 9), + SHAPE_SPLINE: (1 << 10), }; diff --git a/cocos/core/geometry/index.ts b/cocos/core/geometry/index.ts index 9a52a0b768..122b83af58 100644 --- a/cocos/core/geometry/index.ts +++ b/cocos/core/geometry/index.ts @@ -45,5 +45,6 @@ export { OBB } from './obb'; export { Capsule } from './capsule'; export { Frustum } from './frustum'; export { Keyframe, AnimationCurve } from './curve'; +export { SplineMode, Spline } from './spline'; export * from './spec'; export * from './deprecated-3.0.0'; diff --git a/cocos/core/geometry/spline.ts b/cocos/core/geometry/spline.ts new file mode 100644 index 0000000000..6a3e2985f7 --- /dev/null +++ b/cocos/core/geometry/spline.ts @@ -0,0 +1,291 @@ +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. + */ + +/** + * @packageDocumentation + * @module geometry + */ + +import { assertIsTrue } from '../data/utils/asserts'; +import { clamp, Vec3 } from '../math'; +import { warnID } from '../platform/debug'; +import enums from './enums'; + +export enum SplineMode { + /** + * Broken line: + * Each knot is connected with a straight line from the beginning to the end to form a curve. At least two knots. + */ + LINEAR = 0, + + /** + * Piecewise Bezier curve: + * Every four knots form a curve. Total knots number must be a multiple of 4. + * Each curve passes only the first and fourth knots, and does not pass through the middle two control knots. + * + * If you need a whole continuous curve: + * (1) Suppose the four knots of the previous curve are A, B, C, D + * (2) The four knots of the next curve must be D, E, F, G + * (3) C and E need to be symmetrical about D + */ + BEZIER = 1, + + /** + * Catmull Rom curve: + * All knots(including start & end knots) form a whole continuous curve. At least two knots. + * The whole curve passes through all knots. + */ + CATMULL_ROM = 2 +}; + +const SPLINE_WHOLE_INDEX = 0xffffffff; + +const _v0 = new Vec3(); +const _v1 = new Vec3(); +const _v2 = new Vec3(); +const _v3 = new Vec3(); + +/** + * @en + * Basic Geometry: Spline. + * @zh + * 基础几何 Spline + */ + +export class Spline { + private readonly _type: number; + private _mode: SplineMode = SplineMode.CATMULL_ROM; + private _knots: Vec3[] = []; + + private constructor(mode: SplineMode = SplineMode.CATMULL_ROM, knots: Readonly = []) { + this._type = enums.SHAPE_SPLINE; + this._mode = mode; + + for (let i = 0; i < knots.length; i++) { + this._knots[i] = new Vec3(knots[i]); + } + } + + public static create (mode: SplineMode, knots: Vec3[] = []) { + return new Spline(mode, knots); + } + + public static clone (s: Spline) { + return new Spline(s.mode, s.knots); + } + + public static copy (out: Spline, s: Spline) { + out._mode = s.mode; + out._knots.length = 0; + + const knots = s.knots; + const length = knots.length; + for (let i = 0; i < length; i++) { + out._knots[i] = new Vec3(knots[i]); + } + + return out; + } + + get type () { + return this._type; + } + + get mode () { + return this._mode; + } + + get knots (): Readonly { + return this._knots; + } + + public setModeAndKnots (mode: SplineMode, knots: Vec3[]) { + this._mode = mode; + this._knots.length = 0; + + for (let i = 0; i < knots.length; i++) { + this._knots[i] = new Vec3(knots[i]); + } + } + + public clearKnots() { + this._knots.length = 0; + } + + public getKnotCount() { + return this._knots.length; + } + + public addKnot(knot: Vec3) { + this._knots.push(new Vec3(knot)); + } + + public insertKnot(index: number, knot: Vec3) { + const item = new Vec3(knot); + if (index >= this._knots.length) { + this._knots.push(item); + return; + } + + this._knots.splice(index, 0, item); + } + + public removeKnot(index: number) { + assertIsTrue(index >= 0 && index < this._knots.length, "Spline: invalid index"); + + this._knots.splice(index, 1); + } + + public setKnot(index: number, knot: Vec3) { + assertIsTrue(index >= 0 && index < this._knots.length, "Spline: invalid index"); + + this._knots[index].set(knot); + } + + public getKnot(index: number): Readonly { + assertIsTrue(index >= 0 && index < this._knots.length, "Spline: invalid index"); + + return this._knots[index]; + } + + // get a point at t with repect to the `index` segment of curve or the whole curve. + public getPoint(t: number, index: number = SPLINE_WHOLE_INDEX) { + t = clamp(t, 0.0, 1.0); + + const segments = this.getSegments(); + if (segments == 0) { + return new Vec3(0.0, 0.0, 0.0); + } + + if (index == SPLINE_WHOLE_INDEX) { + const deltaT = 1.0 / segments; + + index = Math.floor(t / deltaT); + t = (t % deltaT) / deltaT; + } + + if (index >= segments) { + return new Vec3(this._knots[this._knots.length - 1]); + } + + switch (this._mode) { + case SplineMode.LINEAR: + return Spline.calcLinear(this._knots[index], this._knots[index + 1], t); + case SplineMode.BEZIER: + return Spline.calcBezier(this._knots[index * 4], this._knots[index * 4 + 1], this._knots[index * 4 + 2], this._knots[index * 4 + 3], t); + case SplineMode.CATMULL_ROM: { + const v0 = index > 0 ? this._knots[index - 1] : this._knots[index]; + const v3 = index + 2 < this._knots.length ? this._knots[index + 2] : this._knots[index + 1]; + return Spline.calcCatmullRom(v0, this._knots[index], this._knots[index + 1], v3, t); + } + default: + return new Vec3(0.0, 0.0, 0.0); + } + } + + // get num points from 0 to 1 uniformly with repect to the `index` segment of curve or the whole curve + public getPoints(num: number, index: number = SPLINE_WHOLE_INDEX): Vec3[] { + if (num == 0) { + return []; + } + + if (num == 1) { + const point = this.getPoint(0.0, index); + return [point]; + } + + let points: Vec3[] = []; + const deltaT = 1.0 / (num - 1.0); + + for (let i = 0; i < num; i++) { + const t = i * deltaT; + const point = this.getPoint(t, index); + + points.push(point); + } + + return points; + } + + private getSegments() { + const count = this._knots.length; + switch (this._mode) { + case SplineMode.LINEAR: + case SplineMode.CATMULL_ROM: + if (count < 2) { + warnID(14300); + return 0; + } + + return count - 1; + case SplineMode.BEZIER: + if (count < 4 || count % 4 != 0) { + warnID(14301); + return 0; + } + + return count / 4; + default: + assertIsTrue(false, "Spline error: invalid mode"); + } + } + + private static calcLinear(v0: Vec3, v1: Vec3, t: number) { + const result = new Vec3(); + Vec3.multiplyScalar(_v0, v0, (1.0 - t)); + Vec3.multiplyScalar(_v1, v1, t); + Vec3.add(result, _v0, _v1); + + return result; + } + + private static calcBezier(v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3, t: number) { + const result = new Vec3(); + const s = 1.0 - t; + Vec3.multiplyScalar(_v0, v0, s * s * s); + Vec3.multiplyScalar(_v1, v1, 3.0 * t * s * s); + Vec3.multiplyScalar(_v2, v2, 3.0 * t * t * s); + Vec3.multiplyScalar(_v3, v3, t * t * t); + Vec3.add(_v0, _v0, _v1); + Vec3.add(_v2, _v2, _v3); + Vec3.add(result, _v0, _v2); + + return result; + } + private static calcCatmullRom(v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3, t: number) { + const result = new Vec3(); + const t2 = t * t; + const t3 = t2 * t; + Vec3.multiplyScalar(_v0, v0, -0.5 * t3 + t2 - 0.5 * t); + Vec3.multiplyScalar(_v1, v1, 1.5 * t3 - 2.5 * t2 + 1.0); + Vec3.multiplyScalar(_v2, v2, -1.5 * t3 + 2.0 * t2 + 0.5 * t); + Vec3.multiplyScalar(_v3, v3, 0.5 * t3 - 0.5 * t2); + Vec3.add(_v0, _v0, _v1); + Vec3.add(_v2, _v2, _v3); + Vec3.add(result, _v0, _v2); + + return result; + } +} diff --git a/cocos/core/pipeline/deferred/lighting-stage.ts b/cocos/core/pipeline/deferred/lighting-stage.ts index a2cd0bbad2..444f09c8db 100644 --- a/cocos/core/pipeline/deferred/lighting-stage.ts +++ b/cocos/core/pipeline/deferred/lighting-stage.ts @@ -314,7 +314,7 @@ export class LightingStage extends RenderStage { // planarQueue this._planarQueue.recordCommandBuffer(device, renderPass, cmdBuff); } - camera.geometryRenderer.render(renderPass, cmdBuff, pipeline.pipelineSceneData); + camera.geometryRenderer?.render(renderPass, cmdBuff, pipeline.pipelineSceneData); this._uiPhase.render(camera, renderPass); cmdBuff.endRenderPass(); } diff --git a/cocos/core/pipeline/forward/forward-stage.ts b/cocos/core/pipeline/forward/forward-stage.ts index 54c08305d4..21378e038d 100644 --- a/cocos/core/pipeline/forward/forward-stage.ts +++ b/cocos/core/pipeline/forward/forward-stage.ts @@ -185,7 +185,7 @@ export class ForwardStage extends RenderStage { cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet); this._planarQueue.recordCommandBuffer(device, renderPass, cmdBuff); this._renderQueues[1].recordCommandBuffer(device, renderPass, cmdBuff); - camera.geometryRenderer.render(renderPass, cmdBuff, pipeline.pipelineSceneData); + camera.geometryRenderer?.render(renderPass, cmdBuff, pipeline.pipelineSceneData); this._uiPhase.render(camera, renderPass); renderProfiler(device, renderPass, cmdBuff, pipeline.profiler, camera); cmdBuff.endRenderPass(); diff --git a/cocos/core/pipeline/geometry-renderer.ts b/cocos/core/pipeline/geometry-renderer.ts index 0f3b099e78..44ea534abd 100644 --- a/cocos/core/pipeline/geometry-renderer.ts +++ b/cocos/core/pipeline/geometry-renderer.ts @@ -23,7 +23,12 @@ THE SOFTWARE. */ + /** + * @packageDocumentation + * @module geometry-renderer + */ import { AABB } from '../geometry/aabb'; +import { Spline } from '../geometry/spline'; import { Color } from '../math/color'; import { Mat4 } from '../math/mat4'; import { Vec3 } from '../math/vec3'; @@ -36,8 +41,8 @@ import { Attribute, AttributeName, Buffer, BufferInfo, BufferUsageBit, import { warnID } from '../platform/debug'; import { Frustum } from '../geometry/frustum'; import { toRadian } from '../math/utils'; -import { Camera } from '../renderer/scene/camera'; import { PipelineSceneData } from './pipeline-scene-data'; +import { legacyCC } from '../global-exports'; const _min = new Vec3(); const _max = new Vec3(); @@ -897,6 +902,25 @@ export class GeometryRenderer { } } + public addSpline (spline: Spline, color: Color, index = 0xffffffff, knotSize = 0.5, segments = 32, depthTest = true) { + const numPoints = segments + 1; + const points = spline.getPoints(numPoints, index); + + for (let i = 0; i < segments; i++) { + this.addLine(points[i], points[i + 1], color, depthTest); + } + + if (knotSize > 0.0 && index == 0xffffffff) { + const crossColor = new Color(255 - color.r, 255 - color.g, 255 - color.b, color.a); + const numKnots = spline.getKnotCount(); + const knots = spline.knots; + + for (let i = 0; i < numKnots; i++) { + this.addCross(knots[i], knotSize, crossColor, depthTest); + } + } + } + public addMesh (center: Vec3, vertices: Array, color: Color, depthTest = true, useTransform = false, transform = new Mat4()) { for (let i = 0; i < vertices.length; i += 3) { const v0 = new Vec3(center.x + vertices[i].x, center.y + vertices[i].y, center.z + vertices[i].z); @@ -934,3 +958,5 @@ export class GeometryRenderer { } } } + +legacyCC.internal.GeometryRenderer = GeometryRenderer; diff --git a/cocos/core/renderer/scene/camera.ts b/cocos/core/renderer/scene/camera.ts index 9464908e24..751ccd31c6 100644 --- a/cocos/core/renderer/scene/camera.ts +++ b/cocos/core/renderer/scene/camera.ts @@ -164,7 +164,7 @@ export class Camera { private _visibility = CAMERA_DEFAULT_MASK; private _exposure = 0; private _clearStencil = 0; - private _geometryRenderer = new GeometryRenderer(); + private _geometryRenderer = legacyCC.internal.GeometryRenderer ? new GeometryRenderer() : null; constructor (device: Device) { this._device = device; @@ -174,7 +174,7 @@ export class Camera { this._aspect = this.screenScale = 1; this._frustum.accurate = true; - this._geometryRenderer.activate(device); + this._geometryRenderer?.activate(device); if (!correctionMatrices.length) { const ySign = device.capabilities.clipSpaceSignY; @@ -231,7 +231,7 @@ export class Camera { this.window = null!; } this._name = null; - this._geometryRenderer.destroy(); + this._geometryRenderer?.destroy(); } public attachToScene (scene: RenderScene) { diff --git a/editor/engine-features/render-config.json b/editor/engine-features/render-config.json index a52630021d..ebea6a852b 100644 --- a/editor/engine-features/render-config.json +++ b/editor/engine-features/render-config.json @@ -128,6 +128,12 @@ "description": "i18n:ENGINE.features.profiler.description", "wechatPlugin": true }, + "geometry-renderer": { + "default": ["geometry-renderer"], + "label": "i18n:ENGINE.features.geometry_renderer.label", + "description": "i18n:ENGINE.features.geometry_renderer.description", + "wechatPlugin": true + }, "particle-2d": { "default": ["particle-2d"], "label": "i18n:ENGINE.features.particle_2d.label", diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index bf6a46739d..18d408d2af 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -874,6 +874,10 @@ module.exports = { label: "Running Stats", description: "Include various components and tools used to audit and display rendering stats.", }, + geometry_renderer: { + label: "Geometry Renderer", + description: "Used to render various geometries for debugging or use in editor.", + }, tiled_map: { label: "Tiled Map", description: "Tiled map support.", diff --git a/exports/geometry-renderer.ts b/exports/geometry-renderer.ts new file mode 100644 index 0000000000..c98c14b08c --- /dev/null +++ b/exports/geometry-renderer.ts @@ -0,0 +1 @@ +export * from '../cocos/core/pipeline/geometry-renderer'; diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 0870254909..6bce6d1bd7 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -1962,6 +1962,8 @@ cocos_source_files(MODULE ccgeometry cocos/core/geometry/Spec.h cocos/core/geometry/Sphere.cpp cocos/core/geometry/Sphere.h + cocos/core/geometry/Spline.cpp + cocos/core/geometry/Spline.h cocos/core/geometry/Triangle.cpp cocos/core/geometry/Triangle.h ) diff --git a/native/cocos/base/memory/CallStack.h b/native/cocos/base/memory/CallStack.h index 8291e95c44..1c1276b969 100644 --- a/native/cocos/base/memory/CallStack.h +++ b/native/cocos/base/memory/CallStack.h @@ -34,6 +34,7 @@ #include #include "../Macros.h" #include "base/std/container/string.h" + #include "base/std/container/vector.h" namespace cc { diff --git a/native/cocos/base/memory/MemoryHook.cpp b/native/cocos/base/memory/MemoryHook.cpp index fc88cd0631..840e0cca41 100644 --- a/native/cocos/base/memory/MemoryHook.cpp +++ b/native/cocos/base/memory/MemoryHook.cpp @@ -24,6 +24,7 @@ ****************************************************************************/ #include "MemoryHook.h" +#include "CallStack.h" #if USE_MEMORY_LEAK_DETECTOR #include diff --git a/native/cocos/base/memory/MemoryHook.h b/native/cocos/base/memory/MemoryHook.h index 94981bcd1f..7be9a2da3c 100644 --- a/native/cocos/base/memory/MemoryHook.h +++ b/native/cocos/base/memory/MemoryHook.h @@ -28,11 +28,11 @@ #include "../Config.h" #if USE_MEMORY_LEAK_DETECTOR - #include "../Macros.h" - #include "CallStack.h" - #include "base/std/container/unordered_map.h" - #include + #include "../Macros.h" + #include "base/std/container/string.h" + #include "base/std/container/unordered_map.h" + #include "base/std/container/vector.h" typedef void *(*MallocType)(size_t size); typedef void (*FreeType)(void *ptr); diff --git a/native/cocos/bindings/manual/jsb_conversions_spec.cpp b/native/cocos/bindings/manual/jsb_conversions_spec.cpp index f43081cfe6..f951363255 100644 --- a/native/cocos/bindings/manual/jsb_conversions_spec.cpp +++ b/native/cocos/bindings/manual/jsb_conversions_spec.cpp @@ -724,6 +724,16 @@ bool sevalue_to_native(const se::Value &from, cc::geometry::Frustum *to, se::Obj return true; } +// NOLINTNEXTLINE(readability-identifier-naming) +bool sevalue_to_native(const se::Value &from, cc::geometry::Spline *to, se::Object * /*unused*/) { + SE_PRECONDITION2(from.isObject(), false, "Convert parameter to Spline failed!"); + se::Object *obj = from.toObject(); + se::Value tmp; + set_member_field(obj, to, "_mode", &cc::geometry::Spline::setMode, tmp); + set_member_field>(obj, to, "_knots", &cc::geometry::Spline::setKnots, tmp); + return true; +} + ////////////////////////// scene info // NOLINTNEXTLINE(readability-identifier-naming) diff --git a/native/cocos/bindings/manual/jsb_conversions_spec.h b/native/cocos/bindings/manual/jsb_conversions_spec.h index 7de216076c..cdf9b78f38 100644 --- a/native/cocos/bindings/manual/jsb_conversions_spec.h +++ b/native/cocos/bindings/manual/jsb_conversions_spec.h @@ -79,6 +79,7 @@ class Sphere; class Triangle; class Plane; class Frustum; +class Spline; } // namespace geometry namespace extension { @@ -357,6 +358,7 @@ bool sevalue_to_native(const se::Value &from, cc::geometry::Triangle *, se::Obje bool sevalue_to_native(const se::Value &from, cc::geometry::Plane *to, se::Object * /*unused*/); // NOLINT(readability-identifier-naming) bool sevalue_to_native(const se::Value &from, cc::geometry::Plane **to, se::Object * /*unused*/); // NOLINT(readability-identifier-naming) bool sevalue_to_native(const se::Value &from, cc::geometry::Frustum *to, se::Object * /*unused*/); // NOLINT(readability-identifier-naming) +bool sevalue_to_native(const se::Value &from, cc::geometry::Spline *to, se::Object * /*unused*/); // NOLINT(readability-identifier-naming) //////////////////////////////////////////////////////////////////////////// ////////////////////nativevalue to se ///////////////////////////////////// diff --git a/native/cocos/core/geometry/Enums.h b/native/cocos/core/geometry/Enums.h index 251c1739e7..2bdfa4db4b 100644 --- a/native/cocos/core/geometry/Enums.h +++ b/native/cocos/core/geometry/Enums.h @@ -17,7 +17,8 @@ enum class ShapeEnum { SHAPE_FRUSTUM = (1 << 7), SHAPE_FRUSTUM_ACCURATE = (1 << 8), SHAPE_CAPSULE = (1 << 9), - SHAPE_BAD = (1 << 10), + SHAPE_SPLINE = (1 << 10), + SHAPE_BAD = (1 << 11), }; class ShapeBase : public RefCounted { diff --git a/native/cocos/core/geometry/Geometry.h b/native/cocos/core/geometry/Geometry.h index c75641fdf6..cc7203183c 100644 --- a/native/cocos/core/geometry/Geometry.h +++ b/native/cocos/core/geometry/Geometry.h @@ -14,3 +14,4 @@ #include "Spec.h" #include "Sphere.h" #include "Triangle.h" +#include "Spline.h" diff --git a/native/cocos/core/geometry/Spline.cpp b/native/cocos/core/geometry/Spline.cpp new file mode 100644 index 0000000000..8de9280d91 --- /dev/null +++ b/native/cocos/core/geometry/Spline.cpp @@ -0,0 +1,201 @@ +/**************************************************************************** + Copyright (c) 2021-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. + ****************************************************************************/ + +#include "core/geometry/Spline.h" +#include +#include "base/Log.h" +#include "base/Macros.h" +#include "math/Utils.h" + +namespace cc { +namespace geometry { + +Spline::Spline(SplineMode mode /*= SplineMode::CATMULL_ROM*/, ccstd::vector knots /*= {}*/) +: _mode(mode), _knots(std::move(knots)) { + setType(ShapeEnum::SHAPE_SPLINE); +} + +Spline *Spline::create(SplineMode mode, const ccstd::vector &knots /*= {}*/) { + return new Spline(mode, knots); +} + +Spline *Spline::clone(const Spline &s) { + return new Spline(s._mode, s._knots); +} + +Spline *Spline::copy(Spline *out, const Spline &s) { + out->_mode = s._mode; + out->_knots = s._knots; + + return out; +} + +void Spline::setModeAndKnots(SplineMode mode, const ccstd::vector &knots) { + _mode = mode; + _knots = knots; +} + +void Spline::insertKnot(uint32_t index, const Vec3 &knot) { + if (index >= static_cast(_knots.size())) { + _knots.push_back(knot); + return; + } + + _knots.insert(_knots.begin() + index, knot); +} + +void Spline::removeKnot(uint32_t index) { + CC_ASSERT(index < static_cast(_knots.size())); + + _knots.erase(_knots.begin() + index); +} + +void Spline::setKnot(uint32_t index, const Vec3 &knot) { + CC_ASSERT(index < static_cast(_knots.size())); + + _knots[index] = knot; +} + +const Vec3 &Spline::getKnot(uint32_t index) const { + CC_ASSERT(index < static_cast(_knots.size())); + + return _knots[index]; +} +Vec3 &Spline::getKnot(uint32_t index) { + CC_ASSERT(index < static_cast(_knots.size())); + + return _knots[index]; +} + +Vec3 Spline::getPoint(float t, uint32_t index /*= SPLINE_WHOLE_INDEX*/) const { + t = mathutils::clamp(t, 0.0F, 1.0F); + + const auto segments = getSegments(); + if (segments == 0) { + return Vec3(0.0F, 0.0F, 0.0F); + } + + if (index == SPLINE_WHOLE_INDEX) { + const auto deltaT = 1.0F / static_cast(segments); + + index = static_cast(t / deltaT); + t = std::fmod(t, deltaT) / deltaT; + } + + if (index >= segments) { + return _knots.back(); + } + + switch (_mode) { + case SplineMode::LINEAR: + return calcLinear(_knots[index], _knots[index + 1], t); + case SplineMode::BEZIER: + return calcBezier(_knots[index * 4], _knots[index * 4 + 1], _knots[index * 4 + 2], _knots[index * 4 + 3], t); + case SplineMode::CATMULL_ROM: { + const auto v0 = index > 0 ? _knots[index - 1] : _knots[index]; + const auto v3 = index + 2 < static_cast(_knots.size()) ? _knots[index + 2] : _knots[index + 1]; + return calcCatmullRom(v0, _knots[index], _knots[index + 1], v3, t); + } + default: + return Vec3(0.0F, 0.0F, 0.0F); + } +} + +ccstd::vector Spline::getPoints(uint32_t num, uint32_t index /*= SPLINE_WHOLE_INDEX*/) const { + if (num == 0U) { + return {}; + } + + if (num == 1U) { + auto point = getPoint(0.0F, index); + return {point}; + } + + ccstd::vector points; + const float deltaT = 1.0F / (static_cast(num) - 1.0F); + + for (auto i = 0; i < num; i++) { + const auto t = static_cast(i) * deltaT; + const auto point = getPoint(t, index); + + points.push_back(point); + } + + return points; +} + +uint32_t Spline::getSegments() const { + const auto count = static_cast(_knots.size()); + switch (_mode) { + case SplineMode::LINEAR: + case SplineMode::CATMULL_ROM: + if (count < 2) { + CC_LOG_WARNING("Spline error: less than 2 knots."); + return 0; + } + + return count - 1; + case SplineMode::BEZIER: + if (count < 4 || count % 4 != 0) { + CC_LOG_WARNING("Spline error: less than 4 knots or not a multiple of 4."); + return 0; + } + + return count / 4; + default: + CC_ASSERT(false); + return 0; + } +} + +Vec3 Spline::calcLinear(const Vec3 &v0, const Vec3 &v1, float t) { + const auto result = v0 * (1.0F - t) + v1 * t; + + return result; +} + +Vec3 Spline::calcBezier(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, const Vec3 &v3, float t) { + const auto s = 1.0F - t; + const auto result = v0 * s * s * s + + v1 * 3.0F * t * s * s + + v2 * 3.0F * t * t * s + + v3 * t * t * t; + + return result; +} + +Vec3 Spline::calcCatmullRom(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, const Vec3 &v3, float t) { + const auto t2 = t * t; + const auto t3 = t2 * t; + const auto result = v0 * (-0.5F * t3 + t2 - 0.5F * t) + + v1 * (1.5F * t3 - 2.5F * t2 + 1.0F) + + v2 * (-1.5F * t3 + 2.0F * t2 + 0.5F * t) + + v3 * (0.5F * t3 - 0.5F * t2); + + return result; +} + +} // namespace geometry +} // namespace cc diff --git a/native/cocos/core/geometry/Spline.h b/native/cocos/core/geometry/Spline.h new file mode 100644 index 0000000000..435068af34 --- /dev/null +++ b/native/cocos/core/geometry/Spline.h @@ -0,0 +1,116 @@ +/**************************************************************************** + Copyright (c) 2021-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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. + ****************************************************************************/ + +#pragma once + +#include "base/std/container/vector.h" +#include "core/geometry/Enums.h" +#include "math/Vec3.h" + +namespace cc { +namespace geometry { + +enum class SplineMode { + /** + * Broken line: + * Each knot is connected with a straight line from the beginning to the end to form a curve. At least two knots. + */ + LINEAR = 0, + + /** + * Piecewise Bezier curve: + * Every four knots form a curve. Total knots number must be a multiple of 4. + * Each curve passes only the first and fourth knots, and does not pass through the middle two control knots. + * + * If you need a whole continuous curve: + * (1) Suppose the four knots of the previous curve are A, B, C, D + * (2) The four knots of the next curve must be D, E, F, G + * (3) C and E need to be symmetrical about D + */ + BEZIER = 1, + + /** + * Catmull Rom curve: + * All knots(including start & end knots) form a whole continuous curve. At least two knots. + * The whole curve passes through all knots. + */ + CATMULL_ROM = 2 +}; + +constexpr uint32_t SPLINE_WHOLE_INDEX = 0xffffffff; + +/** + * @en + * Basic Geometry: Spline. + * @zh + * 基础几何 Spline。 + */ + +class Spline final : public ShapeBase { +public: + explicit Spline(SplineMode mode = SplineMode::CATMULL_ROM, ccstd::vector knots = {}); + + Spline(const Spline &) = default; + Spline(Spline &&) = default; + ~Spline() override = default; + Spline &operator=(const Spline &) = default; + Spline &operator=(Spline &&) = default; + + static Spline *create(SplineMode mode, const ccstd::vector &knots = {}); + static Spline *clone(const Spline &s); + static Spline *copy(Spline *out, const Spline &s); + + inline void setMode(SplineMode mode) { _mode = mode; } + inline SplineMode getMode() const { return _mode; } + inline void setKnots(const ccstd::vector &knots) { _knots = knots; } + inline const ccstd::vector &getKnots() const { return _knots; } + inline void clearKnots() { _knots.clear(); } + inline uint32_t getKnotCount() const { return static_cast(_knots.size()); } + inline void addKnot(const Vec3 &knot) { _knots.push_back(knot); } + void setModeAndKnots(SplineMode mode, const ccstd::vector &knots); + void insertKnot(uint32_t index, const Vec3 &knot); + void removeKnot(uint32_t index); + void setKnot(uint32_t index, const Vec3 &knot); + const Vec3 & getKnot(uint32_t index) const; + Vec3 & getKnot(uint32_t index); + + // get a point at t with repect to the `index` segment of curve or the whole curve. + Vec3 getPoint(float t, uint32_t index = SPLINE_WHOLE_INDEX) const; + + // get num points from 0 to 1 uniformly with repect to the `index` segment of curve or the whole curve + ccstd::vector getPoints(uint32_t num, uint32_t index = SPLINE_WHOLE_INDEX) const; + +private: + uint32_t getSegments() const; + static Vec3 calcLinear(const Vec3 &v0, const Vec3 &v1, float t); + static Vec3 calcBezier(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, const Vec3 &v3, float t); + static Vec3 calcCatmullRom(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, const Vec3 &v3, float t); + + SplineMode _mode{SplineMode::CATMULL_ROM}; + ccstd::vector _knots; // control points of the curve. +}; + +} // namespace geometry +} // namespace cc diff --git a/native/cocos/renderer/pipeline/GeometryRenderer.cpp b/native/cocos/renderer/pipeline/GeometryRenderer.cpp index d291d298b9..8e735e8373 100644 --- a/native/cocos/renderer/pipeline/GeometryRenderer.cpp +++ b/native/cocos/renderer/pipeline/GeometryRenderer.cpp @@ -34,6 +34,7 @@ #include "base/std/container/array.h" #include "core/geometry/AABB.h" #include "core/geometry/Frustum.h" +#include "core/geometry/Spline.h" #include "math/Mat4.h" #include "math/Math.h" #include "profiler/Profiler.h" @@ -810,6 +811,25 @@ void GeometryRenderer::addBezier(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, } } +void GeometryRenderer::addSpline(const geometry::Spline &spline, gfx::Color color, uint32_t index, float knotSize, uint32_t segments, bool depthTest) { + const auto numPoints = segments + 1; + auto points = spline.getPoints(numPoints, index); + + for (auto i = 0U; i < segments; i++) { + addLine(points[i], points[i + 1], color, depthTest); + } + + if (knotSize > 0.0F && index == geometry::SPLINE_WHOLE_INDEX) { + const gfx::Color crossColor{1.0F - color.x, 1.0F - color.y, 1.0F - color.z, color.w}; + const auto numKnots = spline.getKnotCount(); + const auto & knots = spline.getKnots(); + + for (auto i = 0U; i < numKnots; i++) { + addCross(knots[i], knotSize, crossColor, depthTest); + } + } +} + void GeometryRenderer::addMesh(const Vec3 ¢er, const ccstd::vector &vertices, gfx::Color color, bool depthTest, bool useTransform, const Mat4 &transform) { for (auto i = 0U; i < vertices.size(); i += 3) { Vec3 v0 = center + vertices[i]; diff --git a/native/cocos/renderer/pipeline/GeometryRenderer.h b/native/cocos/renderer/pipeline/GeometryRenderer.h index beecd78d4a..a341de20ff 100644 --- a/native/cocos/renderer/pipeline/GeometryRenderer.h +++ b/native/cocos/renderer/pipeline/GeometryRenderer.h @@ -44,6 +44,7 @@ class CommandBuffer; namespace geometry { class AABB; class Frustum; +class Spline; } // namespace geometry namespace scene { @@ -94,6 +95,7 @@ public: void addTorus(const Vec3 ¢er, float bigRadius, float radius, gfx::Color color, uint32_t segmentsU = 32U, uint32_t segmentsV = 32U, bool wireframe = true, bool depthTest = true, bool unlit = false, bool useTransform = false, const Mat4 &transform = Mat4()); void addOctahedron(const Vec3 ¢er, float radius, gfx::Color color, bool wireframe = true, bool depthTest = true, bool unlit = false, bool useTransform = false, const Mat4 &transform = Mat4()); void addBezier(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, const Vec3 &v3, gfx::Color color, uint32_t segments = 32U, bool depthTest = true, bool useTransform = false, const Mat4 &transform = Mat4()); + void addSpline(const geometry::Spline &spline, gfx::Color color, uint32_t index = 0xffffffff, float knotSize = 0.5F, uint32_t segments = 32U, bool depthTest = true); void addMesh(const Vec3 ¢er, const ccstd::vector &vertices, gfx::Color color, bool depthTest = true, bool useTransform = false, const Mat4 &transform = Mat4()); void addIndexedMesh(const Vec3 ¢er, const ccstd::vector &vertices, const ccstd::vector &indices, gfx::Color color, bool depthTest = true, bool useTransform = false, const Mat4 &transform = Mat4()); diff --git a/native/cocos/scene/Octree.cpp b/native/cocos/scene/Octree.cpp index e8418d5500..7efa14e433 100644 --- a/native/cocos/scene/Octree.cpp +++ b/native/cocos/scene/Octree.cpp @@ -367,8 +367,7 @@ void Octree::insert(Model *model) { return; } - bool inside = isInside(model); - if (!inside) { + if (isOutside(model)) { CC_LOG_WARNING("Octree insert: model is outside of the scene bounding box, please modify DEFAULT_WORLD_MIN_POS and DEFAULT_WORLD_MAX_POS."); return; } @@ -410,5 +409,12 @@ bool Octree::isInside(Model *model) const { return rootBox.contain(modelBox); } +bool Octree::isOutside(Model *model) const { + const BBox &rootBox = _root->getBox(); + BBox modelBox = BBox(*model->getWorldBounds()); + + return !rootBox.intersect(modelBox); +} + } // namespace scene } // namespace cc diff --git a/native/cocos/scene/Octree.h b/native/cocos/scene/Octree.h index d4d1581304..f2a8f2c08c 100644 --- a/native/cocos/scene/Octree.h +++ b/native/cocos/scene/Octree.h @@ -121,6 +121,12 @@ struct CC_DLL BBox final { inline bool contain(const BBox &box) const { return contain(box.min) && contain(box.max); } + + inline bool intersect(const BBox &box) const { + return !(min.x > box.max.x || max.x < box.min.x || + min.y > box.max.y || max.y < box.min.y || + min.z > box.max.z || max.z < box.min.z); + } }; /** @@ -216,6 +222,7 @@ public: private: bool isInside(Model *model) const; + bool isOutside(Model *model) const; OctreeNode *_root{nullptr}; uint32_t _maxDepth{DEFAULT_OCTREE_DEPTH}; diff --git a/native/tools/tojs/geometry.ini b/native/tools/tojs/geometry.ini index 6ca9b05651..5ee3a96bb5 100644 --- a/native/tools/tojs/geometry.ini +++ b/native/tools/tojs/geometry.ini @@ -33,7 +33,7 @@ hpp_headers = cocos/bindings/auto/jsb_cocos_auto.h # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes = AABB Obb Line Plane Frustum Capsule Sphere Triangle Ray ShapeBase +classes = AABB Obb Line Plane Frustum Capsule Sphere Triangle Ray Spline ShapeBase # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also @@ -49,7 +49,8 @@ skip = AABB::[getBoundary aabbAabb aabbFrustum aabbPlan merge transform transfor rename_functions = -getter_setter = ShapeBase::[_type/getType/setType] +getter_setter = ShapeBase::[_type/getType/setType], + Spline::[mode knots] rename_classes =