summaryrefslogtreecommitdiff
path: root/Runtime/Dynamics/CapsuleCollider.cpp
blob: acfadde87a74235d731a69cae1f16e991b2ee900 (plain)
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
#include "UnityPrefix.h"
#if ENABLE_PHYSICS
#include "CapsuleCollider.h"
#include "Runtime/Graphics/Transform.h"
#include "RigidBody.h"
#include "PhysicsManager.h"
#include "Runtime/Serialize/TransferFunctions/SerializeTransfer.h"
#include "Runtime/Filters/AABBUtility.h"
#include "External/PhysX/builds/SDKs/Physics/include/NxPhysics.h"
#include "Runtime/Misc/BuildSettings.h"

#define GET_SHAPE() ((class NxCapsuleShape*)m_Shape)

/*
 - i am not sure about the getscaled extents calculation.
 
*/

using namespace std;

CapsuleCollider::CapsuleCollider (MemLabelId label, ObjectCreationMode mode)
:	Super(label, mode)
{
}

CapsuleCollider::~CapsuleCollider ()
{
}

void CapsuleCollider::AwakeFromLoad(AwakeFromLoadMode awakeMode)
{
	if (m_Shape)
	{
		// Apply changed values
		SetRadius(m_Radius);
		SetHeight(m_Height);
		SetCenter(m_Center);
		SetDirection (m_Direction);
	}
	
	Super::AwakeFromLoad (awakeMode);
}	

void CapsuleCollider::SmartReset ()
{
	Super::SmartReset();
	AABB aabb;
	if (GetGameObjectPtr () && CalculateLocalAABB (GetGameObject (), &aabb))
	{
		Vector3f extents = aabb.GetExtent ();
		SetRadius (max (extents.x, extents.z));
		SetHeight (extents.y * 2.0F);
		SetCenter (aabb.GetCenter ());
	}
	else
	{
		SetRadius (0.5F);
		SetHeight (1.0F);
		SetCenter (Vector3f::zero);
	}
}

void CapsuleCollider::Reset ()
{
	Super::Reset ();
	m_Radius = 0.5F;
	m_Height = 1.0F;
	m_Center = Vector3f::zero;
	m_Direction = 1;
}


Vector2f CapsuleCollider::GetGlobalExtents () const
{
	const float kMinSize = 0.00001F;
	Vector3f scale = GetComponent (Transform).GetWorldScaleLossy ();

	float absoluteHeight = max (Abs (m_Height * scale.y), kMinSize);
	float absoluteRadius = max (Abs (scale.x), Abs (scale.z)) * m_Radius;
	
	float height = absoluteHeight - absoluteRadius * 2.0F;
	
	height = max (height, kMinSize);
	absoluteRadius = max (absoluteRadius, kMinSize);

	return Vector2f (absoluteRadius, height);
}

Vector3f CapsuleCollider::GetGlobalCenter () const
{
	return GetComponent (Transform).TransformPoint (m_Center);
}

AABB CapsuleCollider::GetBounds ()
{
	if (m_Shape)
	{
		// AABB reported by PhysX is inaccurate, as PhysX will just transform the local AABB.
		// For Capsules it's very easy to do better.
		
		Vector2f extents = GetGlobalExtents();
		Matrix4x4f m = CalculateTransform ();
		
		Vector3f center1 = m.MultiplyPoint3 (Vector3f(0, extents.y * 0.5, 0));
		Vector3f center2 = m.MultiplyPoint3 (Vector3f(0, -extents.y * 0.5, 0));

		// Make AABB of both global centers
		AABB aabb (center1, Vector3f::zero);
		aabb.Encapsulate (center2);
		
		// Expand by global radius
		aabb.m_Extent += Vector3f(extents.x, extents.x, extents.x);
		return aabb;
	}
	else 
		return Super::GetBounds ();
}

void CapsuleCollider::Create (const Rigidbody* ignoreRigidbody)
{
	if (m_Shape)
		Cleanup ();

	NxCapsuleShapeDesc shapeDesc;
	Vector2f extents = GetGlobalExtents ();
	shapeDesc.radius = extents.x;
	shapeDesc.height = extents.y;
	
	FinalizeCreate (shapeDesc, true, ignoreRigidbody);
}

void CapsuleCollider::SetRadius (float radius)
{
	if (m_Radius != radius)
	{
		SetDirty ();
		m_Radius = radius;
	}

	PROFILE_MODIFY_STATIC_COLLIDER

	if (GET_SHAPE ())
	{
		GET_SHAPE ()->setRadius (GetGlobalExtents ().x);
		RigidbodyMassDistributionChanged ();
		RefreshPhysicsInEditMode();
		UpdateCCDSkeleton ();
	}
}

void CapsuleCollider::SetHeight (float height)
{
	if (m_Height != height)
	{
		SetDirty ();
		m_Height = height;
	}
	
	PROFILE_MODIFY_STATIC_COLLIDER
	
	if (GET_SHAPE ())
	{
		GET_SHAPE ()->setHeight (GetGlobalExtents ().y);
		RigidbodyMassDistributionChanged ();
		RefreshPhysicsInEditMode();
		UpdateCCDSkeleton ();
	}
}

void CapsuleCollider::SetCenter (const Vector3f& center)
{
	if (m_Center != center)
	{
		m_Center = center;
		SetDirty ();
	}
	
	if (GET_SHAPE ())
	{
		TransformChanged (Transform::kRotationChanged | Transform::kPositionChanged | kForceUpdateMass);
		RefreshPhysicsInEditMode();
	}
}

void CapsuleCollider::ScaleChanged ()
{
	NxCapsuleShape* shape = GET_SHAPE ();
	Vector2f extents = GetGlobalExtents ();
	shape->setRadius (extents.x);
	shape->setHeight (extents.y);
	
	UpdateCCDSkeleton ();

	PROFILE_MODIFY_STATIC_COLLIDER
}

void CapsuleCollider::SetDirection (int dir)
{
	if (m_Direction != dir)
	{
		SetDirty ();
		m_Direction = dir;
	}

	TransformChanged (kForceUpdateMass);
}

Matrix4x4f CapsuleCollider::CalculateTransform () const
{
	Transform& transform = GetComponent (Transform);
	Vector3f p = transform.TransformPoint (m_Center);

	Quaternionf rotation = transform.GetRotation ();
	if (m_Direction == 2)
		rotation *= AxisAngleToQuaternion (Vector3f::xAxis, Deg2Rad (90));
	else if (m_Direction == 0)
		rotation *= AxisAngleToQuaternion (Vector3f::zAxis, Deg2Rad (90));
	else
		rotation *= AxisAngleToQuaternion (Vector3f::xAxis, Deg2Rad (180));

	Matrix4x4f matrix;
	matrix.SetTR (p, rotation);

	return matrix;
}

void CapsuleCollider::FetchPoseFromTransform ()
{
	AssertIf (HasActorRigidbody ());
	
	Transform& transform = GetComponent (Transform);
	Vector3f p = transform.TransformPoint (m_Center);
	m_Shape->getActor ().setGlobalPosition ((const NxVec3&)p);
	
	Quaternionf rotation = transform.GetRotation ();
	if (m_Direction == 2)
		rotation *= AxisAngleToQuaternion (Vector3f::xAxis, Deg2Rad (90));
	else if (m_Direction == 0)
		rotation *= AxisAngleToQuaternion (Vector3f::zAxis, Deg2Rad (90));
	else
		rotation *= AxisAngleToQuaternion (Vector3f::xAxis, Deg2Rad (180));
	
	m_Shape->getActor ().setGlobalOrientationQuat ((const NxQuat&)rotation);
}

bool CapsuleCollider::GetRelativeToParentPositionAndRotation (Transform& transform, Transform& anyParent, Matrix4x4f& matrix)
{
	Matrix4x4f childMatrix = CalculateTransform ();
	Matrix4x4f parentMatrix = anyParent.GetWorldToLocalMatrixNoScale ();
	MultiplyMatrices4x4 (&parentMatrix, &childMatrix, &matrix);
	ErrorFiniteParameterReturnFalse(matrix)
	return true;
}

void CapsuleCollider::TransformChanged (int changeMask)
{
	Super::TransformChanged (changeMask);
	if (m_Shape)
	{
		if (m_Shape->getActor ().userData == NULL)
		{
			PROFILER_AUTO(gStaticColliderMove, this)
			FetchPoseFromTransform ();
		}
		else
		{
			Rigidbody* body = (Rigidbody*)m_Shape->getActor ().userData;
			Matrix4x4f matrix;
			if (GetRelativeToParentPositionAndRotation (GetComponent (Transform), body->GetComponent (Transform), matrix))
			{
				NxMat34 shapeMatrix;
				shapeMatrix.setColumnMajor44 (matrix.GetPtr ());
				m_Shape->setLocalPose (shapeMatrix);
			}

			if (body->GetGameObjectPtr() != GetGameObjectPtr() || changeMask & (Transform::kScaleChanged | kForceUpdateMass))
				RigidbodyMassDistributionChanged ();
		}
		
		if (changeMask & Transform::kScaleChanged)
			ScaleChanged ();

		RefreshPhysicsInEditMode();
	}
}

NxCCDSkeleton* CapsuleCollider::CreateCCDSkeleton(float scale)
{
	// This is a very simple "approximation" of a capuse, of only 10 vertices.
	// Since CCD only kicks in when normal collisions fail, any is probably mostly 
	// interesting for small objects (as those tend to move faster), I believe that this
	// is a reasonable choice for common expected use. NVidia even recommends using 
	// single vertex meshes for very small objects.
	float radius;
	float height;
	
	if (IS_CONTENT_NEWER_OR_SAME(kUnityVersion4_0_a1))
	{
		Vector2f extents = GetGlobalExtents ();
		radius = extents.x * scale;
		height = extents.y * scale;
	}
	else
	{
		// Prior to 4.0 we incorrectly ignored object scale here. Keep this behaviour for backwards compatibility.
		radius = m_Radius * scale;
		height = m_Height * 0.5f * scale;
	}

	NxU32 triangles[3 * 16] = {
		0,1,2,
		0,2,3,
		0,3,4,
		0,4,1,
		
		1,5,6,
		1,6,2,
		2,6,7,
		2,7,3,
		3,7,8,
		3,8,4,
		4,8,5,
		4,5,1,
		
		9,6,5,
		9,7,6,
		9,8,7,
		9,5,8,
	};

	Vector3f points[10];
	points[0].Set( 0, -radius - height, 0);
	points[1].Set( -radius, -height, 0);
	points[2].Set( 0, -height, -radius);
	points[3].Set( radius, -height, 0);
	points[4].Set( 0, -height, radius);
	points[5].Set( -radius, height, 0);
	points[6].Set( 0, height, -radius);
	points[7].Set( radius, height, 0);
	points[8].Set( 0, height, radius);
	points[9].Set( 0, radius + height, 0);

	NxSimpleTriangleMesh stm;
	stm.numVertices = 10;
	stm.numTriangles = 16;
	stm.pointStrideBytes = sizeof(Vector3f);
	stm.triangleStrideBytes = sizeof(NxU32)*3;

	stm.points = points;
	stm.triangles = triangles;
	return GetDynamicsSDK().createCCDSkeleton(stm);
}

template<class TransferFunction>
void CapsuleCollider::Transfer (TransferFunction& transfer) 
{
	Super::Transfer (transfer);
	transfer.Align();
	TRANSFER_SIMPLE (m_Radius);
	TRANSFER_SIMPLE (m_Height);
	TRANSFER (m_Direction);
	TRANSFER (m_Center);
}

IMPLEMENT_CLASS (CapsuleCollider)
IMPLEMENT_OBJECT_SERIALIZE (CapsuleCollider)

#undef GET_SHAPE
#endif //ENABLE_PHYSICS