-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFragmentPool.ts
More file actions
320 lines (281 loc) · 9.87 KB
/
Copy pathFragmentPool.ts
File metadata and controls
320 lines (281 loc) · 9.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import { Entity, Vector3, RigidBodyType, World, Vector3Like, EntityOptions, ColliderShape, CollisionGroup } from 'hytopia';
import { FragmentTextureManager } from './FragmentTextureManager';
/**
* Fragment Pool System - Optimizes fragment entity management by reusing entities
* instead of constantly creating and destroying them.
*/
export class FragmentPool {
private static _instance: FragmentPool;
private _pool: Entity[] = [];
private _activeFragments: Map<Entity, NodeJS.Timeout> = new Map();
private _poolSize: number;
private _world: World | null = null;
// Fragment configuration
private readonly _fragmentOptions: Partial<EntityOptions> = {
blockHalfExtents: { x: 0.15, y: 0.15, z: 0.15 },
rigidBodyOptions: {
type: RigidBodyType.DYNAMIC,
gravityScale: 0.8,
colliders: [{
shape: ColliderShape.BLOCK, // Block shape
halfExtents: { x: 0.15, y: 0.15, z: 0.15 },
isSensor: true
}]
}
};
private constructor(poolSize: number = 50) {
this._poolSize = poolSize;
}
/**
* Get the singleton instance of the FragmentPool
*/
public static getInstance(poolSize?: number): FragmentPool {
if (!FragmentPool._instance) {
FragmentPool._instance = new FragmentPool(poolSize);
}
return FragmentPool._instance;
}
/**
* Initialize the pool with a world instance
*/
public initialize(world: World): void {
this._world = world;
this._preallocateFragments();
}
/**
* Pre-allocate fragment entities to the pool
*/
private _preallocateFragments(): void {
if (!this._world) {
console.error('[FragmentPool] Cannot preallocate - world not set');
return;
}
console.log(`[FragmentPool] Pre-allocating ${this._poolSize} fragments...`);
for (let i = 0; i < this._poolSize; i++) {
const fragment = new Entity({
...this._fragmentOptions,
blockTextureUri: 'blocks/stone.png' // Default texture
});
// Spawn the fragment at a far-away position initially
fragment.spawn(this._world, { x: 0, y: -1000, z: 0 });
fragment.setCollisionGroupsForSolidColliders({
belongsTo: [],
collidesWith: []
});
this._pool.push(fragment);
}
console.log(`[FragmentPool] Successfully pre-allocated ${this._pool.length} fragments`);
}
/**
* Get a fragment from the pool
*/
public getFragment(
position: Vector3Like,
textureUri: string,
velocity: Vector3Like,
angularVelocity: Vector3Like,
durationMs: number = 1500
): Entity | null {
if (!this._world) {
console.error('[FragmentPool] Cannot get fragment - world not set');
return null;
}
// Create a new fragment with the specified texture
// Note: Block textures cannot be changed after creation, so we create new fragments
let fragment: Entity;
try {
fragment = new Entity({
...this._fragmentOptions,
blockTextureUri: textureUri
});
fragment.spawn(this._world, position);
} catch (error) {
console.error('[FragmentPool] Failed to create/spawn fragment:', error);
return null; // Return null if creation fails
}
// Configure the fragment
try {
// Reset and position the fragment
fragment.setPosition(position);
fragment.setLinearVelocity(velocity);
fragment.setAngularVelocity(angularVelocity);
// Re-enable collisions
fragment.setCollisionGroupsForSolidColliders({
belongsTo: [CollisionGroup.ENTITY],
collidesWith: [CollisionGroup.BLOCK, CollisionGroup.ENTITY]
});
// Set up auto-return timer
const timer = setTimeout(() => {
this.returnFragment(fragment);
}, durationMs);
this._activeFragments.set(fragment, timer);
return fragment;
} catch (error) {
console.error('[FragmentPool] Error configuring fragment:', error);
// Return fragment to pool if configuration failed
this._pool.push(fragment);
return null;
}
}
/**
* Return a fragment to the pool
*/
public returnFragment(fragment: Entity): void {
if (!fragment || !fragment.isSpawned) {
return;
}
// Clear any existing timer
const timer = this._activeFragments.get(fragment);
if (timer) {
clearTimeout(timer);
this._activeFragments.delete(fragment);
}
try {
// Reset fragment state
fragment.setLinearVelocity({ x: 0, y: 0, z: 0 });
fragment.setAngularVelocity({ x: 0, y: 0, z: 0 });
// Move to a far-away position
fragment.setPosition({ x: 0, y: -1000, z: 0 });
// Disable collisions (empty arrays are acceptable for pooled entities)
fragment.setCollisionGroupsForSolidColliders({
belongsTo: [],
collidesWith: []
});
// Return to pool
this._pool.push(fragment);
} catch (error) {
console.error('[FragmentPool] Error returning fragment to pool:', error);
}
}
/**
* Spawn break effect using pooled fragments with enhanced physics
*/
public spawnBreakEffect(
position: Vector3Like,
textureUri: string,
fragmentCount: number = 4,
durationMs: number = 1500,
baseVelocity: number = 3.0,
angularSpeed: number = 2.0,
effectType: 'default' | 'explosive' | 'implosion' | 'spiral' = 'default'
): void {
console.log(`[FragmentPool] Spawning ${fragmentCount} fragments at ${JSON.stringify(position)} with effect: ${effectType}`);
// Get varied textures for fragments
const fragmentTextures = FragmentTextureManager.getInstance().getFragmentTextures(textureUri, fragmentCount);
for (let i = 0; i < fragmentCount; i++) {
let velocity: Vector3Like;
let angularVelocity: Vector3Like;
switch (effectType) {
case 'explosive':
// Explosive effect - fragments fly outward with high velocity
const explosiveAngle = (i / fragmentCount) * Math.PI * 2;
const explosiveY = Math.random() * 0.5 + 0.5; // Upward bias
velocity = {
x: Math.cos(explosiveAngle) * baseVelocity * 2,
y: explosiveY * baseVelocity * 2.5,
z: Math.sin(explosiveAngle) * baseVelocity * 2
};
angularVelocity = {
x: (Math.random() - 0.5) * angularSpeed * 3,
y: (Math.random() - 0.5) * angularSpeed * 3,
z: (Math.random() - 0.5) * angularSpeed * 3
};
break;
case 'implosion':
// Implosion effect - fragments move inward then outward
const implosionAngle = (i / fragmentCount) * Math.PI * 2;
velocity = {
x: -Math.cos(implosionAngle) * baseVelocity * 0.5,
y: Math.random() * baseVelocity,
z: -Math.sin(implosionAngle) * baseVelocity * 0.5
};
// Schedule velocity reversal
setTimeout(() => {
const fragment = this.getFragment(position, textureUri, {
x: Math.cos(implosionAngle) * baseVelocity * 1.5,
y: baseVelocity * 2,
z: Math.sin(implosionAngle) * baseVelocity * 1.5
}, angularVelocity, durationMs - 200);
}, 200);
continue; // Skip this iteration
case 'spiral':
// Spiral effect - fragments move in a spiral pattern
const spiralAngle = (i / fragmentCount) * Math.PI * 2;
const spiralTime = i / fragmentCount;
velocity = {
x: Math.cos(spiralAngle + spiralTime * Math.PI) * baseVelocity,
y: baseVelocity * (1 + spiralTime),
z: Math.sin(spiralAngle + spiralTime * Math.PI) * baseVelocity
};
angularVelocity = {
x: Math.cos(spiralAngle) * angularSpeed,
y: angularSpeed * 2,
z: Math.sin(spiralAngle) * angularSpeed
};
break;
default:
// Default random direction
const dirX = Math.random() - 0.5;
const dirY = Math.random() - 0.5;
const dirZ = Math.random() - 0.5;
const length = Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ);
const normX = length === 0 ? 0 : dirX / length;
const normY = length === 0 ? 1 : dirY / length;
const normZ = length === 0 ? 0 : dirZ / length;
velocity = {
x: normX * baseVelocity * (0.5 + Math.random() * 0.5),
y: normY * baseVelocity * (0.5 + Math.random() * 0.5),
z: normZ * baseVelocity * (0.5 + Math.random() * 0.5)
};
angularVelocity = {
x: (Math.random() - 0.5) * angularSpeed,
y: (Math.random() - 0.5) * angularSpeed,
z: (Math.random() - 0.5) * angularSpeed
};
}
// Get fragment from pool with varied texture
const fragmentTexture = fragmentTextures[i] || textureUri;
const fragment = this.getFragment(
position,
fragmentTexture,
velocity,
angularVelocity,
durationMs
);
if (!fragment) {
console.warn(`[FragmentPool] Failed to get fragment ${i + 1}/${fragmentCount}`);
}
}
}
/**
* Clean up the pool
*/
public cleanup(): void {
console.log('[FragmentPool] Cleaning up fragment pool...');
// Clear all active fragments
this._activeFragments.forEach((timer, fragment) => {
clearTimeout(timer);
if (fragment.isSpawned) {
fragment.despawn();
}
});
this._activeFragments.clear();
// Despawn all pooled fragments
this._pool.forEach(fragment => {
if (fragment.isSpawned) {
fragment.despawn();
}
});
this._pool = [];
}
/**
* Get pool statistics
*/
public getStats(): { pooled: number, active: number, total: number } {
return {
pooled: this._pool.length,
active: this._activeFragments.size,
total: this._pool.length + this._activeFragments.size
};
}
}