@vibe-engine/renderer-3d 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +22 -0
- package/README.md +10 -2
- package/dist/camera.d.ts +8 -0
- package/dist/camera.js +7 -0
- package/dist/index.d.ts +48 -0
- package/dist/index.js +494 -0
- package/dist/labels.d.ts +21 -0
- package/dist/labels.js +45 -0
- package/dist/shader.d.ts +13 -0
- package/dist/shader.js +53 -0
- package/package.json +42 -3
package/LICENSE-APACHE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
package/LICENSE-MIT
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 The vibe-engine contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
package/README.md
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @vibe-engine/renderer-3d
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
vibe-engine 3D renderer (Babylon.js).
|
|
4
|
+
|
|
5
|
+
Part of [vibe-engine](https://github.com/sergiobanhos/vibe-engine), a TypeScript game engine that is code-first, headless-first and made to be driven by AI agents. Start a game with:
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npx @vibe-engine/cli create my-game
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
License: MIT OR Apache-2.0.
|
package/dist/camera.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Câmera 3D por tick (pura): segue o alvo a `offset`, com suavização no relógio do tick (ver regra do 2D). */
|
|
2
|
+
import type { Camera3D } from '@vibe-engine/3d';
|
|
3
|
+
export interface Cam3 {
|
|
4
|
+
x: number;
|
|
5
|
+
y: number;
|
|
6
|
+
z: number;
|
|
7
|
+
}
|
|
8
|
+
export declare function camera3Step(c: typeof Camera3D.Type, from: Cam3 | null, target: Cam3, dt: number): Cam3;
|
package/dist/camera.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export function camera3Step(c, from, target, dt) {
|
|
2
|
+
const want = { x: target.x + c.offset.x, y: target.y + c.offset.y, z: target.z + c.offset.z };
|
|
3
|
+
if (!from || c.smoothing <= 0)
|
|
4
|
+
return want;
|
|
5
|
+
const k = 1 - Math.exp(-dt / c.smoothing);
|
|
6
|
+
return { x: from.x + (want.x - from.x) * k, y: from.y + (want.y - from.y) * k, z: from.z + (want.z - from.z) * k };
|
|
7
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import '@babylonjs/core/Lights/Shadows/shadowGeneratorSceneComponent.js';
|
|
2
|
+
import '@babylonjs/core/Shaders/ShadersInclude/bonesDeclaration.js';
|
|
3
|
+
import '@babylonjs/core/Shaders/ShadersInclude/bonesVertex.js';
|
|
4
|
+
import '@babylonjs/loaders/glTF/index.js';
|
|
5
|
+
import '@babylonjs/core/Meshes/thinInstanceMesh.js';
|
|
6
|
+
import '@babylonjs/core/Culling/ray.js';
|
|
7
|
+
import { type ShaderDef, type ShaderOrigin, type World } from '@vibe-engine/core';
|
|
8
|
+
export { camera3Step } from './camera.ts';
|
|
9
|
+
export interface Renderer3DOptions {
|
|
10
|
+
parent: HTMLElement;
|
|
11
|
+
width: number;
|
|
12
|
+
height: number;
|
|
13
|
+
background?: string;
|
|
14
|
+
/** id → URL dos modelos (`assetUrls(import.meta.glob('./assets/**\/*.glb', ...))`). */
|
|
15
|
+
assets?: Record<string, string>;
|
|
16
|
+
/** Shaders do projeto (`*.shader.ts`) e de onde vieram (erro de compilação com arquivo e linha). Os presets já vêm. */
|
|
17
|
+
shaders?: {
|
|
18
|
+
defs: ShaderDef[];
|
|
19
|
+
origins: Record<string, ShaderOrigin>;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export interface Renderer3D {
|
|
23
|
+
render(world: World, alpha?: number): void;
|
|
24
|
+
beforeTick(world: World): void;
|
|
25
|
+
/** Ponto do mundo sob o mouse, no plano horizontal y = `planeY` (mira em shooters). */
|
|
26
|
+
screenToWorld(clientX: number, clientY: number, planeY?: number): {
|
|
27
|
+
x: number;
|
|
28
|
+
y: number;
|
|
29
|
+
z: number;
|
|
30
|
+
} | null;
|
|
31
|
+
/** Ouvinte do áudio posicional: posição e direção da câmera do último frame (null sem Camera3D). Coordenadas do mundo. */
|
|
32
|
+
listener(): {
|
|
33
|
+
kind: '3d';
|
|
34
|
+
position: {
|
|
35
|
+
x: number;
|
|
36
|
+
y: number;
|
|
37
|
+
z: number;
|
|
38
|
+
};
|
|
39
|
+
forward: {
|
|
40
|
+
x: number;
|
|
41
|
+
y: number;
|
|
42
|
+
z: number;
|
|
43
|
+
};
|
|
44
|
+
} | null;
|
|
45
|
+
readonly canvas: HTMLCanvasElement;
|
|
46
|
+
destroy(): void;
|
|
47
|
+
}
|
|
48
|
+
export declare function createRenderer3D(opts: Renderer3DOptions): Promise<Renderer3D>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Renderer 3D com Babylon.js (ADR-0006). Só lê o world: Mesh, Model, BlockGrid,
|
|
3
|
+
* Light3D, Camera3D e Animator. Câmera por tick, interpolada com o mesmo alpha
|
|
4
|
+
* do alvo (regra do RFC-001 §16). Browser only.
|
|
5
|
+
*/
|
|
6
|
+
import { Engine } from '@babylonjs/core/Engines/engine.js';
|
|
7
|
+
import { Scene } from '@babylonjs/core/scene.js';
|
|
8
|
+
import { UniversalCamera } from '@babylonjs/core/Cameras/universalCamera.js';
|
|
9
|
+
import { Vector2, Vector3, Vector4, Quaternion, Matrix } from '@babylonjs/core/Maths/math.vector.js';
|
|
10
|
+
import { Color3, Color4 } from '@babylonjs/core/Maths/math.color.js';
|
|
11
|
+
import { HemisphericLight } from '@babylonjs/core/Lights/hemisphericLight.js';
|
|
12
|
+
import { DirectionalLight } from '@babylonjs/core/Lights/directionalLight.js';
|
|
13
|
+
import { PointLight } from '@babylonjs/core/Lights/pointLight.js';
|
|
14
|
+
import { ShadowGenerator } from '@babylonjs/core/Lights/Shadows/shadowGenerator.js';
|
|
15
|
+
import '@babylonjs/core/Lights/Shadows/shadowGeneratorSceneComponent.js';
|
|
16
|
+
import { CreateBox } from '@babylonjs/core/Meshes/Builders/boxBuilder.js';
|
|
17
|
+
import { CreateSphere } from '@babylonjs/core/Meshes/Builders/sphereBuilder.js';
|
|
18
|
+
import { CreateCylinder } from '@babylonjs/core/Meshes/Builders/cylinderBuilder.js';
|
|
19
|
+
import { CreateCapsule } from '@babylonjs/core/Meshes/Builders/capsuleBuilder.js';
|
|
20
|
+
import { CreateGround } from '@babylonjs/core/Meshes/Builders/groundBuilder.js';
|
|
21
|
+
import { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial.js';
|
|
22
|
+
import { ShaderMaterial } from '@babylonjs/core/Materials/shaderMaterial.js';
|
|
23
|
+
import { RawTexture } from '@babylonjs/core/Materials/Textures/rawTexture.js';
|
|
24
|
+
import { PostProcess } from '@babylonjs/core/PostProcesses/postProcess.js';
|
|
25
|
+
import { ShaderStore } from '@babylonjs/core/Engines/shaderStore.js';
|
|
26
|
+
import '@babylonjs/core/Shaders/ShadersInclude/bonesDeclaration.js'; // side effect: includes do vertex de superfície (esqueleto)
|
|
27
|
+
import '@babylonjs/core/Shaders/ShadersInclude/bonesVertex.js';
|
|
28
|
+
import { TransformNode } from '@babylonjs/core/Meshes/transformNode.js';
|
|
29
|
+
import { LoadAssetContainerAsync } from '@babylonjs/core/Loading/sceneLoader.js';
|
|
30
|
+
import '@babylonjs/loaders/glTF/index.js';
|
|
31
|
+
import '@babylonjs/core/Meshes/thinInstanceMesh.js';
|
|
32
|
+
import '@babylonjs/core/Culling/ray.js'; // side effect: scene.createPickingRay (screenToWorld)
|
|
33
|
+
import { PostEffect, SHADER_PRESETS, colorToVec4, compileGlsl, shaderUseProblem, uniformValues } from '@vibe-engine/core';
|
|
34
|
+
import { Animator, BlockGrid, Camera3D, Label3D, Light3D, Mesh, MeshShader, Model, Transform3D } from '@vibe-engine/3d';
|
|
35
|
+
import { camera3Step } from './camera.js';
|
|
36
|
+
import { createLabelLayer } from './labels.js';
|
|
37
|
+
import { MESH_UNIFORMS, MESH_VERTEX, meshFragmentPrelude, meshVertexPrelude, postPrelude } from './shader.js';
|
|
38
|
+
export { camera3Step } from './camera.js';
|
|
39
|
+
const hex = (c) => Color3.FromHexString(c.slice(0, 7));
|
|
40
|
+
export async function createRenderer3D(opts) {
|
|
41
|
+
const canvas = document.createElement('canvas');
|
|
42
|
+
canvas.width = opts.width;
|
|
43
|
+
canvas.height = opts.height;
|
|
44
|
+
canvas.style.cssText = `display:block;width:${opts.width}px;height:${opts.height}px`;
|
|
45
|
+
opts.parent.appendChild(canvas);
|
|
46
|
+
const engine = new Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });
|
|
47
|
+
const scene = new Scene(engine);
|
|
48
|
+
// O jogo não usa o picking do Babylon (input vem do runtime): sem raycast a cada movimento do mouse.
|
|
49
|
+
scene.skipPointerMovePicking = true;
|
|
50
|
+
scene.skipPointerDownPicking = true;
|
|
51
|
+
scene.skipPointerUpPicking = true;
|
|
52
|
+
const bg = hex(opts.background ?? '#cfe9f6');
|
|
53
|
+
scene.clearColor = new Color4(bg.r, bg.g, bg.b, 1);
|
|
54
|
+
const camera = new UniversalCamera('camera', new Vector3(0, 5, -10), scene);
|
|
55
|
+
camera.minZ = 0.05;
|
|
56
|
+
const containers = new Map();
|
|
57
|
+
await Promise.all(Object.entries(opts.assets ?? {}).map(async ([id, url]) => containers.set(id, await LoadAssetContainerAsync(url, scene, { pluginExtension: '.glb' }))));
|
|
58
|
+
const views = new Map();
|
|
59
|
+
const grids = new Map();
|
|
60
|
+
const lights = new Map();
|
|
61
|
+
const materials = new Map();
|
|
62
|
+
const material = (color, emissive = '#000000', roughness = 0.8) => {
|
|
63
|
+
const key = `${color}|${emissive}|${roughness}`;
|
|
64
|
+
let m = materials.get(key);
|
|
65
|
+
if (!m) {
|
|
66
|
+
m = new StandardMaterial(key, scene);
|
|
67
|
+
m.diffuseColor = hex(color);
|
|
68
|
+
m.emissiveColor = hex(emissive);
|
|
69
|
+
m.specularColor = new Color3(1, 1, 1).scale((1 - roughness) * 0.4);
|
|
70
|
+
materials.set(key, m);
|
|
71
|
+
}
|
|
72
|
+
return m;
|
|
73
|
+
};
|
|
74
|
+
const unlit = new Map();
|
|
75
|
+
const unlitMaterial = (color, texture = null) => {
|
|
76
|
+
const key = `${color}|${texture?.uniqueId ?? ''}`;
|
|
77
|
+
let m = unlit.get(key);
|
|
78
|
+
if (!m) {
|
|
79
|
+
m = new StandardMaterial(`unlit:${key}`, scene);
|
|
80
|
+
m.disableLighting = true;
|
|
81
|
+
m.emissiveColor = hex(color);
|
|
82
|
+
if (texture)
|
|
83
|
+
m.emissiveTexture = texture;
|
|
84
|
+
unlit.set(key, m);
|
|
85
|
+
}
|
|
86
|
+
return m;
|
|
87
|
+
};
|
|
88
|
+
// Shaders (#125): GLSL ES 3.0 (ADR-0010). Compila antes no WebGL2 só para ler o log com arquivo e linha.
|
|
89
|
+
const shaders = { ...SHADER_PRESETS, ...Object.fromEntries((opts.shaders?.defs ?? []).map((d) => [d.id, d])) };
|
|
90
|
+
const gl = canvas.getContext('webgl2'); // o mesmo contexto que o Babylon criou
|
|
91
|
+
const checked = new Set();
|
|
92
|
+
const check = (def) => {
|
|
93
|
+
if (checked.has(def.id) || !gl)
|
|
94
|
+
return;
|
|
95
|
+
const origin = opts.shaders?.origins[def.id];
|
|
96
|
+
if (def.kind === 'mesh') {
|
|
97
|
+
compileGlsl(gl, 'vertex', meshVertexPrelude(def), def.vertex ?? MESH_VERTEX, def, origin);
|
|
98
|
+
compileGlsl(gl, 'fragment', meshFragmentPrelude(def), def.fragment, def, origin);
|
|
99
|
+
}
|
|
100
|
+
else
|
|
101
|
+
compileGlsl(gl, 'fragment', postPrelude(def), def.fragment, def, origin);
|
|
102
|
+
checked.add(def.id);
|
|
103
|
+
};
|
|
104
|
+
for (const d of opts.shaders?.defs ?? [])
|
|
105
|
+
check(d); // erro de compilação aparece ao abrir o jogo
|
|
106
|
+
const use = (u, kind, who) => {
|
|
107
|
+
const problem = shaderUseProblem(shaders, u, kind, who);
|
|
108
|
+
if (problem)
|
|
109
|
+
throw new Error(`renderer-3d: ${problem.message}`);
|
|
110
|
+
const def = shaders[u.shader];
|
|
111
|
+
check(def);
|
|
112
|
+
return def;
|
|
113
|
+
};
|
|
114
|
+
const setUniforms = (set, def, values) => {
|
|
115
|
+
for (const [n, v] of Object.entries(uniformValues(def, values))) {
|
|
116
|
+
if (Array.isArray(v))
|
|
117
|
+
set.vec(n, v);
|
|
118
|
+
else if (def.uniforms[n].kind === 'int')
|
|
119
|
+
set.int(n, v);
|
|
120
|
+
else
|
|
121
|
+
set.float(n, v);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
const white = RawTexture.CreateRGBATexture(new Uint8Array([255, 255, 255, 255]), 1, 1, scene);
|
|
125
|
+
/** Materiais de shader por entidade (uniforms por entidade). */
|
|
126
|
+
const meshFx = new Map();
|
|
127
|
+
const shaderMaterial = (def, name, color, texture) => {
|
|
128
|
+
const m = new ShaderMaterial(name, scene, { vertexSource: `${meshVertexPrelude(def)}\n${def.vertex ?? MESH_VERTEX}`, fragmentSource: `${meshFragmentPrelude(def)}\n${def.fragment}` }, {
|
|
129
|
+
attributes: ['position', 'normal', 'uv'],
|
|
130
|
+
uniforms: [...MESH_UNIFORMS, ...Object.keys(def.uniforms).filter((n) => n !== 'time')],
|
|
131
|
+
samplers: ['uTexture'],
|
|
132
|
+
});
|
|
133
|
+
m.setVector4('uColor', new Vector4(color[0], color[1], color[2], color[3]));
|
|
134
|
+
m.setTexture('uTexture', texture ?? white);
|
|
135
|
+
return m;
|
|
136
|
+
};
|
|
137
|
+
/** Cor e textura do material original (glTF: PBR; outros: Standard). */
|
|
138
|
+
const baseOf = (mat) => {
|
|
139
|
+
const m = mat;
|
|
140
|
+
const c = m?.albedoColor ?? m?.diffuseColor ?? new Color3(1, 1, 1);
|
|
141
|
+
return { color: [c.r, c.g, c.b, m?.alpha ?? 1], texture: m?.albedoTexture ?? m?.diffuseTexture ?? null };
|
|
142
|
+
};
|
|
143
|
+
const vecSetter = (m) => ({
|
|
144
|
+
float: (n, v) => m.setFloat(n, v),
|
|
145
|
+
int: (n, v) => m.setInt(n, v),
|
|
146
|
+
vec: (n, v) => (v.length === 2 ? m.setVector2(n, new Vector2(v[0], v[1])) : v.length === 3 ? m.setVector3(n, new Vector3(v[0], v[1], v[2])) : m.setVector4(n, new Vector4(v[0], v[1], v[2], v[3]))),
|
|
147
|
+
});
|
|
148
|
+
let posts = [];
|
|
149
|
+
let postKey = '';
|
|
150
|
+
let simTime = 0;
|
|
151
|
+
let prevPos = new Map();
|
|
152
|
+
let prevOff = new Map();
|
|
153
|
+
const snapshot = (world) => {
|
|
154
|
+
const out = new Map();
|
|
155
|
+
for (const e of world.query(Transform3D)) {
|
|
156
|
+
const t = e.read(Transform3D);
|
|
157
|
+
out.set(e.id, { p: new Vector3(t.position.x, t.position.y, t.position.z), r: new Quaternion(t.rotation.x, t.rotation.y, t.rotation.z, t.rotation.w) });
|
|
158
|
+
}
|
|
159
|
+
return out;
|
|
160
|
+
};
|
|
161
|
+
const at = (world, id, t, alpha) => {
|
|
162
|
+
const b = { p: new Vector3(t.position.x, t.position.y, t.position.z), r: new Quaternion(t.rotation.x, t.rotation.y, t.rotation.z, t.rotation.w) };
|
|
163
|
+
const a = prevPos.get(id);
|
|
164
|
+
const p = !a || Vector3.Distance(a.p, b.p) > 4 ? b : { p: Vector3.Lerp(a.p, b.p, alpha), r: Quaternion.Slerp(a.r, b.r, alpha) }; // salto grande: teletransporte
|
|
165
|
+
// Correção da rede: o cliente de rede a diminui a cada tick; aqui só interpola entre ticks.
|
|
166
|
+
const ob = world.visualOffsets.get(id);
|
|
167
|
+
const oa = prevOff.get(id);
|
|
168
|
+
if (oa || ob)
|
|
169
|
+
p.p = p.p.add(Vector3.Lerp(new Vector3(oa?.x ?? 0, oa?.y ?? 0, oa?.z ?? 0), new Vector3(ob?.x ?? 0, ob?.y ?? 0, ob?.z ?? 0), alpha));
|
|
170
|
+
return p;
|
|
171
|
+
};
|
|
172
|
+
let camPrev = null;
|
|
173
|
+
let camCurr = null;
|
|
174
|
+
let listen = null;
|
|
175
|
+
let camFrame = 0;
|
|
176
|
+
const labels = createLabelLayer(opts.parent, canvas, opts.width);
|
|
177
|
+
const shadowCasters = () => [...views.values()].flatMap((v) => v.meshes);
|
|
178
|
+
return {
|
|
179
|
+
canvas,
|
|
180
|
+
listener: () => listen,
|
|
181
|
+
beforeTick(world) { prevPos = snapshot(world); prevOff = new Map([...world.visualOffsets].map(([id, o]) => [id, { ...o }])); },
|
|
182
|
+
screenToWorld(clientX, clientY, planeY = 0) {
|
|
183
|
+
const rect = canvas.getBoundingClientRect();
|
|
184
|
+
const ray = scene.createPickingRay(((clientX - rect.left) * opts.width) / rect.width, ((clientY - rect.top) * opts.height) / rect.height, Matrix.Identity(), camera);
|
|
185
|
+
if (Math.abs(ray.direction.y) < 1e-6)
|
|
186
|
+
return null;
|
|
187
|
+
const t = (planeY - ray.origin.y) / ray.direction.y;
|
|
188
|
+
if (t < 0)
|
|
189
|
+
return null;
|
|
190
|
+
const p = ray.origin.add(ray.direction.scale(t));
|
|
191
|
+
return { x: p.x, y: p.y, z: p.z };
|
|
192
|
+
},
|
|
193
|
+
render(world, alpha = 1) {
|
|
194
|
+
const seen = new Set();
|
|
195
|
+
for (const e of world.query(Transform3D)) {
|
|
196
|
+
const hasMesh = e.has(Mesh);
|
|
197
|
+
const hasModel = e.has(Model);
|
|
198
|
+
if (!hasMesh && !hasModel)
|
|
199
|
+
continue;
|
|
200
|
+
seen.add(e.id);
|
|
201
|
+
const custom = e.has(MeshShader) ? e.read(MeshShader) : null;
|
|
202
|
+
const key = `${hasModel ? `model:${e.read(Model).asset}:${e.read(Model).material}` : `mesh:${JSON.stringify(e.read(Mesh))}`}|${custom?.shader ?? ''}`;
|
|
203
|
+
let v = views.get(e.id);
|
|
204
|
+
if (!v || v.key !== key) {
|
|
205
|
+
if (v) {
|
|
206
|
+
v.node.dispose();
|
|
207
|
+
for (const g of v.groups)
|
|
208
|
+
g.dispose();
|
|
209
|
+
}
|
|
210
|
+
for (const m of meshFx.get(e.id)?.mats ?? [])
|
|
211
|
+
m.dispose();
|
|
212
|
+
meshFx.delete(e.id);
|
|
213
|
+
const node = new TransformNode(e.id, scene);
|
|
214
|
+
node.rotationQuaternion = Quaternion.Identity();
|
|
215
|
+
let meshes = [];
|
|
216
|
+
let groups = [];
|
|
217
|
+
if (hasModel) {
|
|
218
|
+
const m = e.read(Model);
|
|
219
|
+
const container = containers.get(m.asset);
|
|
220
|
+
if (!container)
|
|
221
|
+
throw new Error(`renderer-3d: entity '${e.id}' uses model '${m.asset}', which was not given in assets`);
|
|
222
|
+
const inst = container.instantiateModelsToScene((n) => `${e.id}:${n}`, false);
|
|
223
|
+
// Compõe com o __root__ do loader glTF (giro de 180° e z = -1 da troca de mão): sobrescrever espelha o modelo.
|
|
224
|
+
for (const root of inst.rootNodes) {
|
|
225
|
+
root.parent = node;
|
|
226
|
+
root.position.addInPlace(new Vector3(m.offset.x, m.offset.y, m.offset.z));
|
|
227
|
+
root.scaling.scaleInPlace(m.scale);
|
|
228
|
+
}
|
|
229
|
+
meshes = inst.rootNodes.flatMap((n) => n.getChildMeshes(false));
|
|
230
|
+
groups = inst.animationGroups;
|
|
231
|
+
// instantiateModelsToScene renomeia os grupos com o prefixo; o clipe usa o nome do arquivo.
|
|
232
|
+
groups.forEach((g, i) => { g.name = container.animationGroups[i]?.name ?? g.name; });
|
|
233
|
+
for (const g of groups) {
|
|
234
|
+
g.stop();
|
|
235
|
+
g.enableBlending = true;
|
|
236
|
+
}
|
|
237
|
+
// Material trocado: shader próprio ou toon (um por submalha, com a cor/textura dela) ou unlit.
|
|
238
|
+
const kind = custom ? custom.shader : m.material;
|
|
239
|
+
if (kind === 'unlit')
|
|
240
|
+
for (const mesh of meshes) {
|
|
241
|
+
const b = baseOf(mesh.material);
|
|
242
|
+
mesh.material = unlitMaterial(Color3.FromArray(b.color).toHexString(), b.texture);
|
|
243
|
+
}
|
|
244
|
+
else if (kind) {
|
|
245
|
+
const def = use(custom ?? { shader: 'toon', uniforms: {} }, 'mesh', `${e.id}.${custom ? 'MeshShader' : 'Model'}`);
|
|
246
|
+
const mats = meshes.map((mesh, i) => { const b = baseOf(mesh.material); const sm = shaderMaterial(def, `${e.id}:${def.id}:${i}`, b.color, b.texture); mesh.material = sm; return sm; });
|
|
247
|
+
meshFx.set(e.id, { def, mats, uniforms: custom?.uniforms ?? {} });
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
else {
|
|
251
|
+
const mesh = e.read(Mesh);
|
|
252
|
+
const s = mesh.size;
|
|
253
|
+
const b = mesh.primitive === 'sphere' ? CreateSphere(e.id, { diameterX: s.x, diameterY: s.y, diameterZ: s.z, segments: 16 }, scene)
|
|
254
|
+
: mesh.primitive === 'cylinder' ? CreateCylinder(e.id, { height: s.y, diameter: s.x }, scene)
|
|
255
|
+
: mesh.primitive === 'capsule' ? CreateCapsule(e.id, { height: s.y, radius: s.x / 2 }, scene)
|
|
256
|
+
: mesh.primitive === 'plane' ? CreateGround(e.id, { width: s.x, height: s.z }, scene)
|
|
257
|
+
: CreateBox(e.id, { width: s.x, height: s.y, depth: s.z }, scene);
|
|
258
|
+
if (custom || mesh.material === 'toon') {
|
|
259
|
+
const def = use(custom ?? { shader: 'toon', uniforms: {} }, 'mesh', `${e.id}.${custom ? 'MeshShader' : 'Mesh'}`);
|
|
260
|
+
const m = shaderMaterial(def, `${e.id}:${def.id}`, colorToVec4(mesh.color), null);
|
|
261
|
+
b.material = m;
|
|
262
|
+
meshFx.set(e.id, { def, mats: [m], uniforms: custom?.uniforms ?? {} });
|
|
263
|
+
}
|
|
264
|
+
else
|
|
265
|
+
b.material = mesh.material === 'unlit' ? unlitMaterial(mesh.color) : material(mesh.color, mesh.emissive, mesh.roughness);
|
|
266
|
+
b.parent = node;
|
|
267
|
+
b.receiveShadows = true;
|
|
268
|
+
meshes = [b];
|
|
269
|
+
}
|
|
270
|
+
v = { node, key, meshes, groups, clip: '' };
|
|
271
|
+
views.set(e.id, v);
|
|
272
|
+
}
|
|
273
|
+
const p = at(world, e.id, e.read(Transform3D), alpha);
|
|
274
|
+
const tr = e.read(Transform3D);
|
|
275
|
+
v.node.position.copyFrom(p.p);
|
|
276
|
+
v.node.rotationQuaternion.copyFrom(p.r);
|
|
277
|
+
v.node.scaling.set(tr.scale.x, tr.scale.y, tr.scale.z);
|
|
278
|
+
v.node.setEnabled(e.visible);
|
|
279
|
+
const fx = meshFx.get(e.id);
|
|
280
|
+
if (fx && custom)
|
|
281
|
+
fx.uniforms = custom.uniforms;
|
|
282
|
+
// Animator: troca de clipe com transição (blending do Babylon).
|
|
283
|
+
if (e.has(Animator) && v.groups.length) {
|
|
284
|
+
const an = e.read(Animator);
|
|
285
|
+
if (an.clip !== v.clip) {
|
|
286
|
+
const next = v.groups.find((g) => g.name === an.clip);
|
|
287
|
+
if (an.clip && !next)
|
|
288
|
+
throw new Error(`renderer-3d: '${e.id}' plays clip '${an.clip}', which the model does not have (has: ${v.groups.map((g) => g.name).join(', ')})`);
|
|
289
|
+
for (const g of v.groups) {
|
|
290
|
+
g.blendingSpeed = an.fade > 0 ? Math.min(1, 1 / (an.fade * 60)) : 1;
|
|
291
|
+
if (g !== next)
|
|
292
|
+
g.stop();
|
|
293
|
+
}
|
|
294
|
+
next?.start(an.loop, an.speed);
|
|
295
|
+
v.clip = an.clip;
|
|
296
|
+
}
|
|
297
|
+
for (const g of v.groups)
|
|
298
|
+
if (g.isPlaying)
|
|
299
|
+
g.speedRatio = an.speed;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
for (const [id, v] of views)
|
|
303
|
+
if (!seen.has(id)) {
|
|
304
|
+
v.node.dispose();
|
|
305
|
+
for (const g of v.groups)
|
|
306
|
+
g.dispose();
|
|
307
|
+
views.delete(id);
|
|
308
|
+
for (const m of meshFx.get(id)?.mats ?? [])
|
|
309
|
+
m.dispose();
|
|
310
|
+
meshFx.delete(id);
|
|
311
|
+
}
|
|
312
|
+
// Grades de blocos: uma malha por cor da paleta, com thin instances (barato para milhares de blocos).
|
|
313
|
+
const seenGrids = new Set();
|
|
314
|
+
for (const e of world.query(Transform3D, BlockGrid)) {
|
|
315
|
+
seenGrids.add(e.id);
|
|
316
|
+
const g = e.read(BlockGrid);
|
|
317
|
+
const key = `${g.version}:${g.width}x${g.depth}x${g.height}:${g.cellSize}:${JSON.stringify(g.palette)}`;
|
|
318
|
+
let entry = grids.get(e.id);
|
|
319
|
+
if (!entry || entry.key !== key) {
|
|
320
|
+
for (const m of entry?.meshes ?? [])
|
|
321
|
+
m.dispose();
|
|
322
|
+
const origin = e.read(Transform3D).position;
|
|
323
|
+
const meshes = g.palette.map((pal, index) => {
|
|
324
|
+
const box = CreateBox(`${e.id}:${index}`, { size: g.cellSize }, scene);
|
|
325
|
+
box.material = material(pal.color);
|
|
326
|
+
box.receiveShadows = true;
|
|
327
|
+
const mats = [];
|
|
328
|
+
g.cells.forEach((v, i) => {
|
|
329
|
+
if (v !== index)
|
|
330
|
+
return;
|
|
331
|
+
const x = i % g.width;
|
|
332
|
+
const z = Math.floor(i / g.width) % g.depth;
|
|
333
|
+
const y = Math.floor(i / (g.width * g.depth));
|
|
334
|
+
mats.push(...Matrix.Translation(origin.x + (x + 0.5) * g.cellSize, origin.y + (y + 0.5) * g.cellSize, origin.z + (z + 0.5) * g.cellSize).toArray());
|
|
335
|
+
});
|
|
336
|
+
if (mats.length)
|
|
337
|
+
box.thinInstanceSetBuffer('matrix', new Float32Array(mats), 16);
|
|
338
|
+
else
|
|
339
|
+
box.setEnabled(false);
|
|
340
|
+
return box;
|
|
341
|
+
});
|
|
342
|
+
entry = { meshes, key };
|
|
343
|
+
grids.set(e.id, entry);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
for (const [id, entry] of grids)
|
|
347
|
+
if (!seenGrids.has(id)) {
|
|
348
|
+
for (const m of entry.meshes)
|
|
349
|
+
m.dispose();
|
|
350
|
+
grids.delete(id);
|
|
351
|
+
}
|
|
352
|
+
// Luzes.
|
|
353
|
+
const seenLights = new Set();
|
|
354
|
+
for (const e of world.query(Light3D)) {
|
|
355
|
+
seenLights.add(e.id);
|
|
356
|
+
const l = e.read(Light3D);
|
|
357
|
+
const key = l.kind;
|
|
358
|
+
let entry = lights.get(e.id);
|
|
359
|
+
if (!entry || entry.key !== key) {
|
|
360
|
+
entry?.light.dispose();
|
|
361
|
+
entry?.shadows?.dispose();
|
|
362
|
+
const light = l.kind === 'ambient' ? new HemisphericLight(e.id, new Vector3(0, 1, 0), scene) : l.kind === 'point' ? new PointLight(e.id, Vector3.Zero(), scene) : new DirectionalLight(e.id, new Vector3(l.direction.x, l.direction.y, l.direction.z), scene);
|
|
363
|
+
let shadows = null;
|
|
364
|
+
if (light instanceof DirectionalLight && l.shadows) {
|
|
365
|
+
light.position = new Vector3(-l.direction.x * 30, -l.direction.y * 30, -l.direction.z * 30);
|
|
366
|
+
shadows = new ShadowGenerator(2048, light);
|
|
367
|
+
shadows.usePercentageCloserFiltering = true;
|
|
368
|
+
}
|
|
369
|
+
entry = { light, key, shadows };
|
|
370
|
+
lights.set(e.id, entry);
|
|
371
|
+
}
|
|
372
|
+
entry.light.diffuse = hex(l.color);
|
|
373
|
+
entry.light.intensity = l.intensity;
|
|
374
|
+
if (entry.light instanceof PointLight && e.has(Transform3D)) {
|
|
375
|
+
const p = e.read(Transform3D).position;
|
|
376
|
+
entry.light.position.set(p.x, p.y, p.z);
|
|
377
|
+
entry.light.range = l.range;
|
|
378
|
+
}
|
|
379
|
+
if (entry.shadows) {
|
|
380
|
+
const casters = shadowCasters();
|
|
381
|
+
entry.shadows.getShadowMap().renderList = casters;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
for (const [id, entry] of lights)
|
|
385
|
+
if (!seenLights.has(id)) {
|
|
386
|
+
entry.light.dispose();
|
|
387
|
+
entry.shadows?.dispose();
|
|
388
|
+
lights.delete(id);
|
|
389
|
+
}
|
|
390
|
+
// Câmera por tick, interpolada com o alpha do alvo.
|
|
391
|
+
const cam = world.query(Camera3D)[0];
|
|
392
|
+
if (cam) {
|
|
393
|
+
const c = cam.read(Camera3D);
|
|
394
|
+
const followed = c.follow && world.exists(c.follow) && world.entity(c.follow).has(Transform3D) ? world.entity(c.follow) : null;
|
|
395
|
+
const targetNow = followed ? followed.read(Transform3D).position : cam.has(Transform3D) ? cam.read(Transform3D).position : { x: 0, y: 0, z: 0 };
|
|
396
|
+
const prev = followed ? prevPos.get(followed.id)?.p : undefined;
|
|
397
|
+
const targetPrev = prev ? { x: prev.x, y: prev.y, z: prev.z } : targetNow;
|
|
398
|
+
if (!camCurr) {
|
|
399
|
+
camPrev = camCurr = camera3Step(c, null, targetNow, world.dt);
|
|
400
|
+
camFrame = world.frame;
|
|
401
|
+
}
|
|
402
|
+
const ticks = Math.min(world.frame - camFrame, 8);
|
|
403
|
+
for (let i = 0; i < ticks; i++) {
|
|
404
|
+
camPrev = camCurr;
|
|
405
|
+
camCurr = camera3Step(c, camCurr, i < ticks - 1 ? targetPrev : targetNow, world.dt);
|
|
406
|
+
}
|
|
407
|
+
camFrame = world.frame;
|
|
408
|
+
const pos = { x: camPrev.x + (camCurr.x - camPrev.x) * alpha, y: camPrev.y + (camCurr.y - camPrev.y) * alpha, z: camPrev.z + (camCurr.z - camPrev.z) * alpha };
|
|
409
|
+
const look = followed ? at(world, followed.id, followed.read(Transform3D), alpha).p : new Vector3(targetNow.x, targetNow.y, targetNow.z);
|
|
410
|
+
camera.position.set(pos.x, pos.y, pos.z);
|
|
411
|
+
camera.fov = (c.fov * Math.PI) / 180;
|
|
412
|
+
const target = new Vector3(look.x + c.lookOffset.x, look.y + c.lookOffset.y, look.z + c.lookOffset.z);
|
|
413
|
+
camera.setTarget(target);
|
|
414
|
+
const f = target.subtract(camera.position).normalize();
|
|
415
|
+
listen = { kind: '3d', position: pos, forward: { x: f.x, y: f.y, z: f.z } };
|
|
416
|
+
}
|
|
417
|
+
else
|
|
418
|
+
listen = null;
|
|
419
|
+
// Uniforms dos shaders de superfície: tempo de simulação, luz (primeira direcional + ambientes) e câmera.
|
|
420
|
+
simTime = world.frame * world.dt;
|
|
421
|
+
if (meshFx.size) {
|
|
422
|
+
const lightDir = new Vector3(0, 1, 0);
|
|
423
|
+
let lightColor = new Vector3(0, 0, 0);
|
|
424
|
+
const ambient = new Vector3(0, 0, 0);
|
|
425
|
+
let sun = false;
|
|
426
|
+
for (const e of world.query(Light3D)) {
|
|
427
|
+
const l = e.read(Light3D);
|
|
428
|
+
const c = colorToVec4(l.color);
|
|
429
|
+
const rgb = new Vector3(c[0] * l.intensity, c[1] * l.intensity, c[2] * l.intensity);
|
|
430
|
+
if (l.kind === 'ambient')
|
|
431
|
+
ambient.addInPlace(rgb);
|
|
432
|
+
else if (l.kind === 'directional' && !sun) {
|
|
433
|
+
sun = true;
|
|
434
|
+
lightDir.set(-l.direction.x, -l.direction.y, -l.direction.z);
|
|
435
|
+
lightDir.normalize();
|
|
436
|
+
lightColor = rgb;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
for (const fx of meshFx.values())
|
|
440
|
+
for (const m of fx.mats) {
|
|
441
|
+
m.setFloat('time', simTime);
|
|
442
|
+
m.setVector3('uLightDir', lightDir);
|
|
443
|
+
m.setVector3('uLightColor', lightColor);
|
|
444
|
+
m.setVector3('uAmbient', ambient);
|
|
445
|
+
m.setVector3('uCameraPos', camera.position);
|
|
446
|
+
setUniforms(vecSetter(m), fx.def, fx.uniforms);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
// Pós-processamento: uma passada por entidade visível com PostEffect, em ordem de `order` e id.
|
|
450
|
+
const effects = world.query(PostEffect).filter((e) => e.visible).map((e) => ({ id: e.id, pe: e.read(PostEffect) }))
|
|
451
|
+
.sort((a, b) => a.pe.order - b.pe.order || (a.id < b.id ? -1 : 1));
|
|
452
|
+
const postNow = effects.map((p) => `${p.id}:${p.pe.shader}`).join('|');
|
|
453
|
+
if (postNow !== postKey) {
|
|
454
|
+
for (const p of posts)
|
|
455
|
+
p.pp.dispose(camera);
|
|
456
|
+
posts = effects.map((p) => {
|
|
457
|
+
const def = use(p.pe, 'filter', `${p.id}.PostEffect`);
|
|
458
|
+
const name = `vibe_${def.id.replace(/-/g, '_')}`;
|
|
459
|
+
ShaderStore.ShadersStore[`${name}FragmentShader`] = `${postPrelude(def)}\n${def.fragment}`;
|
|
460
|
+
const entry = { pp: new PostProcess(`post:${p.id}`, name, ['time', 'uTexel', 'uScreen', ...Object.keys(def.uniforms).filter((n) => n !== 'time')], ['textureSampler'], 1, camera), def, uniforms: p.pe.uniforms };
|
|
461
|
+
entry.pp.onApply = (effect) => {
|
|
462
|
+
effect.setFloat('time', simTime);
|
|
463
|
+
effect.setFloat2('uTexel', 1 / entry.pp.width, 1 / entry.pp.height);
|
|
464
|
+
effect.setFloat2('uScreen', entry.pp.width, entry.pp.height);
|
|
465
|
+
setUniforms({ float: (n, v) => effect.setFloat(n, v), int: (n, v) => effect.setInt(n, v), vec: (n, v) => (v.length === 2 ? effect.setFloat2(n, v[0], v[1]) : v.length === 3 ? effect.setFloat3(n, v[0], v[1], v[2]) : effect.setFloat4(n, v[0], v[1], v[2], v[3])) }, entry.def, entry.uniforms);
|
|
466
|
+
};
|
|
467
|
+
return entry;
|
|
468
|
+
});
|
|
469
|
+
postKey = postNow;
|
|
470
|
+
}
|
|
471
|
+
effects.forEach((p, i) => { posts[i].uniforms = p.pe.uniforms; });
|
|
472
|
+
scene.render();
|
|
473
|
+
// Rótulos (Label3D): o ponto interpolado + offset projetado na tela; atrás da câmera, não aparece.
|
|
474
|
+
labels.begin();
|
|
475
|
+
const viewport = camera.viewport.toGlobal(opts.width, opts.height);
|
|
476
|
+
for (const e of world.query(Transform3D, Label3D)) {
|
|
477
|
+
const l = e.read(Label3D);
|
|
478
|
+
if (!e.visible || !l.text)
|
|
479
|
+
continue;
|
|
480
|
+
const p = at(world, e.id, e.read(Transform3D), alpha).p.add(new Vector3(l.offset.x, l.offset.y, l.offset.z));
|
|
481
|
+
const s = Vector3.Project(p, Matrix.Identity(), scene.getTransformMatrix(), viewport);
|
|
482
|
+
if (s.z < 0 || s.z > 1)
|
|
483
|
+
continue;
|
|
484
|
+
labels.draw(e.id, l, s.x, s.y, l.owner !== '' && l.owner === world.localPlayer);
|
|
485
|
+
}
|
|
486
|
+
labels.end();
|
|
487
|
+
},
|
|
488
|
+
destroy() {
|
|
489
|
+
labels.destroy();
|
|
490
|
+
engine.dispose();
|
|
491
|
+
canvas.remove();
|
|
492
|
+
},
|
|
493
|
+
};
|
|
494
|
+
}
|
package/dist/labels.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rótulos no mundo como texto DOM por cima do canvas: nítidos em qualquer
|
|
3
|
+
* zoom (pixel art inclusive) e na fonte do tema da UI (a camada tem a classe
|
|
4
|
+
* `vibe-ui`, então o CSS do tema vale). Só lê o que o renderer manda.
|
|
5
|
+
*/
|
|
6
|
+
export interface LabelLook {
|
|
7
|
+
text: string;
|
|
8
|
+
size: number;
|
|
9
|
+
color: string;
|
|
10
|
+
background: string | null;
|
|
11
|
+
owner: string;
|
|
12
|
+
}
|
|
13
|
+
export declare function createLabelLayer(parent: HTMLElement, canvas: HTMLCanvasElement, width: number): {
|
|
14
|
+
/** Começo do frame: a camada cobre o canvas. */
|
|
15
|
+
begin(): void;
|
|
16
|
+
/** `x`, `y`: ponto de baixo do texto, em pixels lógicos do canvas. `own`: rótulo do jogador local (cores trocadas). */
|
|
17
|
+
draw(id: string, l: LabelLook, x: number, y: number, own: boolean, alpha?: number): void;
|
|
18
|
+
/** Fim do frame: some quem não foi desenhado. */
|
|
19
|
+
end(): void;
|
|
20
|
+
destroy(): void;
|
|
21
|
+
};
|
package/dist/labels.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
export function createLabelLayer(parent, canvas, width) {
|
|
2
|
+
const root = document.createElement('div');
|
|
3
|
+
root.className = 'vibe-ui vibe-labels';
|
|
4
|
+
root.style.cssText = 'position:absolute;left:0;top:0;pointer-events:none;overflow:hidden';
|
|
5
|
+
parent.style.position ||= 'relative';
|
|
6
|
+
parent.appendChild(root);
|
|
7
|
+
const nodes = new Map();
|
|
8
|
+
let seen = new Set();
|
|
9
|
+
let k = 1;
|
|
10
|
+
return {
|
|
11
|
+
/** Começo do frame: a camada cobre o canvas. */
|
|
12
|
+
begin() {
|
|
13
|
+
Object.assign(root.style, { left: `${canvas.offsetLeft}px`, top: `${canvas.offsetTop}px`, width: `${canvas.clientWidth}px`, height: `${canvas.clientHeight}px` });
|
|
14
|
+
k = canvas.clientWidth / width || 1;
|
|
15
|
+
seen = new Set();
|
|
16
|
+
},
|
|
17
|
+
/** `x`, `y`: ponto de baixo do texto, em pixels lógicos do canvas. `own`: rótulo do jogador local (cores trocadas). */
|
|
18
|
+
draw(id, l, x, y, own, alpha = 1) {
|
|
19
|
+
seen.add(id);
|
|
20
|
+
let el = nodes.get(id);
|
|
21
|
+
if (!el) {
|
|
22
|
+
el = document.createElement('div');
|
|
23
|
+
el.style.cssText = 'position:absolute;left:0;top:0;white-space:pre;line-height:1.2;padding:0 3px';
|
|
24
|
+
root.appendChild(el);
|
|
25
|
+
nodes.set(id, el);
|
|
26
|
+
}
|
|
27
|
+
if (el.textContent !== l.text)
|
|
28
|
+
el.textContent = l.text;
|
|
29
|
+
Object.assign(el.style, {
|
|
30
|
+
fontSize: `${l.size}px`,
|
|
31
|
+
color: own ? (l.background ?? '#f4f4f2') : l.color,
|
|
32
|
+
background: own ? l.color : (l.background ?? 'transparent'),
|
|
33
|
+
opacity: String(alpha),
|
|
34
|
+
transform: `translate(${Math.round(x * k)}px, ${Math.round(y * k)}px) translate(-50%, -100%)`,
|
|
35
|
+
});
|
|
36
|
+
},
|
|
37
|
+
/** Fim do frame: some quem não foi desenhado. */
|
|
38
|
+
end() { for (const [id, el] of nodes)
|
|
39
|
+
if (!seen.has(id)) {
|
|
40
|
+
el.remove();
|
|
41
|
+
nodes.delete(id);
|
|
42
|
+
} },
|
|
43
|
+
destroy() { root.remove(); },
|
|
44
|
+
};
|
|
45
|
+
}
|
package/dist/shader.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Código GLSL no Babylon (#125, ADR-0010). Puro (sem Babylon). Pós-processamento usa o
|
|
3
|
+
* vertex `postprocess` do Babylon (`vUV`, `textureSampler`); superfície usa o vertex abaixo.
|
|
4
|
+
* A saída é `layout(location = 0) out vec4 finalColor`: com ela o Babylon não declara a dele.
|
|
5
|
+
*/
|
|
6
|
+
import { type ShaderDef } from '@vibe-engine/core';
|
|
7
|
+
export declare function postPrelude(def: ShaderDef): string;
|
|
8
|
+
/** Uniforms que o renderer põe em todo shader de superfície. */
|
|
9
|
+
export declare const MESH_UNIFORMS: string[];
|
|
10
|
+
export declare function meshVertexPrelude(def: ShaderDef): string;
|
|
11
|
+
/** Vertex padrão. `#include<bonesVertex>` aplica o esqueleto (GLB animado); sem esqueleto vira nada. */
|
|
12
|
+
export declare const MESH_VERTEX = "void main() {\n mat4 finalWorld = world;\n#include<bonesVertex>\n vec4 wp = finalWorld * vec4(position, 1.0);\n vPosition = wp.xyz;\n vNormal = normalize(mat3(finalWorld) * normal);\n vUv = uv;\n gl_Position = viewProjection * wp;\n}";
|
|
13
|
+
export declare function meshFragmentPrelude(def: ShaderDef): string;
|
package/dist/shader.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Código GLSL no Babylon (#125, ADR-0010). Puro (sem Babylon). Pós-processamento usa o
|
|
3
|
+
* vertex `postprocess` do Babylon (`vUV`, `textureSampler`); superfície usa o vertex abaixo.
|
|
4
|
+
* A saída é `layout(location = 0) out vec4 finalColor`: com ela o Babylon não declara a dele.
|
|
5
|
+
*/
|
|
6
|
+
import { uniformDeclarations } from '@vibe-engine/core';
|
|
7
|
+
export function postPrelude(def) {
|
|
8
|
+
return [
|
|
9
|
+
'precision highp float;',
|
|
10
|
+
'layout(location = 0) out vec4 finalColor;',
|
|
11
|
+
'in vec2 vUV;',
|
|
12
|
+
'uniform sampler2D textureSampler;',
|
|
13
|
+
'uniform float time;',
|
|
14
|
+
'uniform vec2 uTexel;',
|
|
15
|
+
'uniform vec2 uScreen;',
|
|
16
|
+
'#define vUv vUV',
|
|
17
|
+
'#define vArea vUV',
|
|
18
|
+
'#define uTexture textureSampler',
|
|
19
|
+
'vec2 areaToUv(vec2 a) { return a; }',
|
|
20
|
+
...uniformDeclarations(def),
|
|
21
|
+
].join('\n');
|
|
22
|
+
}
|
|
23
|
+
/** Uniforms que o renderer põe em todo shader de superfície. */
|
|
24
|
+
export const MESH_UNIFORMS = ['world', 'viewProjection', 'time', 'uColor', 'uLightDir', 'uLightColor', 'uAmbient', 'uCameraPos'];
|
|
25
|
+
const meshCommon = (def) => [
|
|
26
|
+
'precision highp float;',
|
|
27
|
+
'uniform mat4 world;',
|
|
28
|
+
'uniform mat4 viewProjection;',
|
|
29
|
+
'uniform float time;',
|
|
30
|
+
'uniform vec4 uColor;',
|
|
31
|
+
'uniform sampler2D uTexture;',
|
|
32
|
+
'uniform vec3 uLightDir;',
|
|
33
|
+
'uniform vec3 uLightColor;',
|
|
34
|
+
'uniform vec3 uAmbient;',
|
|
35
|
+
'uniform vec3 uCameraPos;',
|
|
36
|
+
...uniformDeclarations(def),
|
|
37
|
+
];
|
|
38
|
+
export function meshVertexPrelude(def) {
|
|
39
|
+
return [...meshCommon(def), '#include<bonesDeclaration>', 'in vec3 position;', 'in vec3 normal;', 'in vec2 uv;', 'out vec2 vUv;', 'out vec3 vNormal;', 'out vec3 vPosition;'].join('\n');
|
|
40
|
+
}
|
|
41
|
+
/** Vertex padrão. `#include<bonesVertex>` aplica o esqueleto (GLB animado); sem esqueleto vira nada. */
|
|
42
|
+
export const MESH_VERTEX = `void main() {
|
|
43
|
+
mat4 finalWorld = world;
|
|
44
|
+
#include<bonesVertex>
|
|
45
|
+
vec4 wp = finalWorld * vec4(position, 1.0);
|
|
46
|
+
vPosition = wp.xyz;
|
|
47
|
+
vNormal = normalize(mat3(finalWorld) * normal);
|
|
48
|
+
vUv = uv;
|
|
49
|
+
gl_Position = viewProjection * wp;
|
|
50
|
+
}`;
|
|
51
|
+
export function meshFragmentPrelude(def) {
|
|
52
|
+
return [...meshCommon(def), 'layout(location = 0) out vec4 finalColor;', 'in vec2 vUv;', 'in vec3 vNormal;', 'in vec3 vPosition;'].join('\n');
|
|
53
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vibe-engine/renderer-3d",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "vibe-engine 3D renderer (Babylon.js)",
|
|
5
|
+
"license": "MIT OR Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/sergiobanhos/vibe-engine.git",
|
|
9
|
+
"directory": "packages/renderer-3d"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/sergiobanhos/vibe-engine#readme",
|
|
12
|
+
"keywords": [
|
|
13
|
+
"game-engine",
|
|
14
|
+
"ecs",
|
|
15
|
+
"typescript",
|
|
16
|
+
"headless",
|
|
17
|
+
"ai-native",
|
|
18
|
+
"vibe-engine"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=24"
|
|
22
|
+
},
|
|
23
|
+
"type": "module",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"default": "./dist/index.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"@babylonjs/core": "9.38.0",
|
|
32
|
+
"@babylonjs/loaders": "9.38.0",
|
|
33
|
+
"@vibe-engine/3d": "0.1.0",
|
|
34
|
+
"@vibe-engine/core": "0.1.0"
|
|
35
|
+
},
|
|
36
|
+
"files": [
|
|
37
|
+
"dist",
|
|
38
|
+
"LICENSE-MIT",
|
|
39
|
+
"LICENSE-APACHE",
|
|
40
|
+
"README.md"
|
|
41
|
+
],
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
}
|
|
6
45
|
}
|