forked from galacean/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLitePhysicsScene.ts
372 lines (342 loc) · 13.5 KB
/
LitePhysicsScene.ts
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import { BoundingBox, BoundingSphere, CollisionUtil, DisorderedArray, Ray, Vector3 } from "@galacean/engine";
import { ICharacterController, ICollision, IPhysicsScene } from "@galacean/engine-design";
import { LiteCollider } from "./LiteCollider";
import { LiteDynamicCollider } from "./LiteDynamicCollider";
import { LiteHitResult } from "./LiteHitResult";
import { LiteStaticCollider } from "./LiteStaticCollider";
import { LiteBoxColliderShape } from "./shape/LiteBoxColliderShape";
import { LiteColliderShape } from "./shape/LiteColliderShape";
import { LiteSphereColliderShape } from "./shape/LiteSphereColliderShape";
/**
* A manager is a collection of colliders and constraints which can interact.
*/
export class LitePhysicsScene implements IPhysicsScene {
private static _tempSphere: BoundingSphere = new BoundingSphere();
private static _tempBox: BoundingBox = new BoundingBox();
private static _currentHit: LiteHitResult = new LiteHitResult();
private static _hitResult: LiteHitResult = new LiteHitResult();
private readonly _onContactEnter?: (collision: ICollision) => void;
private readonly _onContactExit?: (collision: ICollision) => void;
private readonly _onContactStay?: (collision: ICollision) => void;
private readonly _onTriggerEnter?: (obj1: number, obj2: number) => void;
private readonly _onTriggerExit?: (obj1: number, obj2: number) => void;
private readonly _onTriggerStay?: (obj1: number, obj2: number) => void;
private _staticColliders: LiteStaticCollider[] = [];
private _dynamicColliders: LiteDynamicCollider[] = [];
private _sphere: BoundingSphere = new BoundingSphere();
private _box: BoundingBox = new BoundingBox();
private _currentEvents: DisorderedArray<TriggerEvent> = new DisorderedArray<TriggerEvent>();
private _eventMap: Record<number, Record<number, TriggerEvent>> = {};
private _eventPool: TriggerEvent[] = [];
constructor(
onContactEnter?: (collision: ICollision) => void,
onContactExit?: (collision: ICollision) => void,
onContactStay?: (collision: ICollision) => void,
onTriggerEnter?: (obj1: number, obj2: number) => void,
onTriggerExit?: (obj1: number, obj2: number) => void,
onTriggerStay?: (obj1: number, obj2: number) => void
) {
this._onContactEnter = onContactEnter;
this._onContactExit = onContactExit;
this._onContactStay = onContactStay;
this._onTriggerEnter = onTriggerEnter;
this._onTriggerExit = onTriggerExit;
this._onTriggerStay = onTriggerStay;
}
/**
* {@inheritDoc IPhysicsManager.setGravity }
*/
setGravity(value: Vector3): void {
console.log("Physics-lite don't support gravity. Use Physics-PhysX instead!");
}
/**
* {@inheritDoc IPhysicsManager.addCollider }
*/
addCollider(actor: LiteCollider): void {
actor._scene = this;
const colliders = actor._isStaticCollider ? this._staticColliders : this._dynamicColliders;
colliders.push(actor);
const shapes = actor._shapes;
for (let i = 0, n = shapes.length; i < n; i++) {
this._addColliderShape(shapes[i]);
}
}
/**
* {@inheritDoc IPhysicsManager.removeCollider }
*/
removeCollider(collider: LiteCollider): void {
collider._scene = null;
const colliders = collider._isStaticCollider ? this._staticColliders : this._dynamicColliders;
const index = colliders.indexOf(collider);
index > -1 && colliders.splice(index, 1);
const shapes = collider._shapes;
for (let i = 0, n = shapes.length; i < n; i++) {
this._removeColliderShape(shapes[i]);
}
}
/**
* {@inheritDoc IPhysicsManager.update }
*/
update(deltaTime: number): void {
const dynamicColliders = this._dynamicColliders;
for (let i = 0, len = dynamicColliders.length; i < len; i++) {
const collider = dynamicColliders[i];
this._collisionDetection(collider, this._staticColliders);
this._collisionDetection(collider, dynamicColliders);
}
this._fireEvent();
}
/**
* {@inheritDoc IPhysicsManager.raycast }
*/
raycast(
ray: Ray,
distance: number,
onRaycast: (obj: number) => boolean,
hit?: (shapeUniqueID: number, distance: number, position: Vector3, normal: Vector3) => void
): boolean {
if (!hit) {
return (
this._raycast(ray, distance, onRaycast, this._staticColliders, hit) ||
this._raycast(ray, distance, onRaycast, this._dynamicColliders, hit)
);
} else {
const raycastStaticRes = this._raycast(ray, distance, onRaycast, this._staticColliders, hit);
if (raycastStaticRes) {
distance = LitePhysicsScene._currentHit.distance;
}
const raycastDynamicRes = this._raycast(ray, distance, onRaycast, this._dynamicColliders, hit);
const isHit = raycastStaticRes || raycastDynamicRes;
const hitResult = LitePhysicsScene._hitResult;
if (!isHit) {
hitResult.shapeID = -1;
hitResult.distance = 0;
hitResult.point.set(0, 0, 0);
hitResult.normal.set(0, 0, 0);
} else {
hit(hitResult.shapeID, hitResult.distance, hitResult.point, hitResult.normal);
}
return isHit;
}
}
/**
* {@inheritDoc IPhysicsManager.addCharacterController }
*/
addCharacterController(characterController: ICharacterController): void {
throw "Physics-lite don't support addCharacterController. Use Physics-PhysX instead!";
}
/**
* {@inheritDoc IPhysicsManager.removeCharacterController }
*/
removeCharacterController(characterController: ICharacterController): void {
throw "Physics-lite don't support removeCharacterController. Use Physics-PhysX instead!";
}
/**
* @internal
*/
_addColliderShape(colliderShape: LiteColliderShape): void {
this._eventMap[colliderShape._id] = {};
}
/**
* @internal
*/
_removeColliderShape(colliderShape: LiteColliderShape): void {
const { _eventPool: eventPool, _currentEvents: currentEvents, _eventMap: eventMap } = this;
const { _id: id } = colliderShape;
currentEvents.forEach((event, i) => {
if (event.index1 == id) {
currentEvents.deleteByIndex(i);
eventPool.push(event);
} else if (event.index2 == id) {
currentEvents.deleteByIndex(i);
eventPool.push(event);
// If the shape is big index, should clear from the small index shape subMap
eventMap[event.index1][id] = undefined;
}
});
delete eventMap[id];
}
/**
* Calculate the bounding box in world space from boxCollider.
* @param boxCollider - The boxCollider to calculate
* @param out - The calculated boundingBox
*/
private static _updateWorldBox(boxCollider: LiteBoxColliderShape, out: BoundingBox): void {
const mat = boxCollider._transform.worldMatrix;
out.min.copyFrom(boxCollider._boxMin);
out.max.copyFrom(boxCollider._boxMax);
BoundingBox.transform(out, mat, out);
}
/**
* Get the sphere info of the given sphere collider in world space.
* @param sphereCollider - The given sphere collider
* @param out - The calculated boundingSphere
*/
private static _upWorldSphere(sphereCollider: LiteSphereColliderShape, out: BoundingSphere): void {
Vector3.transformCoordinate(sphereCollider._transform.position, sphereCollider._transform.worldMatrix, out.center);
out.radius = sphereCollider.worldRadius;
}
private _getTrigger(index1: number, index2: number): TriggerEvent {
let event: TriggerEvent;
if (this._eventPool.length) {
event = this._eventPool.pop();
event.index1 = index1;
event.index2 = index2;
} else {
event = new TriggerEvent(index1, index2);
}
this._eventMap[index1][index2] = event;
return event;
}
private _collisionDetection(myCollider: LiteCollider, colliders: LiteCollider[]): void {
const myColliderShapes = myCollider._shapes;
for (let i = 0, len = myColliderShapes.length; i < len; i++) {
const myShape = myColliderShapes[i];
if (myShape instanceof LiteBoxColliderShape) {
LitePhysicsScene._updateWorldBox(myShape, this._box);
for (let j = 0, len = colliders.length; j < len; j++) {
const colliderShape = colliders[j]._shapes;
for (let k = 0, len = colliderShape.length; k < len; k++) {
const shape = colliderShape[k];
const index1 = shape._id;
const index2 = myShape._id;
const event = index1 < index2 ? this._eventMap[index1][index2] : this._eventMap[index2][index1];
if (event !== undefined && !event.alreadyInvoked) {
continue;
}
if (shape != myShape && this._boxCollision(shape)) {
if (event === undefined) {
const event = index1 < index2 ? this._getTrigger(index1, index2) : this._getTrigger(index2, index1);
event.state = TriggerEventState.Enter;
event.alreadyInvoked = false;
this._currentEvents.add(event);
} else if (event.state === TriggerEventState.Enter) {
event.state = TriggerEventState.Stay;
event.alreadyInvoked = false;
} else if (event.state === TriggerEventState.Stay) {
event.alreadyInvoked = false;
}
}
}
}
} else if (myShape instanceof LiteSphereColliderShape) {
LitePhysicsScene._upWorldSphere(myShape, this._sphere);
for (let j = 0, len = colliders.length; j < len; j++) {
const colliderShape = colliders[j]._shapes;
for (let k = 0, len = colliderShape.length; k < len; k++) {
const shape = colliderShape[k];
const index1 = shape._id;
const index2 = myShape._id;
const event = index1 < index2 ? this._eventMap[index1][index2] : this._eventMap[index2][index1];
if (event !== undefined && !event.alreadyInvoked) {
continue;
}
if (shape != myShape && this._sphereCollision(shape)) {
if (event === undefined) {
const event = index1 < index2 ? this._getTrigger(index1, index2) : this._getTrigger(index2, index1);
event.state = TriggerEventState.Enter;
event.alreadyInvoked = false;
this._currentEvents.add(event);
} else if (event.state === TriggerEventState.Enter) {
event.state = TriggerEventState.Stay;
event.alreadyInvoked = false;
} else if (event.state === TriggerEventState.Stay) {
event.alreadyInvoked = false;
}
}
}
}
}
}
}
private _fireEvent(): void {
const { _eventPool: eventPool, _currentEvents: currentEvents } = this;
currentEvents.forEach((event, i) => {
if (!event.alreadyInvoked) {
if (event.state == TriggerEventState.Enter) {
this._onTriggerEnter(event.index1, event.index2);
event.alreadyInvoked = true;
} else if (event.state == TriggerEventState.Stay) {
this._onTriggerStay(event.index1, event.index2);
event.alreadyInvoked = true;
}
} else {
event.state = TriggerEventState.Exit;
this._eventMap[event.index1][event.index2] = undefined;
currentEvents.deleteByIndex(i);
this._onTriggerExit(event.index1, event.index2);
eventPool.push(event);
}
});
}
private _boxCollision(other: LiteColliderShape): boolean {
if (other instanceof LiteBoxColliderShape) {
const box = LitePhysicsScene._tempBox;
LitePhysicsScene._updateWorldBox(other, box);
return CollisionUtil.intersectsBoxAndBox(box, this._box);
} else if (other instanceof LiteSphereColliderShape) {
const sphere = LitePhysicsScene._tempSphere;
LitePhysicsScene._upWorldSphere(other, sphere);
return CollisionUtil.intersectsSphereAndBox(sphere, this._box);
}
return false;
}
private _sphereCollision(other: LiteColliderShape): boolean {
if (other instanceof LiteBoxColliderShape) {
const box = LitePhysicsScene._tempBox;
LitePhysicsScene._updateWorldBox(other, box);
return CollisionUtil.intersectsSphereAndBox(this._sphere, box);
} else if (other instanceof LiteSphereColliderShape) {
const sphere = LitePhysicsScene._tempSphere;
LitePhysicsScene._upWorldSphere(other, sphere);
return CollisionUtil.intersectsSphereAndSphere(sphere, this._sphere);
}
return false;
}
private _raycast(
ray: Ray,
distance: number,
onRaycast: (obj: number) => boolean,
colliders: LiteCollider[],
hit?: (shapeUniqueID: number, distance: number, position: Vector3, normal: Vector3) => void
): boolean {
let isHit = false;
const curHit = LitePhysicsScene._currentHit;
for (let i = 0, len = colliders.length; i < len; i++) {
if (colliders[i]._raycast(ray, onRaycast, curHit) && curHit.distance < distance) {
if (hit) {
isHit = true;
const hitResult = LitePhysicsScene._hitResult;
hitResult.normal.copyFrom(curHit.normal);
hitResult.point.copyFrom(curHit.point);
hitResult.distance = distance = curHit.distance;
hitResult.shapeID = curHit.shapeID;
} else {
return true;
}
}
}
return isHit;
}
}
/**
* Physics state
*/
enum TriggerEventState {
Enter,
Stay,
Exit
}
/**
* Trigger event to store interactive object ids and state.
*/
class TriggerEvent {
state: TriggerEventState;
index1: number;
index2: number;
alreadyInvoked: boolean = false;
constructor(index1: number, index2: number) {
this.index1 = index1;
this.index2 = index2;
}
}