three-base 2.0.188 → 2.0.192

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/MeshBase.ts CHANGED
@@ -1,257 +1,301 @@
1
- /*
2
- * @Author: xiaosihan
3
- * @Date: 2022-02-24 22:49:42
4
- * @Last Modified by: xiaosihan
5
- * @Last Modified time: 2025-06-25
6
- */
7
- import { AnimationAction, AnimationClip, AnimationMixer, Clock, Group, Mesh, Object3D, Vector3 } from "three";
8
- import threeUtils from "./threeUtils";
9
- import threeLoader from "./threeLoader";
10
- import * as SkeletonUtils from "three/examples/jsm/utils/SkeletonUtils";
11
- import { isString } from "lodash";
12
- import { dispatchCustomEvent } from "./EventMap";
13
-
14
- // 模型基类
15
- export default class MeshBase extends Group {
16
- constructor(url?: string) {
17
- super();
18
- url && this.loadModel(url);
19
- }
20
-
21
- url: string = "";
22
- // 模型对象
23
- static models: Map<string, Object3D> = new Map();
24
- // 模型是否在加载中
25
- static loadModeling: Map<string, boolean> = new Map();
26
- // 加载完成
27
- loaded: boolean = false;
28
- // 是否有动画
29
- hasAnimation: boolean = false;
30
- //动画混合器
31
- mixer?: AnimationMixer;
32
- //动画剪辑对象数组
33
- animationActions: {
34
- [key: string]: AnimationAction;
35
- } = {};
36
- // 获取文件名的后缀
37
- getSuffix(filename: string): string {
38
- const match = filename.match(/\.([^\.]+)$/);
39
- return match ? match[1].toLowerCase() : "";
40
- }
41
- reset(...object: Object3D[]): this {
42
- threeUtils.dipose(this);
43
- for (const child of this.children) {
44
- child.parent = null;
45
- }
46
- for (const item of object) {
47
- this.add(item);
48
- }
49
- return this;
50
- }
51
- // 兜底:为缺失顶点法线的几何体计算法线。
52
- // 某些 glb/stl 模型仅有 POSITION 没有 NORMAL(如 public/models/bottle.glb),
53
- // 会让法线 pass 输出零向量 -> AO 算出 NaN -> 整片被乘黑,且 PBR 金属材质无法正确受光 -> 发黑。
54
- // 在加载完成后统一兜底,保证光照与 AO 都正确;已含法线的模型不受影响。
55
- protected ensureNormals(root: Object3D): void {
56
- root.traverse((obj) => {
57
- if (obj instanceof Mesh && obj.geometry && !obj.geometry.getAttribute("normal")) {
58
- obj.geometry.computeVertexNormals();
59
- }
60
- });
61
- }
62
- // 如果url 是blob地址的话,就用suffix字段来制定模型的类型
63
- async loadModel(url: string | File | Array<File>, filename: string = ""): Promise<void> {
64
- //获取模型文件的地址
65
- const modelurl = await (async (): Promise<string> => {
66
- if (isString(url)) {
67
- return url;
68
- }
69
- else if (url instanceof File) {
70
- return url.name;
71
- }
72
- else if (url instanceof Array) {
73
- let modelurl = "";
74
- const suffixs = [
75
- "zip",
76
- "obj",
77
- "glb",
78
- "gltf",
79
- "fbx",
80
- "dae",
81
- "stl",
82
- "usdz",
83
- ];
84
- for (let file of url) {
85
- if (suffixs.includes(threeUtils.getSuffix(file.name))) {
86
- modelurl = file.name;
87
- }
88
- }
89
- return modelurl;
90
- }
91
- return "";
92
- })();
93
- this.url = modelurl || "";
94
- if (!modelurl) {
95
- return;
96
- }
97
- this.loaded = false;
98
- // 没有模型并且没有加载任务时就去加载模型
99
- if (!MeshBase.models.get(modelurl) &&
100
- !MeshBase.loadModeling.get(modelurl)) {
101
- MeshBase.loadModeling.set(modelurl, true);
102
- // 万能加载器
103
- let modal = await threeLoader.loadModel(url, filename);
104
- MeshBase.models.set(modelurl, modal);
105
- MeshBase.loadModeling.set(modelurl, false);
106
- }
107
- // 如果模型还在加载中, 就等待模型加载完成
108
- do {
109
- await new Promise((resolve) => setTimeout(resolve, 50));
110
- } while (MeshBase.loadModeling.get(modelurl));
111
- if (MeshBase.models.get(modelurl)) {
112
- const mesh = MeshBase.models.get(modelurl)!;
113
- // 兜底:为缺失顶点法线的几何体补算法线。某些 glb/stl 模型只有 POSITION,
114
- // 没有 NORMAL,会导致:① 法线 pass 输出零向量 -> AO 算出 NaN -> 整片被乘黑;
115
- // ② PBR 金属材质无法正确光照 -> 颜色发黑。统一在加载后兜底,光照与 AO 都正确。
116
- this.ensureNormals(mesh);
117
- // 判断是否有动画
118
- this.hasAnimation = (mesh as Group & { animations: AnimationClip[] }).animations.length > 0;
119
- if (this.hasAnimation) {
120
- const model = SkeletonUtils.clone(mesh);
121
- this.mixer = new AnimationMixer(model);
122
- this.animationActions = {};
123
- (mesh as Group & { animations: AnimationClip[] }).animations.map((animation: AnimationClip) => {
124
- const animationAction = this.mixer!.clipAction(animation).play();
125
- animationAction.weight = 0;
126
- this.animationActions[animation.name] = animationAction;
127
- });
128
- this.reset(model);
129
- }
130
- else {
131
- this.reset(mesh.clone(true));
132
- }
133
- }
134
- // ⭐ 2026-10-09 皇上旨:走 threeUtils 公共 rAF 链,不再另起独立 rAF 回调
135
- await threeUtils.waitNextFrame();
136
- this.loaded = true;
137
- // 加载完成事件
138
- dispatchCustomEvent(this, { type: "loaded" });
139
- }
140
- // 超出绘制区域时不绘制
141
- frustumCulled: boolean = false;
142
- // 创建阴影
143
- castShadow: boolean = false;
144
- // 接受阴影
145
- receiveShadow: boolean = false;
146
- // promise.resole 队列
147
- resoles: Array<(value: void | PromiseLike<void>) => void> = [];
148
- // 等待加载加载完成
149
- async awaitLoaded(): Promise<void> {
150
- if (!this.loaded) {
151
- await new Promise<void>((resolve) => {
152
- if (this.resoles.length === 0) {
153
- (async () => {
154
- while (!this.loaded) {
155
- //⭐ 2026-10-09 皇上旨「整条 rAF 链只走 threeUtils 一条」:
156
- // 原生 rAF 是**独立于主循环的另一个回调**,同一帧并行跑;
157
- // 模型多时(十几个 GLB 同时 awaitLoaded)每帧多十几个回调 ⇒ 卡顿。
158
- await threeUtils.waitNextFrame();
159
- }
160
- while (this.resoles.length > 0) {
161
- const resole = this.resoles.pop();
162
- resole && resole();
163
- }
164
- })();
165
- }
166
- this.resoles.unshift(resolve);
167
- });
168
- }
169
- }
170
- //遍历模型
171
- async traverseMesh(callback: (mesh: Mesh) => void): Promise<void> {
172
- // 等待加载完成
173
- await this.awaitLoaded();
174
- this.traverse((obj) => {
175
- if (obj instanceof Mesh) {
176
- callback(obj);
177
- }
178
- });
179
- }
180
- clock: Clock = new Clock();
181
- //设置动画的权重
182
- async setClipActionWeight(weights: {
183
- [key: string]: number;
184
- } = {}): Promise<void> {
185
- // 等待加载完成
186
- await this.awaitLoaded();
187
- for (let key in this.animationActions) {
188
- this.animationActions[key].weight = weights[key] || 0;
189
- }
190
- }
191
- //获取动画列表
192
- getAnimas(): string[] {
193
- return Object.keys(this.animationActions);
194
- }
195
- //播放指定动画
196
- setAnimas(anima: string = ""): void {
197
- this.setClipActionWeight({ [anima]: 1 });
198
- }
199
- //停止所有动画
200
- stop(): void {
201
- this.setClipActionWeight();
202
- }
203
- updateMatrix(): void {
204
- //播放动画
205
- if (this.mixer) {
206
- this.mixer.update(this.clock.getDelta());
207
- }
208
- // 深度应用属性
209
- this.traverse((obj) => {
210
- if (obj instanceof Mesh) {
211
- obj.frustumCulled = this.frustumCulled;
212
- obj.castShadow = this.castShadow;
213
- obj.receiveShadow = this.receiveShadow;
214
- }
215
- });
216
- super.updateMatrix();
217
- }
218
- // 获取模型的尺寸
219
- async getSize(): Promise<Vector3> {
220
- await this.awaitLoaded();
221
- return threeUtils.getSize(this);
222
- }
223
- // 居中
224
- async center(): Promise<void> {
225
- await this.awaitLoaded();
226
- threeUtils.center(this);
227
- }
228
- //底对齐
229
- async alignBottom(y: number = 0): Promise<void> {
230
- await this.awaitLoaded();
231
- threeUtils.alignBottom(this, y);
232
- }
233
- // 放大到指定尺寸
234
- async scaleTo(size: number = 1, key: Array<"x" | "y" | "z"> = ["x", "y", "z"]): Promise<void> {
235
- await this.awaitLoaded();
236
- threeUtils.scaleTo(this, size, key);
237
- }
238
- //按照法线拓展
239
- expandBynormal(length: number): void {
240
- this.traverseMesh((mesh) => {
241
- // 没有法线就计算法线
242
- mesh.geometry = mesh.geometry.clone();
243
- if (!mesh.geometry.getAttribute("normal")) {
244
- mesh.geometry.computeVertexNormals();
245
- }
246
- const normal = mesh.geometry.getAttribute("normal");
247
- const position = mesh.geometry.getAttribute("position");
248
- const v3 = new Vector3(0, 0, 0);
249
- for (let i = 0; i < position.count; i++) {
250
- v3.set(normal.getX(i), normal.getY(i), normal.getZ(i));
251
- v3.setLength(length);
252
- position.setXYZ(i, position.getX(i) + v3.x, position.getY(i) + v3.y, position.getZ(i) + v3.z);
253
- }
254
- position.needsUpdate = true;
255
- });
256
- }
257
- }
1
+ /*
2
+ * @Author: xiaosihan
3
+ * @Date: 2022-02-24 22:49:42
4
+ * @Last Modified by: xiaosihan
5
+ * @Last Modified time: 2025-06-25
6
+ */
7
+ import { AnimationAction, AnimationClip, AnimationMixer, Clock, Group, Mesh, Object3D, Vector3 } from "three";
8
+ import threeUtils from "./threeUtils";
9
+ import threeLoader from "./threeLoader";
10
+ import * as SkeletonUtils from "three/examples/jsm/utils/SkeletonUtils";
11
+ import { isString } from "lodash";
12
+ import { dispatchCustomEvent } from "./EventMap";
13
+
14
+ // 模型基类
15
+ export default class MeshBase extends Group {
16
+ constructor(url?: string) {
17
+ super();
18
+ url && this.loadModel(url);
19
+ }
20
+
21
+ url: string = "";
22
+ // 模型对象
23
+ static models: Map<string, Object3D> = new Map();
24
+ // 模型是否在加载中
25
+ static loadModeling: Map<string, boolean> = new Map();
26
+ // 加载完成
27
+ loaded: boolean = false;
28
+ // 是否有动画
29
+ hasAnimation: boolean = false;
30
+ //动画混合器
31
+ mixer?: AnimationMixer;
32
+ //动画剪辑对象数组
33
+ animationActions: {
34
+ [key: string]: AnimationAction;
35
+ } = {};
36
+ // 获取文件名的后缀
37
+ getSuffix(filename: string): string {
38
+ const match = filename.match(/\.([^\.]+)$/);
39
+ return match ? match[1].toLowerCase() : "";
40
+ }
41
+ reset(...object: Object3D[]): this {
42
+ threeUtils.dipose(this);
43
+ for (const child of this.children) {
44
+ child.parent = null;
45
+ }
46
+ for (const item of object) {
47
+ this.add(item);
48
+ }
49
+ return this;
50
+ }
51
+ /** 「压着等放行」的内容子对象在册表(摘牌 = 从这里删掉,放行那一拍便不再写它的 `visible`) */
52
+ private readonly _revealPending = new Set<Object3D>();
53
+ /**
54
+ * ⭐ 2026-10-28「这个方案也可以用在 MeshBase 对象上面,让每个模型对象都逐帧显示出来,就不用一起阻塞了」:
55
+ * 刚进场景图的这几颗内容先压住,再交给 `threeUtils` 的全局队列 —— 那一拍每帧只跑一项
56
+ * (`requestAnimationFrame()` 里 `workList.splice(0, 1)`),且派发点在渲染之后 ⇒ 一帧只放行一个对象,
57
+ * 它下一帧才被真画出来。几十只模型同时落地时,「顶点缓冲上传 + 首次 program 编译」(都发生在真被画的
58
+ * 那一帧)就摊到几十帧上,不再是进门那一下的一整卡。
59
+ * ⚠️ 压的是**内容子对象**的 `visible`,⛔ 不是 MeshBase 自己:`ManyModelGroup.setDatas` 拿 MeshBase 的
60
+ * `visible` 当「这条数据还在不在」的筛子 ⇒ 那个旋钮归消费者,这里不许占用。
61
+ * ⚠️ 只压「这一次新加进来的」那几颗 ⇒ 换模型(`reset`)时不会把旁边早已点亮的内容一起按下去。
62
+ * ⚠️ ⛔ 别改成「每颗在自己的 `onBeforeRender` 里轮询 loaded」:three 的 `projectObject` 第一句就是
63
+ * `if (object.visible === false) return;`(`node_modules/three/build/three.module.js:29837`)⇒
64
+ * 隐形对象一次回调都收不到,自己等自己 = 永远不亮。
65
+ * ⚠️ `visible` 是业务的旋钮,这里只是**借一下**:进场时就压着的那几颗⛔ 不收进这一轮(不替别人放开);
66
+ * 要在放行之前接管某颗,调 `releaseReveal(item)` 摘牌 ⇒ 放行那一拍跳过它,`visible` 归调用方。
67
+ */
68
+ protected revealSoon(items: Object3D[]): void {
69
+ const held: Object3D[] = [];
70
+ for (const item of items) {
71
+ if (!item.visible) continue; // 本来就压着 ⇒ 显隐归业务,⛔ 不收进这一轮、也不替它放开
72
+ item.visible = false;
73
+ this._revealPending.add(item);
74
+ held.push(item);
75
+ }
76
+ if (!held.length) return;
77
+ threeUtils.addWork(() => {
78
+ for (const item of held) {
79
+ if (!this._revealPending.delete(item)) continue; // 已被摘牌 ⇒ 这一拍不碰它的 visible
80
+ item.visible = true;
81
+ }
82
+ });
83
+ }
84
+
85
+ /**
86
+ * 把某颗内容的显隐控制权交回调用方(2026-10-28:`visible` 上有业务在用,加载窗口期内写的那一笔⛔ 不能被
87
+ * 放行那一拍覆盖)。摘牌后它**仍是压着的**(`false`),要它可见就自己写 `true`。
88
+ */
89
+ releaseReveal(item: Object3D): void {
90
+ this._revealPending.delete(item);
91
+ }
92
+ // 兜底:为缺失顶点法线的几何体计算法线。
93
+ // 某些 glb/stl 模型仅有 POSITION 没有 NORMAL(如 public/models/bottle.glb),
94
+ // 会让法线 pass 输出零向量 -> AO 算出 NaN -> 整片被乘黑,且 PBR 金属材质无法正确受光 -> 发黑。
95
+ // 在加载完成后统一兜底,保证光照与 AO 都正确;已含法线的模型不受影响。
96
+ protected ensureNormals(root: Object3D): void {
97
+ root.traverse((obj) => {
98
+ if (obj instanceof Mesh && obj.geometry && !obj.geometry.getAttribute("normal")) {
99
+ obj.geometry.computeVertexNormals();
100
+ }
101
+ });
102
+ }
103
+ // 如果url 是blob地址的话,就用suffix字段来制定模型的类型
104
+ async loadModel(url: string | File | Array<File>, filename: string = ""): Promise<void> {
105
+ //获取模型文件的地址
106
+ const modelurl = await (async (): Promise<string> => {
107
+ if (isString(url)) {
108
+ return url;
109
+ }
110
+ else if (url instanceof File) {
111
+ return url.name;
112
+ }
113
+ else if (url instanceof Array) {
114
+ let modelurl = "";
115
+ const suffixs = [
116
+ "zip",
117
+ "obj",
118
+ "glb",
119
+ "gltf",
120
+ "fbx",
121
+ "dae",
122
+ "stl",
123
+ "usdz",
124
+ ];
125
+ for (let file of url) {
126
+ if (suffixs.includes(threeUtils.getSuffix(file.name))) {
127
+ modelurl = file.name;
128
+ }
129
+ }
130
+ return modelurl;
131
+ }
132
+ return "";
133
+ })();
134
+ this.url = modelurl || "";
135
+ if (!modelurl) {
136
+ return;
137
+ }
138
+ this.loaded = false;
139
+ // 没有模型并且没有加载任务时就去加载模型
140
+ if (!MeshBase.models.get(modelurl) &&
141
+ !MeshBase.loadModeling.get(modelurl)) {
142
+ MeshBase.loadModeling.set(modelurl, true);
143
+ // 万能加载器
144
+ let modal = await threeLoader.loadModel(url, filename);
145
+ MeshBase.models.set(modelurl, modal);
146
+ MeshBase.loadModeling.set(modelurl, false);
147
+ }
148
+ // 如果模型还在加载中, 就等待模型加载完成
149
+ do {
150
+ await new Promise((resolve) => setTimeout(resolve, 50));
151
+ } while (MeshBase.loadModeling.get(modelurl));
152
+ if (MeshBase.models.get(modelurl)) {
153
+ const mesh = MeshBase.models.get(modelurl)!;
154
+ // 兜底:为缺失顶点法线的几何体补算法线。某些 glb/stl 模型只有 POSITION,
155
+ // 没有 NORMAL,会导致:① 法线 pass 输出零向量 -> AO 算出 NaN -> 整片被乘黑;
156
+ // ② PBR 金属材质无法正确光照 -> 颜色发黑。统一在加载后兜底,光照与 AO 都正确。
157
+ this.ensureNormals(mesh);
158
+ // 判断是否有动画
159
+ this.hasAnimation = (mesh as Group & { animations: AnimationClip[] }).animations.length > 0;
160
+ if (this.hasAnimation) {
161
+ const model = SkeletonUtils.clone(mesh);
162
+ this.mixer = new AnimationMixer(model);
163
+ this.animationActions = {};
164
+ (mesh as Group & { animations: AnimationClip[] }).animations.map((animation: AnimationClip) => {
165
+ const animationAction = this.mixer!.clipAction(animation).play();
166
+ animationAction.weight = 0;
167
+ this.animationActions[animation.name] = animationAction;
168
+ });
169
+ this.reset(model);
170
+ this.revealSoon([model]);
171
+ }
172
+ else {
173
+ const clone = mesh.clone(true);
174
+ this.reset(clone);
175
+ this.revealSoon([clone]);
176
+ }
177
+ }
178
+ // ⭐ 2026-10-09 皇上旨:走 threeUtils 公共 rAF 链,不再另起独立 rAF 回调
179
+ await threeUtils.waitNextFrame();
180
+ this.loaded = true;
181
+ // 加载完成事件
182
+ dispatchCustomEvent(this, { type: "loaded" });
183
+ }
184
+ // 超出绘制区域时不绘制
185
+ frustumCulled: boolean = false;
186
+ // 创建阴影
187
+ castShadow: boolean = false;
188
+ // 接受阴影
189
+ receiveShadow: boolean = false;
190
+ // promise.resole 队列
191
+ resoles: Array<(value: void | PromiseLike<void>) => void> = [];
192
+ // 等待加载加载完成
193
+ async awaitLoaded(): Promise<void> {
194
+ if (!this.loaded) {
195
+ await new Promise<void>((resolve) => {
196
+ if (this.resoles.length === 0) {
197
+ (async () => {
198
+ while (!this.loaded) {
199
+ //⭐ 2026-10-09 皇上旨「整条 rAF 链只走 threeUtils 一条」:
200
+ // 原生 rAF 是**独立于主循环的另一个回调**,同一帧并行跑;
201
+ // 模型多时(十几个 GLB 同时 awaitLoaded)每帧多十几个回调 ⇒ 卡顿。
202
+ await threeUtils.waitNextFrame();
203
+ }
204
+ while (this.resoles.length > 0) {
205
+ const resole = this.resoles.pop();
206
+ resole && resole();
207
+ }
208
+ })();
209
+ }
210
+ this.resoles.unshift(resolve);
211
+ });
212
+ }
213
+ }
214
+ //遍历模型
215
+ async traverseMesh(callback: (mesh: Mesh) => void): Promise<void> {
216
+ // 等待加载完成
217
+ await this.awaitLoaded();
218
+ this.traverse((obj) => {
219
+ if (obj instanceof Mesh) {
220
+ callback(obj);
221
+ }
222
+ });
223
+ }
224
+ clock: Clock = new Clock();
225
+ //设置动画的权重
226
+ async setClipActionWeight(weights: {
227
+ [key: string]: number;
228
+ } = {}): Promise<void> {
229
+ // 等待加载完成
230
+ await this.awaitLoaded();
231
+ for (let key in this.animationActions) {
232
+ this.animationActions[key].weight = weights[key] || 0;
233
+ }
234
+ }
235
+ //获取动画列表
236
+ getAnimas(): string[] {
237
+ return Object.keys(this.animationActions);
238
+ }
239
+ //播放指定动画
240
+ setAnimas(anima: string = ""): void {
241
+ this.setClipActionWeight({ [anima]: 1 });
242
+ }
243
+ //停止所有动画
244
+ stop(): void {
245
+ this.setClipActionWeight();
246
+ }
247
+ updateMatrix(): void {
248
+ //播放动画
249
+ if (this.mixer) {
250
+ this.mixer.update(this.clock.getDelta());
251
+ }
252
+ // 深度应用属性
253
+ this.traverse((obj) => {
254
+ if (obj instanceof Mesh) {
255
+ obj.frustumCulled = this.frustumCulled;
256
+ obj.castShadow = this.castShadow;
257
+ obj.receiveShadow = this.receiveShadow;
258
+ }
259
+ });
260
+ super.updateMatrix();
261
+ }
262
+ // 获取模型的尺寸
263
+ async getSize(): Promise<Vector3> {
264
+ await this.awaitLoaded();
265
+ return threeUtils.getSize(this);
266
+ }
267
+ // 居中
268
+ async center(): Promise<void> {
269
+ await this.awaitLoaded();
270
+ threeUtils.center(this);
271
+ }
272
+ //底对齐
273
+ async alignBottom(y: number = 0): Promise<void> {
274
+ await this.awaitLoaded();
275
+ threeUtils.alignBottom(this, y);
276
+ }
277
+ // 放大到指定尺寸
278
+ async scaleTo(size: number = 1, key: Array<"x" | "y" | "z"> = ["x", "y", "z"]): Promise<void> {
279
+ await this.awaitLoaded();
280
+ threeUtils.scaleTo(this, size, key);
281
+ }
282
+ //按照法线拓展
283
+ expandBynormal(length: number): void {
284
+ this.traverseMesh((mesh) => {
285
+ // 没有法线就计算法线
286
+ mesh.geometry = mesh.geometry.clone();
287
+ if (!mesh.geometry.getAttribute("normal")) {
288
+ mesh.geometry.computeVertexNormals();
289
+ }
290
+ const normal = mesh.geometry.getAttribute("normal");
291
+ const position = mesh.geometry.getAttribute("position");
292
+ const v3 = new Vector3(0, 0, 0);
293
+ for (let i = 0; i < position.count; i++) {
294
+ v3.set(normal.getX(i), normal.getY(i), normal.getZ(i));
295
+ v3.setLength(length);
296
+ position.setXYZ(i, position.getX(i) + v3.x, position.getY(i) + v3.y, position.getZ(i) + v3.z);
297
+ }
298
+ position.needsUpdate = true;
299
+ });
300
+ }
301
+ }