-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSphereCollisionManager.cs
More file actions
333 lines (281 loc) · 13.9 KB
/
Copy pathSphereCollisionManager.cs
File metadata and controls
333 lines (281 loc) · 13.9 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
321
322
323
324
325
326
327
328
329
330
331
332
333
using System;
using System.Collections.Generic;
using System.Text;
using TgcViewer.Utils.TgcGeometry;
using Microsoft.DirectX;
using TgcViewer;
namespace AlumnoEjemplos.GODMODE
{
/// <summary>
/// Herramienta para realizar el movimiento de una Esfera con detección de colisiones,
/// efecto de Sliding y gravedad.
/// Basado en el paper de Kasper Fauerby
/// http://www.peroxide.dk/papers/collision/collision.pdf
/// Su utiliza una estrategia distinta al paper en el nivel más bajo de colisión.
/// No se analizan colisiones a nivel de tríangulo, sino que todo objeto se descompone
/// a nivel de un BoundingBox con 6 caras rectangulares.
///
/// </summary>
public class SphereCollisionManager
{
const float EPSILON = 0.005f;
//0.05f;
private Vector3 gravityForce;
/// <summary>
/// Vector que representa la fuerza de gravedad.
/// Debe tener un valor negativo en Y para que la fuerza atraiga hacia el suelo
/// </summary>
public Vector3 GravityForce
{
get { return gravityForce; }
set { gravityForce = value; }
}
private bool gravityEnabled;
/// <summary>
/// Habilita o deshabilita la aplicación de fuerza de gravedad
/// </summary>
public bool GravityEnabled
{
get { return gravityEnabled; }
set { gravityEnabled = value; }
}
private float slideFactor;
/// <summary>
/// Multiplicador de la fuerza de Sliding
/// </summary>
public float SlideFactor
{
get { return slideFactor; }
set { slideFactor = value; }
}
List<TgcBoundingBox> objetosCandidatos = new List<TgcBoundingBox>();
public SphereCollisionManager()
{
gravityEnabled = true;
gravityForce = new Vector3(0, -10, 0);
slideFactor = 1.3f;
}
/// <summary>
/// Mover BoundingSphere con detección de colisiones, sliding y gravedad.
/// Se actualiza la posición del centrodel BoundingSphere.
/// </summary>
/// <param name="characterSphere">BoundingSphere del cuerpo a mover</param>
/// <param name="movementVector">Movimiento a realizar</param>
/// <param name="obstaculos">BoundingBox de obstáculos contra los cuales se puede colisionar</param>
/// <returns>Desplazamiento relativo final efecutado al BoundingSphere</returns>
public Vector3 moveCharacter(TgcBoundingSphere characterSphere, Vector3 movementVector, List<TgcBoundingBox> obstaculos)
{
Vector3 originalSphereCenter = characterSphere.Center;
//Realizar movimiento
collideWithWorld(characterSphere, movementVector, obstaculos);
//Aplicar gravedad
if (gravityEnabled)
{
collideWithWorld(characterSphere, gravityForce, obstaculos);
}
return characterSphere.Center - originalSphereCenter;
}
/// <summary>
/// Detección de colisiones, filtrando los obstaculos que se encuentran dentro del radio de movimiento
/// </summary>
private void collideWithWorld(TgcBoundingSphere characterSphere, Vector3 movementVector, List<TgcBoundingBox> obstaculos)
{
if (movementVector.LengthSq() < EPSILON)
{
return;
}
Vector3 lastCenterSafePosition = characterSphere.Center;
//Dejar solo los obstáculos que están dentro del radio de movimiento de la esfera
Vector3 halfMovementVec = Vector3.Multiply(movementVector, 0.5f);
TgcBoundingSphere testSphere = new TgcBoundingSphere(
characterSphere.Center + halfMovementVec,
halfMovementVec.Length() + characterSphere.Radius
);
objetosCandidatos.Clear();
foreach (TgcBoundingBox obstaculo in obstaculos)
{
if (TgcCollisionUtils.testSphereAABB(testSphere, obstaculo))
{
objetosCandidatos.Add(obstaculo);
}
}
//Detectar colisiones y deplazar con sliding
doCollideWithWorld(characterSphere, movementVector, objetosCandidatos, 0);
//Manejo de error. No deberiamos colisionar con nadie si todo salio bien
foreach (TgcBoundingBox obstaculo in objetosCandidatos)
{
if (TgcCollisionUtils.testSphereAABB(characterSphere, obstaculo))
{
//Hubo un error, volver a la posición original
characterSphere.setCenter(lastCenterSafePosition);
return;
}
}
}
/// <summary>
/// Detección de colisiones recursiva
/// </summary>
public void doCollideWithWorld(TgcBoundingSphere characterSphere, Vector3 movementVector, List<TgcBoundingBox> obstaculos, int recursionDepth)
{
//Limitar recursividad
if (recursionDepth > 3)//Estaba en 5
{
return;
}
//Ver si la distancia a recorrer es para tener en cuenta
float distanceToTravelSq = movementVector.LengthSq();
if (distanceToTravelSq < EPSILON)
{
return;
}
//Posicion deseada
Vector3 originalSphereCenter = characterSphere.Center;
Vector3 nextSphereCenter = originalSphereCenter + movementVector;
//Buscar el punto de colision mas cercano de todos los objetos candidatos
float minCollisionDistSq = float.MaxValue;
Vector3 realMovementVector = movementVector;
TgcBoundingBox.Face collisionFace = null;
TgcBoundingBox collisionObstacle = null;
Vector3 nearestPolygonIntersectionPoint = Vector3.Empty;
foreach (TgcBoundingBox obstaculoBB in obstaculos)
{
//Obtener los polígonos que conforman las 6 caras del BoundingBox
TgcBoundingBox.Face[] bbFaces = obstaculoBB.computeFaces();
foreach (TgcBoundingBox.Face bbFace in bbFaces)
{
Vector3 pNormal = TgcCollisionUtils.getPlaneNormal(bbFace.Plane);
TgcRay movementRay = new TgcRay(originalSphereCenter, movementVector);
float brutePlaneDist;
Vector3 brutePlaneIntersectionPoint;
if (!TgcCollisionUtils.intersectRayPlane(movementRay, bbFace.Plane, out brutePlaneDist, out brutePlaneIntersectionPoint))
{
continue;
}
float movementRadiusLengthSq = Vector3.Multiply(movementVector, characterSphere.Radius).LengthSq();
if (brutePlaneDist * brutePlaneDist > movementRadiusLengthSq)
{
continue;
}
//Obtener punto de colisión en el plano, según la normal del plano
float pDist;
Vector3 planeIntersectionPoint;
Vector3 sphereIntersectionPoint;
TgcRay planeNormalRay = new TgcRay(originalSphereCenter, -pNormal);
bool embebbed = false;
bool collisionFound = false;
if (TgcCollisionUtils.intersectRayPlane(planeNormalRay, bbFace.Plane, out pDist, out planeIntersectionPoint))
{
//Ver si el plano está embebido en la esfera
if (pDist <= characterSphere.Radius)
{
embebbed = true;
//TODO: REVISAR ESTO, caso embebido a analizar con más detalle
sphereIntersectionPoint = originalSphereCenter - pNormal * characterSphere.Radius;
}
//Esta fuera de la esfera
else
{
//Obtener punto de colisión del contorno de la esfera según la normal del plano
sphereIntersectionPoint = originalSphereCenter - Vector3.Multiply(pNormal, characterSphere.Radius);
//Disparar un rayo desde el contorno de la esfera hacia el plano, con el vector de movimiento
TgcRay sphereMovementRay = new TgcRay(sphereIntersectionPoint, movementVector);
if (!TgcCollisionUtils.intersectRayPlane(sphereMovementRay, bbFace.Plane, out pDist, out planeIntersectionPoint))
{
//no hay colisión
continue;
}
}
//Ver si planeIntersectionPoint pertenece al polígono
Vector3 newMovementVector;
float newMoveDistSq;
Vector3 polygonIntersectionPoint;
if (pointInBounbingBoxFace(planeIntersectionPoint, bbFace))
{
if (embebbed)
{
//TODO: REVISAR ESTO, nunca debería pasar
//throw new Exception("El polígono está dentro de la esfera");
}
polygonIntersectionPoint = planeIntersectionPoint;
collisionFound = true;
}
else
{
//Buscar el punto mas cercano planeIntersectionPoint que tiene el polígono real de esta cara
polygonIntersectionPoint = TgcCollisionUtils.closestPointRectangle3d(planeIntersectionPoint,
bbFace.Extremes[0], bbFace.Extremes[1], bbFace.Extremes[2]);
//Revertir el vector de velocidad desde el nuevo polygonIntersectionPoint para ver donde colisiona la esfera, si es que llega
Vector3 reversePointSeg = polygonIntersectionPoint - movementVector;
if (TgcCollisionUtils.intersectSegmentSphere(polygonIntersectionPoint, reversePointSeg, characterSphere, out pDist, out sphereIntersectionPoint))
{
collisionFound = true;
}
}
if (collisionFound)
{
//Nuevo vector de movimiento acotado
newMovementVector = polygonIntersectionPoint - sphereIntersectionPoint;
newMoveDistSq = newMovementVector.LengthSq();
if (newMoveDistSq <= distanceToTravelSq && newMoveDistSq < minCollisionDistSq)
{
minCollisionDistSq = newMoveDistSq;
realMovementVector = newMovementVector;
nearestPolygonIntersectionPoint = polygonIntersectionPoint;
collisionFace = bbFace;
collisionObstacle = obstaculoBB;
}
}
}
}
}
//Si nunca hubo colisión, avanzar todo lo requerido
if (collisionFace == null)
{
//Avanzar hasta muy cerca
float movementLength = movementVector.Length();
movementVector.Multiply((movementLength - EPSILON) / movementLength);
characterSphere.moveCenter(movementVector);
return;
}
//Solo movernos si ya no estamos muy cerca
if (minCollisionDistSq >= EPSILON)
{
//Mover el BoundingSphere hasta casi la nueva posición real
float movementLength = realMovementVector.Length();
realMovementVector.Multiply((movementLength - EPSILON) / movementLength);
characterSphere.moveCenter(realMovementVector);
}
//Calcular plano de Sliding
Vector3 slidePlaneOrigin = nearestPolygonIntersectionPoint;
Vector3 slidePlaneNormal = characterSphere.Center - nearestPolygonIntersectionPoint;
slidePlaneNormal.Normalize();
Plane slidePlane = Plane.FromPointNormal(slidePlaneOrigin, slidePlaneNormal);
//Proyectamos el punto original de destino en el plano de sliding
TgcRay slideRay = new TgcRay(nearestPolygonIntersectionPoint + Vector3.Multiply(movementVector, slideFactor), slidePlaneNormal);
float slideT;
Vector3 slideDestinationPoint;
if (TgcCollisionUtils.intersectRayPlane(slideRay, slidePlane, out slideT, out slideDestinationPoint))
{
//Nuevo vector de movimiento
Vector3 slideMovementVector = slideDestinationPoint - nearestPolygonIntersectionPoint;
if (slideMovementVector.LengthSq() < EPSILON)
{
return;
}
//Recursividad para aplicar sliding
doCollideWithWorld(characterSphere, slideMovementVector, obstaculos, recursionDepth + 1);
}
}
/// <summary>
/// Ver si un punto pertenece a una cara de un BoundingBox
/// </summary>
/// <returns>True si pertenece</returns>
private bool pointInBounbingBoxFace(Vector3 p, TgcBoundingBox.Face bbFace)
{
Vector3 min = bbFace.Extremes[0];
Vector3 max = bbFace.Extremes[3];
return p.X >= min.X && p.Y >= min.Y && p.Z >= min.Z &&
p.X <= max.X && p.Y <= max.Y && p.Z <= max.Z;
}
}
}