| 1 |
{%MainUnit castletransform.pas} |
| 2 |
{ |
| 3 |
Copyright 2017-2024 Michalis Kamburelis. |
| 4 |
|
| 5 |
This file is part of "Castle Game Engine". |
| 6 |
|
| 7 |
"Castle Game Engine" is free software; see the file COPYING.txt, |
| 8 |
included in this distribution, for details about the copyright. |
| 9 |
|
| 10 |
"Castle Game Engine" is distributed in the hope that it will be useful, |
| 11 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 13 |
|
| 14 |
---------------------------------------------------------------------------- |
| 15 |
} |
| 16 |
|
| 17 |
{ Physics. Integrates TCastleTransform with Kraft physics engine. } |
| 18 |
|
| 19 |
{$ifdef read_interface} |
| 20 |
|
| 21 |
{ Information send along with TCollisionEvent event, like |
| 22 |
TCastleRigidBody.OnCollisionEnter, TCastleRigidBody.OnCollisionExit. } |
| 23 |
TPhysicsCollisionDetails = record |
| 24 |
public |
| 25 |
Transforms: array [0..1] of TCastleTransform; |
| 26 |
|
| 27 |
{ Object that receives the OnCollisionXxx event. } |
| 28 |
function Sender: TCastleTransform; |
| 29 |
|
| 30 |
{ The object object (not the one that receives the OnCollisionXxx event) |
| 31 |
to which the event is related. |
| 32 |
|
| 33 |
@unorderedList( |
| 34 |
@item In case of @link(OnCollisionEnter), this is the object that we collided with. |
| 35 |
@item In case of @link(OnCollisionStay), this is the object that we are currently colliding with. |
| 36 |
@item In case of @link(OnCollisionExit), this is the object that we stopped colliding with. |
| 37 |
) } |
| 38 |
function OtherTransform: TCastleTransform; |
| 39 |
end; |
| 40 |
|
| 41 |
TPhysicsLayer = 0..19; |
| 42 |
TPhysicsLayers = set of TPhysicsLayer; |
| 43 |
|
| 44 |
TCastleLayerCollisions = class(TCastleComponent) |
| 45 |
strict private |
| 46 |
function GetCollides(const Layer1, Layer2: TPhysicsLayer): Boolean; |
| 47 |
procedure SetCollides(const Layer1, Layer2: TPhysicsLayer; const AValue: Boolean); |
| 48 |
procedure UpdateRigidBodies; |
| 49 |
function DefaultCollides(const Layer: TPhysicsLayer): TPhysicsLayers; |
| 50 |
private |
| 51 |
FCollides: array [TPhysicsLayer] of TPhysicsLayers; |
| 52 |
public |
| 53 |
constructor Create(AOwner: TComponent); override; |
| 54 |
|
| 55 |
procedure CustomSerialization(const SerializationProcess: TSerializationProcess); override; |
| 56 |
|
| 57 |
{ Do physical objects from indicated 2 layers collide with each other. } |
| 58 |
property Collides[const Layer1, Layer2: TPhysicsLayer]: Boolean read GetCollides write SetCollides; |
| 59 |
end; |
| 60 |
|
| 61 |
TCastleLayerNames = class(TCastleComponent) |
| 62 |
strict private |
| 63 |
FLayerNames: array[TPhysicsLayer] of String; |
| 64 |
FLayerDescriptions: array[TPhysicsLayer] of String; |
| 65 |
function GetLayerDescriptions(const Layer: TPhysicsLayer): String; |
| 66 |
function GetLayerNames(const Layer: TPhysicsLayer): String; |
| 67 |
procedure SetLayerNames(const Layer: TPhysicsLayer; const AValue: String); |
| 68 |
procedure SetLayerDescriptions(const Layer: TPhysicsLayer; const AValue: String); |
| 69 |
public |
| 70 |
procedure CustomSerialization(const SerializationProcess: TSerializationProcess); override; |
| 71 |
|
| 72 |
{ Name of each layer. This information is just for developer convenience, |
| 73 |
to display layer names in the editor. } |
| 74 |
property Names[const Layer: TPhysicsLayer]: String read GetLayerNames write SetLayerNames; |
| 75 |
|
| 76 |
{ Longer (possibly multiline) description about each layer. |
| 77 |
This information is just for developer convenience, |
| 78 |
to document layer purpose in the editor. } |
| 79 |
property Descriptions[const Layer: TPhysicsLayer]: String read GetLayerDescriptions write SetLayerDescriptions; |
| 80 |
end; |
| 81 |
|
| 82 |
{ Configure physics simulation calculation. } |
| 83 |
TPhysicsProperties = class(TComponent) |
| 84 |
strict private |
| 85 |
FAngularVelocityRK4Integration: Boolean; |
| 86 |
FLinearVelocityRK4Integration: Boolean; |
| 87 |
FFrequency: Single; |
| 88 |
FGravityStrength: Single; |
| 89 |
FMaxPhysicsTicksPerUpdate: Cardinal; |
| 90 |
FContinuousCollisionDetection: Boolean; |
| 91 |
FLayerCollisions: TCastleLayerCollisions; |
| 92 |
FLayerNames: TCastleLayerNames; |
| 93 |
procedure SetAngularVelocityRK4Integration(const AValue: Boolean); |
| 94 |
procedure SetLinearVelocityRK4Integration(const AValue: Boolean); |
| 95 |
procedure SetFrequency(const AValue: Single); |
| 96 |
procedure SetContinuousCollisionDetection(const AValue: Boolean); |
| 97 |
// unused |
| 98 |
//procedure SetLayerNames(const AValue: TStrings); |
| 99 |
private |
| 100 |
{ Buffer to not count physics step time per frame } |
| 101 |
FPhysicsTimeStep: TFloatTime; |
| 102 |
RootTransform: TCastleAbstractRootTransform; |
| 103 |
public |
| 104 |
const |
| 105 |
DefaultAngularVelocityRK4Integration = false; |
| 106 |
DefaultLinearVelocityRK4Integration = false; |
| 107 |
DefaultFrequency = 60.0; |
| 108 |
DefaultMaxPhysicsTicksPerUpdate = 5; |
| 109 |
DefaultGravityStrength = 9.81; |
| 110 |
DefaultContinuousCollisionDetection = true; |
| 111 |
constructor Create(AOwner: TComponent); override; |
| 112 |
destructor Destroy; override; |
| 113 |
published |
| 114 |
{ Use a more precise (but also more expensive) method for simulating angular velocity. |
| 115 |
The "RK4" refers to Runge–Kutta method. } |
| 116 |
property AngularVelocityRK4Integration: Boolean read FAngularVelocityRK4Integration write SetAngularVelocityRK4Integration default DefaultAngularVelocityRK4Integration; |
| 117 |
|
| 118 |
{ Use a more precise (but also more expensive) method for simulating linear velocity. |
| 119 |
The "RK4" refers to Runge–Kutta method. } |
| 120 |
property LinearVelocityRK4Integration: Boolean read FLinearVelocityRK4Integration write SetLinearVelocityRK4Integration default DefaultLinearVelocityRK4Integration; |
| 121 |
|
| 122 |
{ How often should the physics simulation run in a second. |
| 123 |
Larger values increase accuracy (up to a certain point), but also increase the CPU overhead. } |
| 124 |
property Frequency: Single read FFrequency write SetFrequency {$ifdef FPC}default DefaultFrequency{$endif}; |
| 125 |
|
| 126 |
{ Physics gravity is set using the -GravityUp vector (from main camera) |
| 127 |
multiplied with GravityStrength. } |
| 128 |
property GravityStrength: Single read FGravityStrength write FGravityStrength {$ifdef FPC}default DefaultGravityStrength{$endif}; |
| 129 |
|
| 130 |
{ Non-zero value avoids the "spiral of death" when the physics takes |
| 131 |
a long time to calculate. |
| 132 |
|
| 133 |
When the value is zero, physics makes always as many steps as necessary, |
| 134 |
to advance the time by @code(1 / @link(Frequency)) steps. |
| 135 |
This means that if physics takes a long time to calculate, |
| 136 |
next time it will take even longer time to calculate (it will need more steps), |
| 137 |
thus we have a "spiral of death" that leads to lower and lower FPS. } |
| 138 |
property MaxPhysicsTicksPerUpdate: Cardinal read FMaxPhysicsTicksPerUpdate write FMaxPhysicsTicksPerUpdate default DefaultMaxPhysicsTicksPerUpdate; |
| 139 |
|
| 140 |
{ Should engine use continous collision detection (CCD). } |
| 141 |
property ContinuousCollisionDetection: Boolean read FContinuousCollisionDetection write SetContinuousCollisionDetection default DefaultContinuousCollisionDetection; |
| 142 |
|
| 143 |
{ Which layers collide with each other. } |
| 144 |
property LayerCollisions: TCastleLayerCollisions read FLayerCollisions write FLayerCollisions; |
| 145 |
|
| 146 |
{ Name and a descriptions of layers. } |
| 147 |
property LayerNames: TCastleLayerNames read FLayerNames write FLayerNames; |
| 148 |
end; |
| 149 |
|
| 150 |
{ Abstract collider that determines the shape used to determine collisions with physics bodies. } |
| 151 |
TCastleCollider = class(TCastleBehavior) |
| 152 |
strict private |
| 153 |
{ Implementation note: |
| 154 |
This doesn't store any references to Kraft objects. |
| 155 |
This only describes shape. |
| 156 |
TCastleRigidBody takes care of initializing Kraft. } |
| 157 |
FDensity, FMass, FRestitution, FFriction: Single; |
| 158 |
FTranslation: TVector3; |
| 159 |
FRotation: TVector4; |
| 160 |
FAutoSize: Boolean; |
| 161 |
FCalculatingSize: Boolean; //< are we inside CalculateSize or InternalAutoSize |
| 162 |
{ Accumulated scale of all parent TCastleTransform. |
| 163 |
Does not include @link(SizeScale). |
| 164 |
This is always converted to a single scalar either using Approximate2DScale |
| 165 |
or Approximate3DScale, depending on Mode2D. } |
| 166 |
FWorldScale: TVector3; |
| 167 |
FSizeScale: Single; |
| 168 |
FMode2D: Boolean; |
| 169 |
WarningNonUniformScaleDone: Boolean; |
| 170 |
|
| 171 |
{ Updates FLocalTransformation and FUseLocalTransformation after changing |
| 172 |
Translation, FSizeScale, FWorldScale, Rotation and in InitializeKraft. } |
| 173 |
procedure UpdateLocalTransform; |
| 174 |
|
| 175 |
procedure SetDensity(const AValue: Single); |
| 176 |
procedure SetMass(const AValue: Single); |
| 177 |
procedure SetRestitution(const AValue: Single); |
| 178 |
procedure SetFriction(const AValue: Single); |
| 179 |
procedure SetTranslation(const AValue: TVector3); |
| 180 |
procedure SetRotation(const AValue: TVector4); |
| 181 |
procedure SetSizeScale(const AValue: Single); |
| 182 |
procedure SetAutoSize(const AValue: Boolean); |
| 183 |
function GetRigidBody: TCastleRigidBody; |
| 184 |
procedure SetMode2D(const AValue: Boolean); |
| 185 |
private |
| 186 |
FKraftShape: TKraftShape; // owned by TKraftRigidBody |
| 187 |
{ When @false, behave as if Translation/Rotation/FLocalTransform/FLocalInverseTransform |
| 188 |
were all "identity", i.e. "no transformation". |
| 189 |
This is an often case, so we want to optimize it. } |
| 190 |
FUseLocalTransform: Boolean; |
| 191 |
FLocalTransform: TMatrix4; |
| 192 |
FLocalInverseTransform: TMatrix4; |
| 193 |
|
| 194 |
{ Visualizes Translation, Rotation } |
| 195 |
FVisualizationParent: TCastleTransform; |
| 196 |
|
| 197 |
{ Initializes FKraftShape. } |
| 198 |
procedure InitializeKraft(const APhysics: TKraft; const ACastleRigidBody: TCastleRigidBody); |
| 199 |
|
| 200 |
{ Updates FWorldScale, needed e.g. after adding collider to world. |
| 201 |
Calls ShapeChangedNotifyRigidBody if it changed. |
| 202 |
|
| 203 |
Descendants implementors: |
| 204 |
You should multiply your descendant sizes with TotalScale in CreateKraftShape. |
| 205 |
TotalScale includes FWorldScale (updated by this method) and |
| 206 |
FSizeScale (set explicitly by user to tweak size). } |
| 207 |
procedure UpdateWorldScale; |
| 208 |
|
| 209 |
function WorldScaleScalar: Single; |
| 210 |
|
| 211 |
{ Configure Sender (TCastleCollider) to have Mode2D. } |
| 212 |
class procedure CreateComponent2D(Sender: TObject); |
| 213 |
protected |
| 214 |
{ Use this for "stored" for properties that are auto-calculated when AutoSize. } |
| 215 |
function StoredWithAutoSize: Boolean; |
| 216 |
|
| 217 |
{ Total scale, accumulated from all parents TCastleTransform.Scale (converted to scalar |
| 218 |
following Mode2D) and collider SizeScale. } |
| 219 |
function TotalScale: Single; |
| 220 |
|
| 221 |
function CreateKraftShape(const APhysics: TKraft; |
| 222 |
const ARigidBody: TKraftRigidBody): TKraftShape; virtual; abstract; |
| 223 |
|
| 224 |
procedure DeinitializePhysicsEngineObjects; virtual; |
| 225 |
|
| 226 |
{ Notify associated TCastleRigidBody that Kraft shape needs to be recreated. |
| 227 |
This may in turn call TCastleCollider.InitializeKraft |
| 228 |
and TCastleCollider.CreateKraftShape. } |
| 229 |
procedure ShapeChangedNotifyRigidBody; |
| 230 |
|
| 231 |
{ Called when the collider size has changed and needs to be updated. } |
| 232 |
procedure UpdateVisualization; virtual; |
| 233 |
procedure WorldAfterAttach; override; |
| 234 |
procedure WorldBeforeDetach; override; |
| 235 |
|
| 236 |
{ Only one TCastleCollider behavior can be added to a given |
| 237 |
TCastleTransform so we check that here. } |
| 238 |
function CanAttachToParent(const NewParent: TCastleTransform; |
| 239 |
out ReasonWhyCannot: String): Boolean; override; |
| 240 |
|
| 241 |
{ Sets AutoSize = @false, unless this is called |
| 242 |
inside InternalAutoSize or at loading. |
| 243 |
Call this when something changes collider size explicitly, |
| 244 |
e.g. TCastleSphereCollider.Radius changes. } |
| 245 |
procedure DisableAutoSize; |
| 246 |
|
| 247 |
{ Recalculate collider size. |
| 248 |
Do not be concerned about AutoSize here, just update collider properties. |
| 249 |
The default implementation resets Translation and Rotation. } |
| 250 |
procedure CalculateSizeCore; virtual; |
| 251 |
public |
| 252 |
const |
| 253 |
{ Default for @link(Density). } |
| 254 |
DefaultDensity = 1.0; |
| 255 |
|
| 256 |
{ Default for @link(Mass), zero means "use @link(Density) instead". } |
| 257 |
DefaultMass = 0.0; |
| 258 |
|
| 259 |
{ Default for @link(Restitution). } |
| 260 |
DefaultRestitution = 0.0; |
| 261 |
|
| 262 |
{ Default for @link(Friction). } |
| 263 |
DefaultFriction = 0.5; |
| 264 |
class var |
| 265 |
{ Minimum collider thickness used by @link(AutoSize) in 3D mode (when @link(Mode2D) = @false). |
| 266 |
Changing this only affects new size calculations.} |
| 267 |
AutoSizeMinThickness: Single; |
| 268 |
|
| 269 |
{ Minimum collider thickness used by @link(AutoSize) in 2D mode (when @link(Mode2D) = @true). |
| 270 |
This is used for axis other than Z (like X, Y, or collider radiuses that affect size |
| 271 |
in a few axis). |
| 272 |
Changing this only affects new size calculations.} |
| 273 |
AutoSizeMinThickness2D: Single; |
| 274 |
|
| 275 |
{ Minimum collider thickness used by @link(AutoSize) in 2D mode (when @link(Mode2D) = @true) for Z. |
| 276 |
This is used only by TCastleBoxCollider now, as only that collider has specific size in Z. |
| 277 |
Changing this only affects new size calculations.} |
| 278 |
AutoSizeMinThickness2DDepth: Single; |
| 279 |
|
| 280 |
constructor Create(AOwner: TComponent); override; |
| 281 |
destructor Destroy; override; |
| 282 |
function PropertySections(const PropertyName: String): TPropertySections; override; |
| 283 |
procedure CustomSerialization(const SerializationProcess: TSerializationProcess); override; |
| 284 |
|
| 285 |
{ Notify this collider that given TCastleTransform changed. |
| 286 |
It can provoke AutoSize recalculation (if Parent changed) |
| 287 |
or other reactions (e.g. mesh update, if TransformChanged corresponds to Mesh). } |
| 288 |
procedure InternalTransformChanged(const TransformChanged: TCastleTransform); virtual; |
| 289 |
|
| 290 |
{ Create collider visualization. } |
| 291 |
procedure InternalDesigningBegin; virtual; |
| 292 |
{ Destroy collider visualization. } |
| 293 |
procedure InternalDesigningEnd; virtual; |
| 294 |
|
| 295 |
procedure ParentBeforeDetach; override; |
| 296 |
|
| 297 |
{ Recalculate collider size using parent bounding box, only if @link(AutoSize) says we should recalculate. |
| 298 |
Ignored if not @link(AutoSize). } |
| 299 |
procedure InternalAutoSize; |
| 300 |
|
| 301 |
{ Calculate collider size to reflect parent bounding box now. |
| 302 |
This works regardless of @link(AutoSize) value, |
| 303 |
and doesn't change @link(AutoSize) value. |
| 304 |
The idea is that you can call it when |
| 305 |
|
| 306 |
@orderedList( |
| 307 |
@item(You have @link(AutoSize) = @false and want to adjust size to bounding box |
| 308 |
at specific moment.) |
| 309 |
@item(You have @link(AutoSize) = @true but still want to force recalculation right now, |
| 310 |
because @link(AutoSize) doesn't do it too eagerly (see AutoSize description). |
| 311 |
) |
| 312 |
) |
| 313 |
|
| 314 |
@seealso AutoSize } |
| 315 |
procedure CalculateSize; |
| 316 |
|
| 317 |
{ Local collider translation, relative to parent TCastleTransform. |
| 318 |
Note that CalculateSize and AutoSize mechanisms set it automatically. } |
| 319 |
property Translation: TVector3 read FTranslation write SetTranslation; |
| 320 |
|
| 321 |
{ Local collider rotation, relative to parent TCastleTransform. |
| 322 |
Note that CalculateSize and AutoSize mechanisms set it automatically. } |
| 323 |
property Rotation: TVector4 read FRotation write SetRotation; |
| 324 |
published |
| 325 |
{ Automatically calculate collider properties that determine collider size |
| 326 |
based on the parent transformation bounding box. |
| 327 |
|
| 328 |
When this is set, properties like |
| 329 |
@link(TCastleSphereCollider.Radius) or @link(TCastleBoxCollider.Size) |
| 330 |
are automatically updated to the best values to match collider size |
| 331 |
with the parent @link(TCastleTransform.LocalBoundingBox). |
| 332 |
|
| 333 |
Note that even when this is @true, the collider size recalculation is not done |
| 334 |
too "eagerly", i.e. the collider size is not recalculated on every possible change. |
| 335 |
For example, if you animate a TCastleScene, then bounding box may change every frame |
| 336 |
(note: it depends on the technique; e.g. glTF models with skinned animation |
| 337 |
have a complete bounding box of the animation precalculated and constant; |
| 338 |
but X3D models morphed using CoordinateInterpolator have bounding box |
| 339 |
changing every frame). |
| 340 |
|
| 341 |
But it would be bad to change the collider size (even at design-time) every frame. |
| 342 |
That's because changing the collider size may imply (for the underlying physics engine) |
| 343 |
recreation of internal srtuctures and reinitialization of the collision state. |
| 344 |
So in the ideal case, the collider size should just stay constant once the object |
| 345 |
has been added to some TCastleViewport and it may interact with other physics bodies. |
| 346 |
|
| 347 |
You can always manually force recalculation of the collider size using the |
| 348 |
@link(CalculateSize) method. } |
| 349 |
property AutoSize: Boolean read FAutoSize write SetAutoSize default true; |
| 350 |
|
| 351 |
{ Density (per volume) in kg, this implicitly determines mass |
| 352 |
(volume is automatically calculated by the physics engine). |
| 353 |
If you instead prefer to explicitly set mass, set @link(Mass) |
| 354 |
property to something non-zero. } |
| 355 |
property Density: Single read FDensity write SetDensity |
| 356 |
{$ifdef FPC}default DefaultDensity{$endif}; |
| 357 |
|
| 358 |
{ Mass in kg. When non-zero, this overrides the automatically calculated |
| 359 |
mass from the volume and @link(Density). } |
| 360 |
property Mass: Single read FMass write SetMass |
| 361 |
{$ifdef FPC}default DefaultMass{$endif}; |
| 362 |
|
| 363 |
{ Larger restitution means that on collision, this object behaves more elastic. |
| 364 |
Reasonable values are between 0 (inelastic) and 1 (elastic). |
| 365 |
See https://en.wikipedia.org/wiki/Coefficient_of_restitution . } |
| 366 |
property Restitution: Single read FRestitution write SetRestitution |
| 367 |
{$ifdef FPC}default DefaultRestitution{$endif}; |
| 368 |
|
| 369 |
{ Larger friction means that it is harder for body to slide alongside another object. } |
| 370 |
property Friction: Single read FFriction write SetFriction |
| 371 |
{$ifdef FPC}default DefaultFriction{$endif}; |
| 372 |
|
| 373 |
{ Local collider size scale. |
| 374 |
|
| 375 |
This is particularly useful if @link(AutoSize) mechanism calculated too large box. |
| 376 |
For collision purposes, you sometimes want a collider that is a bit smaller |
| 377 |
than the bounding box/sphere around the object. |
| 378 |
Maybe it should even be too small at certain places, but then it will make |
| 379 |
a better fit overall. |
| 380 |
|
| 381 |
You can achieve this (and still keep using @link(AutoSize)) by adjusting |
| 382 |
this property e.g. to 0.9 to have collider be 90% of what |
| 383 |
@link(AutoSize) calculated. |
| 384 |
|
| 385 |
This is @bold(not) reset by CalculateSize and AutoSize mechanisms |
| 386 |
(in contrast to Translation, Rotation) because the idea is that user adjusts |
| 387 |
the auto-calculated size this way. } |
| 388 |
property SizeScale: Single read FSizeScale write SetSizeScale {$ifdef FPC}default 1.0{$endif}; |
| 389 |
|
| 390 |
{ Make various features (in particular automatic size calculation caused by @link(AutoSize)) |
| 391 |
better adjusted to 2D models, where the user-visible shape is in XY |
| 392 |
and the Z coordinate (position in Z, thickness in Z) should have little or no effect on the result. |
| 393 |
|
| 394 |
More precisely, when this is @true: |
| 395 |
|
| 396 |
@orderedList( |
| 397 |
@item(@link(AutoSize) estimates collider 3D sizes (because internally Kraft colliders are always in 3D) |
| 398 |
based on geometry sizes only in XY dimensions. |
| 399 |
So it ignores how thin or thick is you geometry along the Z axis.) |
| 400 |
|
| 401 |
@item(@link(AutoSize) assumes a bit larger "minimum thickness" for 2D, |
| 402 |
because typical 2D worlds use larger units. |
| 403 |
Moreover, it assumes even larger thickness in Z, to avoid too thin boxes |
| 404 |
(that would not be detected as collidable). |
| 405 |
See @link(AutoSizeMinThickness), @link(AutoSizeMinThickness2D), @link(AutoSizeMinThickness2DDepth).) |
| 406 |
|
| 407 |
@item(Non-uniform scale (coming from accumulated TCastleTransform.Scale on all our parents) |
| 408 |
is handled differently. When Mode2D = @true, the non-uniform scale is converted |
| 409 |
into a scalar using Approximate2DScale, so it only looks at XY coordinates. |
| 410 |
When Mode2D = @false, the non-uniform scale is converted using Approximate3DScale, |
| 411 |
so it looks at all coordinates.) |
| 412 |
|
| 413 |
@item(In the future, esp. if we integrate with other physics engines like Box2D, |
| 414 |
it is possible that some colliders in 2D mode will have a shape much more suitable |
| 415 |
in 2D. "Suitable in 2D" ideally means "Z coordinate is ignored". |
| 416 |
This means that a 2D collider should (ideally) behave as if it is infinite in Z. |
| 417 |
|
| 418 |
For example a 2D sphere collider may effectively be an infinite cylinder. |
| 419 |
That is: it should be a circle in XY, but extruded into infinity in -Z and +Z. |
| 420 |
This is not @italic(right now) how the TCastleSphereCollider behaves with Mode2D = @true, |
| 421 |
but it may be in the future. |
| 422 |
) |
| 423 |
) |
| 424 |
} |
| 425 |
property Mode2D: Boolean read FMode2D write SetMode2D default false; |
| 426 |
|
| 427 |
{$define read_interface_class} |
| 428 |
{$I auto_generated_persistent_vectors/tcastlecollider_persistent_vectors.inc} |
| 429 |
{$undef read_interface_class} |
| 430 |
end; |
| 431 |
|
| 432 |
{ Push everything to be above the given static plane, like a floor. |
| 433 |
|
| 434 |
Half of 3D space (below the plane) is effectively collidable, |
| 435 |
and everything is pushed to be above the floor. |
| 436 |
Note: This is more than just "collide as an infinite plane", because |
| 437 |
even if you place a body completely below the plane, it will be pushed up. |
| 438 |
|
| 439 |
Add this collider to TCastleTransform behaviors, along with a TCastleRigidBody, |
| 440 |
to make the given TCastleTransform be affected by physics and collide with other physics bodies. |
| 441 |
|
| 442 |
This collider supports only static rigid bodies. |
| 443 |
The associated TCastleRigidBody instance (with the same TCastleTransform parent) |
| 444 |
will behave as if @link(TCastleRigidBody.Dynamic) and @link(TCastleRigidBody.Animated) are @false. } |
| 445 |
TCastlePlaneCollider = class(TCastleCollider) |
| 446 |
strict private |
| 447 |
FNormal: TVector3; |
| 448 |
FDistance: Single; |
| 449 |
FVisualization: TCastleTransform; |
| 450 |
procedure SetNormal(const AValue: TVector3); |
| 451 |
procedure SetDistance(const AValue: Single); |
| 452 |
function CalculateScaledDistance: Single; |
| 453 |
protected |
| 454 |
function CreateKraftShape(const APhysics: TKraft; |
| 455 |
const ARigidBody: TKraftRigidBody): TKraftShape; override; |
| 456 |
procedure CalculateSizeCore; override; |
| 457 |
procedure UpdateVisualization; override; |
| 458 |
public |
| 459 |
constructor Create(AOwner: TComponent); override; |
| 460 |
destructor Destroy; override; |
| 461 |
|
| 462 |
procedure InternalDesigningBegin; override; |
| 463 |
procedure InternalDesigningEnd; override; |
| 464 |
|
| 465 |
function PropertySections(const PropertyName: String): TPropertySections; override; |
| 466 |
|
| 467 |
{ Normal vector of the plane. |
| 468 |
By default this is +Y (if not AutoSize). |
| 469 |
This makes the default plane by constant in Y axis, and span to infinity in X and Z axis. |
| 470 |
This makes it nice as a ground/floor in 3D. } |
| 471 |
property Normal: TVector3 read FNormal write SetNormal stored StoredWithAutoSize; |
| 472 |
published |
| 473 |
{ Distance from (0,0,0) to the point. |
| 474 |
Default 0 (if not AutoSize). } |
| 475 |
property Distance: Single read FDistance write SetDistance stored StoredWithAutoSize; |
| 476 |
|
| 477 |
{$define read_interface_class} |
| 478 |
{$I auto_generated_persistent_vectors/tcastleplanecollider_persistent_vectors.inc} |
| 479 |
{$undef read_interface_class} |
| 480 |
end; |
| 481 |
|
| 482 |
{ Collide as a box. |
| 483 |
Add this collider to TCastleTransform behaviors, along with a TCastleRigidBody, |
| 484 |
to make the given TCastleTransform be affected by physics and collide with other physics bodies. } |
| 485 |
TCastleBoxCollider = class(TCastleCollider) |
| 486 |
strict private |
| 487 |
FVisualization: TCastleTransform; |
| 488 |
FSize: TVector3; //< this size doesn't include FSizeScale or FWorldScale |
| 489 |
procedure SetSize(const AValue: TVector3); |
| 490 |
{ Returns scaled size, because scale is added to size directly. } |
| 491 |
function CalculateScaledSize: CastleVectors.TVector3; |
| 492 |
protected |
| 493 |
function CreateKraftShape(const APhysics: TKraft; |
| 494 |
const ARigidBody: TKraftRigidBody): TKraftShape; override; |
| 495 |
procedure CalculateSizeCore; override; |
| 496 |
procedure UpdateVisualization; override; |
| 497 |
public |
| 498 |
constructor Create(AOwner: TComponent); override; |
| 499 |
destructor Destroy; override; |
| 500 |
function PropertySections(const PropertyName: String): TPropertySections; override; |
| 501 |
procedure InternalDesigningBegin; override; |
| 502 |
procedure InternalDesigningEnd; override; |
| 503 |
|
| 504 |
{ Box size. |
| 505 |
Default is (2,2,2) (if not AutoSize), consistent with TCastleBox. } |
| 506 |
property Size: TVector3 read FSize write SetSize; |
| 507 |
published |
| 508 |
{$define read_interface_class} |
| 509 |
{$I auto_generated_persistent_vectors/tcastleboxcollider_persistent_vectors.inc} |
| 510 |
{$undef read_interface_class} |
| 511 |
end; |
| 512 |
|
| 513 |
{ Collide as a sphere. |
| 514 |
Add this collider to TCastleTransform behaviors, along with a TCastleRigidBody, |
| 515 |
to make the given TCastleTransform be affected by physics and collide with other physics bodies. } |
| 516 |
TCastleSphereCollider = class(TCastleCollider) |
| 517 |
strict private |
| 518 |
FRadius: Single; |
| 519 |
FVisualization: TCastleTransform; |
| 520 |
procedure SetRadius(const AValue: Single); |
| 521 |
{ Returns scaled Radius, because scale is added to size directly. } |
| 522 |
function CalculateScaledRadius: Single; |
| 523 |
protected |
| 524 |
function CreateKraftShape(const APhysics: TKraft; |
| 525 |
const ARigidBody: TKraftRigidBody): TKraftShape; override; |
| 526 |
procedure CalculateSizeCore; override; |
| 527 |
procedure UpdateVisualization; override; |
| 528 |
public |
| 529 |
constructor Create(AOwner: TComponent); override; |
| 530 |
function PropertySections(const PropertyName: String): TPropertySections; override; |
| 531 |
procedure InternalDesigningBegin; override; |
| 532 |
procedure InternalDesigningEnd; override; |
| 533 |
published |
| 534 |
{ Sphere radius. |
| 535 |
Default is 1 (if not AutoSize), consistent with TCastleSphere. } |
| 536 |
property Radius: Single read FRadius write SetRadius stored StoredWithAutoSize; |
| 537 |
end; |
| 538 |
|
| 539 |
{ Collide as a capsule. |
| 540 |
Add this collider to TCastleTransform behaviors, along with a TCastleRigidBody, |
| 541 |
to make the given TCastleTransform be affected by physics and collide with other physics bodies. } |
| 542 |
TCastleCapsuleCollider = class(TCastleCollider) |
| 543 |
strict private |
| 544 |
FRadius: Single; |
| 545 |
FHeight: Single; |
| 546 |
|
| 547 |
FVisualization: TCastleTransform; |
| 548 |
FVisualizationTop: TCastleTransform; |
| 549 |
FVisualizationBottom: TCastleTransform; |
| 550 |
FVisualizationCylinder: TCastleTransform; |
| 551 |
|
| 552 |
procedure SetRadius(const AValue: Single); |
| 553 |
procedure SetHeight(const AValue: Single); |
| 554 |
function CalculateScaledHeight: Single; |
| 555 |
function CalculateScaledRadius: Single; |
| 556 |
protected |
| 557 |
function CreateKraftShape(const APhysics: TKraft; |
| 558 |
const ARigidBody: TKraftRigidBody): TKraftShape; override; |
| 559 |
procedure CalculateSizeCore; override; |
| 560 |
procedure UpdateVisualization; override; |
| 561 |
public |
| 562 |
constructor Create(AOwner: TComponent); override; |
| 563 |
function PropertySections(const PropertyName: String): TPropertySections; override; |
| 564 |
|
| 565 |
procedure InternalDesigningBegin; override; |
| 566 |
procedure InternalDesigningEnd; override; |
| 567 |
published |
| 568 |
{ Sphere (at both top and bottom of capsule) radius. |
| 569 |
Default is 1 (if not AutoSize), consistent with TCastleSphere. } |
| 570 |
property Radius: Single read FRadius write SetRadius stored StoredWithAutoSize; |
| 571 |
|
| 572 |
{ Sphere (at both top and bottom of capsule) radius. |
| 573 |
Default is 2 (if not AutoSize), consistent with TCastleCylinder. } |
| 574 |
property Height: Single read FHeight write SetHeight stored StoredWithAutoSize; |
| 575 |
end; |
| 576 |
|
| 577 |
{ Collide as a set of triangles determined by @link(Mesh). |
| 578 |
Add this collider to TCastleTransform behaviors, along with a TCastleRigidBody, |
| 579 |
to make the given TCastleTransform be affected by physics and collide with other physics bodies. |
| 580 |
|
| 581 |
Make sure to set the @link(Mesh) property. |
| 582 |
|
| 583 |
In the current implementation, this collider supports only static rigid bodies. |
| 584 |
The associated TCastleRigidBody instance (with the same TCastleTransform parent) |
| 585 |
will behave as if @link(TCastleRigidBody.Dynamic) and @link(TCastleRigidBody.Animated) are @false. } |
| 586 |
TCastleMeshCollider = class(TCastleCollider) |
| 587 |
strict private |
| 588 |
FKraftMesh: TKraftMesh; |
| 589 |
FMesh: TCastleTransform; |
| 590 |
FDoubleSided: Boolean; |
| 591 |
procedure AddTriangle(Shape: TObject; |
| 592 |
const Position: TTriangle3; |
| 593 |
const Normal: TTriangle3; const TexCoord: TTriangle4; |
| 594 |
const Face: TFaceIndex); |
| 595 |
procedure SetDoubleSided(const Value: Boolean); |
| 596 |
procedure SetMesh(const AValue: TCastleTransform); |
| 597 |
protected |
| 598 |
function CreateKraftShape(const APhysics: TKraft; |
| 599 |
const ARigidBody: TKraftRigidBody): TKraftShape; override; |
| 600 |
procedure DeinitializePhysicsEngineObjects; override; |
| 601 |
public |
| 602 |
function PropertySections(const PropertyName: String): TPropertySections; override; |
| 603 |
procedure DesignerWarnings(const SList: TStrings); override; |
| 604 |
|
| 605 |
procedure InternalTransformChanged(const TransformChanged: TCastleTransform); override; |
| 606 |
|
| 607 |
{ Update the collider triangles to reflect current @link(Mesh) shape. |
| 608 |
This is necessary for physics engine to reflect the @link(Mesh). |
| 609 |
|
| 610 |
We do it automatically in some circumstances (like when you change |
| 611 |
collider properties, like @link(Mesh) or @link(DoubleSided), |
| 612 |
or when you change @link(TCastleSceneCore.Url)) but we don't try to keep |
| 613 |
the physics mesh follow the triangles every frame (as you really shouldn't |
| 614 |
change physics mesh so often, it's supposed to be a static collider). } |
| 615 |
procedure MeshChanged; |
| 616 |
published |
| 617 |
{ Mesh which is used to collide. |
| 618 |
It can be a TCastleScene, TCastleBox or other instance of TCastleTransform |
| 619 |
with @link(TCastleTransform.HasColliderMesh) = @true. |
| 620 |
|
| 621 |
It does not have to be convex. |
| 622 |
|
| 623 |
Note: The values of @link(TCastleTransform.Collides Mesh.Collides) and |
| 624 |
@link(TCastleTransform.GetCollides Mesh.GetCollides) of the assigned instance |
| 625 |
do not matter. |
| 626 |
|
| 627 |
Note: Using the TCollisionNode X3D nodes inside the assigned instance |
| 628 |
is still useful. This way the scene may collide |
| 629 |
as something different than it's visible, see |
| 630 |
https://castle-engine.io/x3d_implementation_navigation.php . } |
| 631 |
property Mesh: TCastleTransform read FMesh write SetMesh; |
| 632 |
|
| 633 |
{ Treat both faces sides as collidable. |
| 634 |
When this is @false: Depending on physics engine and situation, |
| 635 |
the back faces (where the normal doesn't point) may be ignored e.g. |
| 636 |
by @link(TCastleRigidBody.PhysicsRayCast). } |
| 637 |
property DoubleSided: Boolean read FDoubleSided write SetDoubleSided default false; |
| 638 |
end; |
| 639 |
|
| 640 |
TCollisionEvent = procedure (const CollisionDetails: TPhysicsCollisionDetails) of object; |
| 641 |
|
| 642 |
TCastleRigidBodyList = {$ifdef FPC}specialize{$endif} TList<TCastleRigidBody>; |
| 643 |
|
| 644 |
TCollisionDetection = ( |
| 645 |
cdDiscrete, |
| 646 |
cdContinuous |
| 647 |
); |
| 648 |
|
| 649 |
{ Use this behavior to be affected by physics collisions and forces. |
| 650 |
Add a TCastleRigidBody and some collider (TCastleCollider descendant) |
| 651 |
as behaviors of TCastleTransform to make the given TCastleTransform |
| 652 |
be affected by physics and collide with other physics bodies. } |
| 653 |
TCastleRigidBody = class(TCastleBehavior) |
| 654 |
strict private |
| 655 |
type |
| 656 |
TState = ( |
| 657 |
stateNone, //< nothing is done |
| 658 |
stateMissingCollider, //< needs initialize collider |
| 659 |
stateReady //< ready to work |
| 660 |
); |
| 661 |
var |
| 662 |
{ Current rigid body state. } |
| 663 |
FState: TState; |
| 664 |
{ Castle collider behavior that was used to initialize rigid body or nil |
| 665 |
if physics engine collider was not initialized } |
| 666 |
FCastleCollider: TCastleCollider; |
| 667 |
|
| 668 |
FDuringSettingTransformationFromPhysicsEngine: Boolean; |
| 669 |
|
| 670 |
FLayer: TPhysicsLayer; |
| 671 |
|
| 672 |
{ List of collisions from previous step. } |
| 673 |
FPrevCollisions: TCastleRigidBodyList; |
| 674 |
{ List of collisions from current step. } |
| 675 |
FCurrentCollisions: TCastleRigidBodyList; |
| 676 |
|
| 677 |
FOnCollisionEnter: TCollisionEvent; |
| 678 |
FOnCollisionStay: TCollisionEvent; |
| 679 |
FOnCollisionExit: TCollisionEvent; |
| 680 |
FNotifyOnInitialized: TCastleComponentNotification; |
| 681 |
FNotifyBeforeDeinitialized: TCastleComponentNotification; |
| 682 |
procedure PhysicsPostStep(const RigidBody: TKraftRigidBody; const TimeStep: TKraftTimeStep); |
| 683 |
{ Assign or unassign PhysicsPostStep in TKraftBody.OnPostStep when needed. } |
| 684 |
procedure CheckPhysicsPostStepNeeded; |
| 685 |
|
| 686 |
{ Updates Kraft rigid body (FKraftBody) type krbtDynamic, krbtKinematic, krbtStatic |
| 687 |
based on Dynamic and Animated properties. |
| 688 |
|
| 689 |
Note that some colliders force the body type to krbtStatic if they only support static colliders |
| 690 |
by doing "ARigidBody.RigidBodyType := krbtStatic" in CreateKraftShape, |
| 691 |
which is after this call. } |
| 692 |
procedure UpdateKraftRigidBodyType; |
| 693 |
|
| 694 |
{ Changes Kraft GravityScale based on Gravity property. Used in SetGravity |
| 695 |
and InitializeEngineRigidBody. } |
| 696 |
procedure UpdateKraftGravity; |
| 697 |
private |
| 698 |
FKraftBody: TKraftRigidBody; |
| 699 |
FGravity: Boolean; |
| 700 |
FDynamic: Boolean; |
| 701 |
FAnimated: Boolean; |
| 702 |
FTrigger: Boolean; |
| 703 |
FCollisionDetection: TCollisionDetection; |
| 704 |
FExists: Boolean; |
| 705 |
FLockTranslation: T3DCoords; |
| 706 |
FLockRotation: T3DCoords; |
| 707 |
FAngularVelocity: TVector3; |
| 708 |
FAngularVelocityDamp: Single; |
| 709 |
FMaxAngularVelocity: Single; |
| 710 |
FLinearVelocity: TVector3; |
| 711 |
FLinearVelocityDamp: Single; |
| 712 |
FMaxLinearVelocity: Single; |
| 713 |
|
| 714 |
FCollisionList: TCastleTransformList; |
| 715 |
|
| 716 |
{ Transform for which we initialized the physics objects or nil } |
| 717 |
FTransform: TCastleTransform; |
| 718 |
|
| 719 |
{ Get appropriate TKraftShape (from TCastleCollider). } |
| 720 |
function GetKraftShape: TKraftShape; |
| 721 |
|
| 722 |
{ Updates existence state of all physics engine objects - body and collider. } |
| 723 |
procedure UpdateExist; |
| 724 |
{ Updates existence state of physics engine body. } |
| 725 |
procedure UpdateExistBody; |
| 726 |
{ Updates colision detection type (discrete, continous) of physics engine body. } |
| 727 |
procedure UpdateCollisionDetection; |
| 728 |
{ Updates axes that have translation lock and call Finish if needed } |
| 729 |
procedure UpdateLockTranslation; |
| 730 |
{ Updates axes that have rotation lock and call Finish if needed } |
| 731 |
procedure UpdateLockRotation; |
| 732 |
{ Updates the collision layer on which the body is located } |
| 733 |
procedure UpdateLayer; |
| 734 |
|
| 735 |
{ Sets all values from Kraft to CGE private fields. Currently angular and |
| 736 |
linear velocity. } |
| 737 |
procedure SynchronizeFromKraft; |
| 738 |
|
| 739 |
{ Calls FKraftBody.Finish, if the body is already initialized (in stateReady). |
| 740 |
This is required after changing various properties in Kraft body/collider. } |
| 741 |
procedure KraftForceUpdatingReadyBody; |
| 742 |
|
| 743 |
procedure SetWorldTransformation(const WorldTransform: TMatrix4); |
| 744 |
procedure SetLockTranslation(const AValue: T3DCoords); |
| 745 |
procedure SetLockRotation(const AValue: T3DCoords); |
| 746 |
|
| 747 |
procedure SetAngularVelocity(const AVelocity: TVector3); |
| 748 |
procedure SetAngularVelocityDamp(const AValue: Single); |
| 749 |
procedure SetMaxAngularVelocity(const AValue: Single); |
| 750 |
|
| 751 |
procedure SetLinearVelocity(const LVelocity: TVector3); |
| 752 |
procedure SetLinearVelocityDamp(const AValue: Single); |
| 753 |
procedure SetMaxLinearVelocity(const AValue: Single); |
| 754 |
|
| 755 |
procedure SetOnCollisionEnter(const AValue: TCollisionEvent); |
| 756 |
procedure SetOnCollisionStay(const AValue: TCollisionEvent); |
| 757 |
procedure SetOnCollisionExit(const AValue: TCollisionEvent); |
| 758 |
|
| 759 |
procedure SetCollisionDetection(const AValue: TCollisionDetection); |
| 760 |
|
| 761 |
procedure SetLayer(const AValue: TPhysicsLayer); |
| 762 |
|
| 763 |
procedure SetDynamic(const AValue: Boolean); |
| 764 |
procedure SetAnimated(const AValue: Boolean); |
| 765 |
procedure SetGravity(const AValue: Boolean); |
| 766 |
|
| 767 |
procedure SetExists(const Value: Boolean); |
| 768 |
procedure SetTrigger(const Value: Boolean); |
| 769 |
|
| 770 |
{ Creates physics engine object and connects the rigid body with |
| 771 |
@link(TCastleTransform Parent) and @link(TCastleTransform Parent).World. |
| 772 |
|
| 773 |
Initialization is done in three steps: |
| 774 |
1. Creation of Kraft rigid body in InitializeEngineRigidBody |
| 775 |
2. Creation of Kraft shape based on TCastleCollider |
| 776 |
3. Finishing initialization when creation of Kraft shape succeeded } |
| 777 |
procedure InitializePhysicsEngineObjects; |
| 778 |
|
| 779 |
{ Frees physics objects in three steps: |
| 780 |
1. Deinitialize colliders |
| 781 |
2. Removes self from other rigid bodies collision lists |
| 782 |
3. Frees the physics engine rigid body object } |
| 783 |
procedure DeinitializePhysicsEngineObjects; |
| 784 |
|
| 785 |
{ Initialize rigid body objects from physics engine } |
| 786 |
procedure InitializeEngineRigidBody; |
| 787 |
|
| 788 |
{ Initialize collider from physics engine. |
| 789 |
If some collider is set, this moves state to stateReady or raises an exception. |
| 790 |
If no collider is set, this silently exits without updating state. } |
| 791 |
procedure InitializeCollider; |
| 792 |
|
| 793 |
{ Used by TCastleCollider when it's parent changes to handle case when |
| 794 |
rigid body is added before collider behavior } |
| 795 |
procedure CheckInitialization(const ACastleCollider: TCastleCollider); |
| 796 |
|
| 797 |
{ Deinitializes physics engine collider object. } |
| 798 |
procedure DeinitializeCollider; |
| 799 |
|
| 800 |
{ Called by TCastleCollider when it's shape changes } |
| 801 |
procedure ReinitializeCastleCollider; |
| 802 |
|
| 803 |
{ Configure Sender (TCastleRigidBody) using Setup2D. } |
| 804 |
class procedure CreateComponent2D(Sender: TObject); |
| 805 |
|
| 806 |
procedure AddNotificationOnInitialized( |
| 807 |
const AEvent: TComponentEvent); overload; |
| 808 |
{ Calls all callbacks added by AddNotificationOnInitialized } |
| 809 |
procedure NotifyOnInitialized; |
| 810 |
procedure RemoveNotificationOnInitialized( |
| 811 |
const AEvent: TComponentEvent); overload; |
| 812 |
|
| 813 |
procedure AddNotificationBeforeDeinitialized( |
| 814 |
const AEvent: TComponentEvent); overload; |
| 815 |
{ Calls all callbacks added by AddNotificationOnInitialized } |
| 816 |
procedure NotifyBeforeDeinitialized; |
| 817 |
procedure RemoveNotificationBeforeDeinitialized( |
| 818 |
const AEvent: TComponentEvent); overload; |
| 819 |
|
| 820 |
{ Is rigid body full initialized? } |
| 821 |
function IsInitialized: Boolean; |
| 822 |
|
| 823 |
property DuringSettingTransformationFromPhysicsEngine: Boolean |
| 824 |
read FDuringSettingTransformationFromPhysicsEngine; |
| 825 |
protected |
| 826 |
{ Initializes physics engine objects when TCastleRigidBody is attached |
| 827 |
to world. } |
| 828 |
procedure WorldAfterAttach; override; |
| 829 |
|
| 830 |
{ Deinitializes physics engine objects when TCastleRigidBody is attached |
| 831 |
to world. } |
| 832 |
procedure WorldBeforeDetach; override; |
| 833 |
procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); override; |
| 834 |
|
| 835 |
{ Only one TCastleRigidBody behavior can be added to a given |
| 836 |
TCastleTransform so we check that here. } |
| 837 |
function CanAttachToParent(const NewParent: TCastleTransform; |
| 838 |
out ReasonWhyCannot: String): Boolean; override; |
| 839 |
public |
| 840 |
constructor Create(AOwner: TComponent); override; |
| 841 |
destructor Destroy; override; |
| 842 |
|
| 843 |
{ Utility function to set common values for physics in 2D games. |
| 844 |
Locks moving along the Z axis, |
| 845 |
locks rotating along the X and Y axes. } |
| 846 |
procedure Setup2D; |
| 847 |
|
| 848 |
{ Transformations that we collide with currently. } |
| 849 |
function GetCollidingTransforms: TCastleTransformList; |
| 850 |
|
| 851 |
{ First object hit by the ray, calculated using the physics engine. |
| 852 |
|
| 853 |
Returns the TPhysicsRayCastResult record. |
| 854 |
Read TPhysicsRayCastResult.Hit (boolean), TPhysicsRayCastResult.Transform |
| 855 |
(guaranteed to be @nil when TPhysicsRayCastResult.Hit is @false) and other fields |
| 856 |
to know what was hit. |
| 857 |
|
| 858 |
The given RayOrigin, RayDirection, MaxDistance are in the parent |
| 859 |
coordinate system of associated TCastleTransform (@link(TCastleBehavior.Parent)). |
| 860 |
So for example query like this works naturally: |
| 861 |
|
| 862 |
@longCode(# |
| 863 |
RBody := MyTransform.FindBehavior(TCastleRigidBody) as TCastleRigidBody; |
| 864 |
Hit := RBody.RayCast(MyTransform.Translation, MyTransform.Direction, MaxDistance); |
| 865 |
#) |
| 866 |
|
| 867 |
It returns TPhysicsRayCastResult, with information there |
| 868 |
consistently in the same coordinate system as inputs. |
| 869 |
So TPhysicsRayCastResult.Distance, TPhysicsRayCastResult.Point, TPhysicsRayCastResult.Normal |
| 870 |
are in parent coordinate system of associated TCastleTransform (@link(TCastleBehavior.Parent)). |
| 871 |
|
| 872 |
This ignores the collider of this rigid body (to not accidentally collide |
| 873 |
with your own collider), and checks collisions with the rest of the world in |
| 874 |
given max distance. |
| 875 |
Only collisions with the physics colliders (TCastleCollider) |
| 876 |
are considered. |
| 877 |
|
| 878 |
Note: The @link(TCastleTransform.Pickable) property is ignored by this method, |
| 879 |
i.e. it considers all colliders regardless of their @link(TCastleTransform.Pickable) value. |
| 880 |
The @link(TCastleTransform.Pickable) is only taken into account by the routines |
| 881 |
of the old physics system |
| 882 |
(see https://castle-engine.io/physics#_old_system_for_collisions_and_gravity ). |
| 883 |
In the new system, a similar role will be filled by layers. } |
| 884 |
function PhysicsRayCast(const RayOrigin, RayDirection: TVector3; |
| 885 |
const MaxDistance: Single = MaxSingle): TPhysicsRayCastResult; |
| 886 |
|
| 887 |
function PropertySections(const PropertyName: String): TPropertySections; override; |
| 888 |
|
| 889 |
{ Push this rigid body. |
| 890 |
The body is pushed from a Position and along the direction of Force. |
| 891 |
Longer length of Force makes a stronger push. |
| 892 |
|
| 893 |
The forces affecting each body are reset every frame |
| 894 |
(only the body velocity is preserved across frames). |
| 895 |
If you want to keep applying this force (e.g. it is a wind that continues pushing in given direction) |
| 896 |
you should call this method every frame. |
| 897 |
It automatically accounts for the delta time (because the force will actually |
| 898 |
be applied later, with delta time, to velocity) so no need to multiply the arguments with SecondsPassed. |
| 899 |
That is, adding force means @code(Velocity += Force * SecondsPassed / Mass). |
| 900 |
|
| 901 |
By changing Position from which you push, |
| 902 |
you can change the angular velocity, |
| 903 |
i.e. different Position makes the body spin in different ways. |
| 904 |
Note that Position too distant from the body center may result in unrealistically strong push. |
| 905 |
If Position is exactly at body center, then angular velocity will not be affected. |
| 906 |
|
| 907 |
Force and Position are in the world coordinate system. } |
| 908 |
procedure AddForceAtPosition(const Force, Position: TVector3); |
| 909 |
|
| 910 |
{ Push this rigid body. |
| 911 |
The body is pushed along the direction of Force. |
| 912 |
Longer length of Force makes a stronger push. |
| 913 |
|
| 914 |
This is similar to @link(AddForceAtPosition), but the Force (direction) |
| 915 |
can be in local or global coordinate system |
| 916 |
(depending on ForceInLocalCoordinates). |
| 917 |
Moreover it doesn't take as parameter any Position: |
| 918 |
the force always acts from the origin of this body. |
| 919 |
|
| 920 |
Just like with @link(AddForceAtPosition), |
| 921 |
the forces affecting each body are reset every frame |
| 922 |
(only the body velocity is preserved across frames). |
| 923 |
If you want to keep applying this force (e.g. it is a wind that continues pushing in given direction) |
| 924 |
you should call this method every frame. |
| 925 |
It automatically accounts for the delta time (because the force will actually |
| 926 |
be applied later, with delta time, to velocity) so no need to multiply the arguments with SecondsPassed. } |
| 927 |
procedure AddForce(const Force: TVector3; const ForceInLocalCoordinates: Boolean); |
| 928 |
|
| 929 |
{ Rotate this rigid body with physics. |
| 930 |
Longer length of Torque makes a stronger push. |
| 931 |
Torque is in world coordinates. |
| 932 |
|
| 933 |
Just like with @link(AddForceAtPosition), |
| 934 |
the forces affecting each body are reset every frame |
| 935 |
(only the body velocity is preserved across frames). |
| 936 |
If you want to keep applying this force (e.g. it is a whirlwind that continues rotating) |
| 937 |
you should call this method every frame. |
| 938 |
It automatically accounts for the delta time (because the force will actually |
| 939 |
be applied later, with delta time, to velocity) so no need to multiply the arguments with SecondsPassed. } |
| 940 |
procedure AddTorque(const Torque: TVector3); |
| 941 |
|
| 942 |
{ Apply a one-time instant increase in speed, that pushes the body (increasing velocity). |
| 943 |
Impulse is a direction along which to push, Point is the position from which you push. |
| 944 |
Longer length of Impulse makes a stronger push. |
| 945 |
|
| 946 |
Impulse and Point are both in world coordinates. |
| 947 |
|
| 948 |
Adding impulse means @code(Velocity += Force / Mass). |
| 949 |
To be more precise, adding impulse directly increases @link(LinearVelocity) and @link(AngularVelocity). |
| 950 |
Unlike @link(AddForceAtPosition), the velocity increase is not multiplied by the delta of time, |
| 951 |
so it is not expected you will call this every frame. |
| 952 |
(If you do, you should take care to multiply Impulse by SecondsPassed.) |
| 953 |
|
| 954 |
Same notes as for Position of @link(AddForceAtPosition): |
| 955 |
By changing Point from which you push, |
| 956 |
you can change the angular velocity, |
| 957 |
i.e. different Point makes the body spin in different ways. |
| 958 |
Note that Point too distant from the body center may result in unrealistically strong push. |
| 959 |
If Point is exactly at body center, then angular velocity will not be affected. } |
| 960 |
procedure ApplyImpulse(const Impulse, Point: TVector3); |
| 961 |
|
| 962 |
{ Returns true when rigid body behavior exists, and is added to Castle |
| 963 |
Transform, and this transform ExistsInRoot = true. } |
| 964 |
function ExistsInRoot: Boolean; |
| 965 |
|
| 966 |
{ For performance, physics engine sometimes puts some body to "sleep", |
| 967 |
which means it will not move anymore, |
| 968 |
because it didn't move (much) in the recent frames. |
| 969 |
In general, the body should be "woken up" automatically when something collides |
| 970 |
with it, so the mechanism should be invisible to you... but sometimes it is necessary |
| 971 |
to wake up a body explicitly. } |
| 972 |
procedure WakeUp; |
| 973 |
|
| 974 |
//procedure Sleep; |
| 975 |
|
| 976 |
{ Current rotating velocity of this body. |
| 977 |
You can query it (as it changes, affected by forces) and set it at any point. |
| 978 |
In world coordinates. |
| 979 |
|
| 980 |
See https://en.wikipedia.org/wiki/Angular_velocity |
| 981 |
about the exact meaning of angular velocity. The vector direction |
| 982 |
(AngularVelocity.Normalize) determines the axis around which we rotate. |
| 983 |
The vector length (AngularVelocity.Length) determines the speed (in radians/second) |
| 984 |
with which we rotate. } |
| 985 |
property AngularVelocity: TVector3 read FAngularVelocity write SetAngularVelocity; |
| 986 |
|
| 987 |
{ Current moving velocity of this body. |
| 988 |
You can query it (as it changes, affected by forces) and set it at any point. |
| 989 |
In world coordinates. } |
| 990 |
property LinearVelocity: TVector3 read FLinearVelocity write SetLinearVelocity; |
| 991 |
|
| 992 |
{$ifdef FPC} |
| 993 |
property InitialAngularVelocity: TVector3 read FAngularVelocity write SetAngularVelocity; |
| 994 |
deprecated 'use AngularVelocity'; |
| 995 |
property InitialLinearVelocity: TVector3 read FLinearVelocity write SetLinearVelocity; |
| 996 |
deprecated 'use LinearVelocity'; |
| 997 |
{$endif} |
| 998 |
|
| 999 |
{ Occurs when TCastleRigidBody starts colliding with another TCastleRigidBody. |
| 1000 |
|
| 1001 |
It can occur repeatedly for the same body (in the same time instant) |
| 1002 |
if the collision has many points of contact. |
| 1003 |
|
| 1004 |
@italic(Warning:) Do not free the related @link(TCastleTransform) |
| 1005 |
or @link(TCastleRigidBody) or @link(TCastleCollider) components |
| 1006 |
upon receiving this event. |
| 1007 |
Right now, it would free an underlying physics engine object, |
| 1008 |
and this would crash the physics engine. |
| 1009 |
|
| 1010 |
Instead, you can: |
| 1011 |
|
| 1012 |
@unorderedList( |
| 1013 |
@item(Schedule any component to free it later, using |
| 1014 |
@link(TCastleApplicationProperties.FreeDelayed ApplicationProperties.FreeDelayed).) |
| 1015 |
@item(Schedule @link(TCastleTransform) for removal/freeing later using |
| 1016 |
@link(TCastleTransform.RemoveDelayed).) |
| 1017 |
@item(Or set @link(TCastleTransform.Exists) to @false |
| 1018 |
and maybe free it later using your own mechanism.) |
| 1019 |
) } |
| 1020 |
property OnCollisionEnter: TCollisionEvent read FOnCollisionEnter write SetOnCollisionEnter; |
| 1021 |
|
| 1022 |
{ Occurs when TCastleRigidBody stops colliding with another TCastleRigidBody. |
| 1023 |
|
| 1024 |
Just like at @link(OnCollisionEnter): |
| 1025 |
Do not free the related components upon receiving this event. |
| 1026 |
See the @link(OnCollisionEnter) documentation for details |
| 1027 |
of this limitation and solutions. } |
| 1028 |
property OnCollisionExit: TCollisionEvent read FOnCollisionExit write SetOnCollisionExit; |
| 1029 |
|
| 1030 |
{ Occurs when TCastleRigidBody still collides with another TCastleRigidBody. |
| 1031 |
|
| 1032 |
Just like at @link(OnCollisionEnter): |
| 1033 |
Do not free the related components upon receiving this event. |
| 1034 |
See the @link(OnCollisionEnter) documentation for details |
| 1035 |
of this limitation and solutions. } |
| 1036 |
property OnCollisionStay: TCollisionEvent read FOnCollisionStay write SetOnCollisionStay; |
| 1037 |
published |
| 1038 |
{ Does the physics simulation move and rotate this object |
| 1039 |
(because of gravity, or because it collides with others). |
| 1040 |
|
| 1041 |
When @false the object is not transformed by the physics simulation. |
| 1042 |
It still collides with other physical objects. |
| 1043 |
So it's a static collidable body that will not move on any collision / force. } |
| 1044 |
property Dynamic: Boolean read FDynamic write SetDynamic default true; |
| 1045 |
|
| 1046 |
{ Is the transformation of this object updated often |
| 1047 |
(relevant only when @link(Dynamic) = @false). |
| 1048 |
|
| 1049 |
This property is taken into account only if @link(Dynamic) = @false. |
| 1050 |
|
| 1051 |
This property is an optimization hint to the physics engine, |
| 1052 |
it says @italic(how often) you will change the transformation. |
| 1053 |
|
| 1054 |
@definitionList( |
| 1055 |
@itemLabel true (animated object, also known as "kinematic") |
| 1056 |
@item( |
| 1057 |
The physics engine is prepared that this object can move often, |
| 1058 |
e.g. every frame, so you can animate the related @link(TCastleTransform) |
| 1059 |
using any technique. |
| 1060 |
) |
| 1061 |
|
| 1062 |
@itemLabel false (static object) |
| 1063 |
@item( |
| 1064 |
Changing the transformation properties is costly, |
| 1065 |
it may even be like destroying this object |
| 1066 |
and creating a new one from the point of view of the physics engine, |
| 1067 |
@italic(so do not change the transformation often, e.g. every frame). |
| 1068 |
|
| 1069 |
The upside is that collisions with static objects may be much more |
| 1070 |
optimized, since the physics engine can assume that all the static |
| 1071 |
objects form a completely frozen unmovable geometry in the world. |
| 1072 |
) |
| 1073 |
) |
| 1074 |
} |
| 1075 |
property Animated: Boolean read FAnimated write SetAnimated default false; |
| 1076 |
|
| 1077 |
{ Triggers report when other object collides with them, |
| 1078 |
but still allow the other object to pass through. |
| 1079 |
In other words, colliding with a trigger will not cause the collider to stop or |
| 1080 |
"bounce off" the trigger. |
| 1081 |
|
| 1082 |
They are useful as sensors. E.g. a trigger may be a coin (like in "Mario") |
| 1083 |
that the player can "consume" by colliding with it. |
| 1084 |
|
| 1085 |
Triggers report collisions through the same events as other rigid bodies: |
| 1086 |
(@link(TCastleRigidBody.OnCollisionEnter), @link(TCastleRigidBody.OnCollisionStay), |
| 1087 |
@link(TCastleRigidBody.OnCollisionExit)). } |
| 1088 |
property Trigger: Boolean read FTrigger write SetTrigger default false; |
| 1089 |
|
| 1090 |
{ Sets CollisionDetectionMode in rigid body to Discrete or ContinuousSweep. } |
| 1091 |
property CollisionDetection: TCollisionDetection read FCollisionDetection |
| 1092 |
write SetCollisionDetection default cdDiscrete; |
| 1093 |
|
| 1094 |
{ Physics layer of the rigid body determines with which other bodies it may collide. |
| 1095 |
|
| 1096 |
The way layers interact is configured in the |
| 1097 |
@link(TPhysicsProperties.LayerCollisions MyViewport.Items.PhysicsProperties.LayerCollisions). |
| 1098 |
|
| 1099 |
Each layer can also have name and description. You can set |
| 1100 |
them using the |
| 1101 |
@link(TPhysicsProperties.LayerNames MyViewport.Items.PhysicsProperties.LayerNames) |
| 1102 |
property. } |
| 1103 |
property Layer: TPhysicsLayer read FLayer write SetLayer default 0; |
| 1104 |
|
| 1105 |
{ Is this object affected by gravity. } |
| 1106 |
property Gravity: Boolean read FGravity write SetGravity default true; |
| 1107 |
|
| 1108 |
{ Disable motion (@link(TCastleTransform.Translation) change) along |
| 1109 |
the particular (world) axis. |
| 1110 |
|
| 1111 |
For 2D games, you will usually want to disable motion along the Z axis. |
| 1112 |
Instead of directly changing this property, |
| 1113 |
you can achieve this by calling @link(Setup2D). } |
| 1114 |
property LockTranslation: T3DCoords read FLockTranslation write SetLockTranslation default []; |
| 1115 |
|
| 1116 |
{ Disable rotation (@link(TCastleTransform.Rotation) change) along |
| 1117 |
the particular (world) axis. |
| 1118 |
|
| 1119 |
For 2D games, you will usually want to disable rotation along the X and Y axes. |
| 1120 |
Instead of directly changing this property, |
| 1121 |
you can achieve this by calling @link(Setup2D). } |
| 1122 |
property LockRotation: T3DCoords read FLockRotation write SetLockRotation default []; |
| 1123 |
|
| 1124 |
{ Controls whether the rigid body is actually processed by the physics engine. |
| 1125 |
When this is @false, the rigid body is not updated by the physics engine, |
| 1126 |
it does not cause collisions with other rigid bodies |
| 1127 |
and it does not receive events like @link(OnCollisionEnter), |
| 1128 |
@link(OnCollisionStay), @link(OnCollisionExit). } |
| 1129 |
property Exists: Boolean read FExists write SetExists default true; |
| 1130 |
|
| 1131 |
{ Damping means that the velocity will decrease over time. |
| 1132 |
AngularVelocityDamp causes AngularVelocity to decrease over time. |
| 1133 |
For the exact equations how it works, see @link(LinearVelocityDamp). } |
| 1134 |
property AngularVelocityDamp: Single read FAngularVelocityDamp write SetAngularVelocityDamp {$ifdef FPC}default 0.1{$endif}; |
| 1135 |
property MaxAngularVelocity: Single read FMaxAngularVelocity write SetMaxAngularVelocity; |
| 1136 |
|
| 1137 |
{ Damping means that the velocity will decrease over time. |
| 1138 |
LinearVelocityDamp causes LinearVelocity to decrease over time, |
| 1139 |
similar AngularVelocityDamp causes AngularVelocity to decrease over time. |
| 1140 |
|
| 1141 |
Values from 0.0 up to infinity make sense. |
| 1142 |
|
| 1143 |
Exact interpretation: |
| 1144 |
|
| 1145 |
The damping is applied every "physics frame" following this equation: |
| 1146 |
|
| 1147 |
@code(LinearVelocity := LinearVelocity * 1 / (1 + LinearVelocityDamp * 1/PhysicsProperties.Frequency)) |
| 1148 |
|
| 1149 |
Where @code(PhysicsProperties.Frequency) is by default 60, |
| 1150 |
and can be customized for each viewport using @link(TPhysicsProperties.Frequency |
| 1151 |
Viewport.Items.PhysicsProperties.Frequency). The frequency also determines how |
| 1152 |
often do "physics frames" occur. |
| 1153 |
|
| 1154 |
In effect, damping = 0 means that no damping occurs. |
| 1155 |
|
| 1156 |
Damping values > 0 means that LinearVelocity decreases with time, |
| 1157 |
larger LinearVelocityDamp -> the faster LinearVelocity will decrease. |
| 1158 |
|
| 1159 |
The meaning of damping = 1.0 depends on @link(TPhysicsProperties.Frequency |
| 1160 |
Viewport.Items.PhysicsProperties.Frequency): |
| 1161 |
|
| 1162 |
@unorderedList( |
| 1163 |
@item(With TPhysicsProperties.Frequency = 60 (default), the XxxVelocityDamp = 1.0 implies that |
| 1164 |
the velocity drops to ~0.37 of original after 1 second.) |
| 1165 |
|
| 1166 |
@item(With TPhysicsProperties.Frequency = 1 |
| 1167 |
(crazy small, just giving it as example), |
| 1168 |
the XxxVelocityDamp = 1.0 implies that the velocity drops to half of original after 1 second.) |
| 1169 |
|
| 1170 |
@item(With TPhysicsProperties.Frequency = 10000 |
| 1171 |
(crazy large, just giving it as example), |
| 1172 |
the XxxVelocityDamp = 1.0 implies that the velocity drops to ~0.36 of original after 1 second.) |
| 1173 |
) |
| 1174 |
} |
| 1175 |
property LinearVelocityDamp: Single read FLinearVelocityDamp write SetLinearVelocityDamp {$ifdef FPC}default 0.1{$endif}; |
| 1176 |
property MaxLinearVelocity: Single read FMaxLinearVelocity write SetMaxLinearVelocity; |
| 1177 |
|
| 1178 |
{$define read_interface_class} |
| 1179 |
{$I auto_generated_persistent_vectors/tcastlerigidbody_persistent_vectors.inc} |
| 1180 |
{$undef read_interface_class} |
| 1181 |
end; |
| 1182 |
|
| 1183 |
{$endif read_interface} |
| 1184 |
|
| 1185 |
{$ifdef read_implementation} |
| 1186 |
|
| 1187 |
{ utilities ------------------------------------------------------------------ } |
| 1188 |
|
| 1189 |
function VectorToKraft(const V: TVector3): TKraftVector3; |
| 1190 |
begin |
| 1191 |
// simple implementation |
| 1192 |
// Result.X := V.X; |
| 1193 |
// Result.Y := V.Y; |
| 1194 |
// Result.Z := V.Z; |
| 1195 |
|
| 1196 |
// optimized implementation |
| 1197 |
Assert(SizeOf(TKraftScalar) = SizeOf(Single)); |
| 1198 |
Move(V, Result, SizeOf(V)); |
| 1199 |
end; |
| 1200 |
|
| 1201 |
function VectorFromKraft(const V: TKraftVector3): TVector3; |
| 1202 |
begin |
| 1203 |
// optimized implementation |
| 1204 |
Assert(SizeOf(TKraftScalar) = SizeOf(Single)); |
| 1205 |
Move(V, Result, SizeOf(V)); |
| 1206 |
end; |
| 1207 |
|
| 1208 |
function MatrixToKraft(const M: TMatrix4): TKraftMatrix4x4; |
| 1209 |
begin |
| 1210 |
Assert(SizeOf(M) = SizeOf(Result)); |
| 1211 |
// simply copy the contents, |
| 1212 |
// memory layout is the same (column-major, Single precision) |
| 1213 |
Move(M, Result, SizeOf(M)); |
| 1214 |
end; |
| 1215 |
|
| 1216 |
function MatrixFromKraft(const M: TKraftMatrix4x4): TMatrix4; |
| 1217 |
begin |
| 1218 |
Assert(SizeOf(M) = SizeOf(Result)); |
| 1219 |
Move(M, Result, SizeOf(M)); |
| 1220 |
end; |
| 1221 |
|
| 1222 |
procedure ColliderVisualizationConfigBase(const Transform: TCastleTransform); |
| 1223 |
begin |
| 1224 |
Transform.SetTransient; |
| 1225 |
|
| 1226 |
Transform.Collides := false; |
| 1227 |
Transform.Pickable := false; |
| 1228 |
Transform.CastShadows := false; |
| 1229 |
Transform.InternalExcludeFromParentBoundingVolume := true;; |
| 1230 |
end; |
| 1231 |
|
| 1232 |
procedure ColliderVisualizationConfig(const Primitive: TCastleAbstractPrimitive); |
| 1233 |
begin |
| 1234 |
ColliderVisualizationConfigBase(Primitive); |
| 1235 |
Primitive.Color := Vector4(HexToColorRGB('FC9C2D'), 0.8); |
| 1236 |
Primitive.Material := pmUnlit; |
| 1237 |
Primitive.RenderOptions.LineWidth := 3; |
| 1238 |
Primitive.RenderOptions.WireframeColor := HexToColorRGB('FC9C2D'); |
| 1239 |
Primitive.RenderOptions.WireframeEffect := weWireframeOnly; |
| 1240 |
end; |
| 1241 |
|
| 1242 |
{ TCastleLayerCollisions ----------------------------------------------------- } |
| 1243 |
|
| 1244 |
function TCastleLayerCollisions.GetCollides(const Layer1, Layer2: TPhysicsLayer): Boolean; |
| 1245 |
begin |
| 1246 |
Result := Layer2 in FCollides[Layer1]; |
| 1247 |
Assert(Result = (Layer1 in FCollides[Layer2])); |
| 1248 |
end; |
| 1249 |
|
| 1250 |
procedure TCastleLayerCollisions.SetCollides(const Layer1, |
| 1251 |
Layer2: TPhysicsLayer; const AValue: Boolean); |
| 1252 |
begin |
| 1253 |
if AValue then |
| 1254 |
begin |
| 1255 |
Include(FCollides[Layer1], Layer2); |
| 1256 |
Include(FCollides[Layer2], Layer1); |
| 1257 |
end else |
| 1258 |
begin |
| 1259 |
Exclude(FCollides[Layer1], Layer2); |
| 1260 |
Exclude(FCollides[Layer2], Layer1); |
| 1261 |
end; |
| 1262 |
UpdateRigidBodies; |
| 1263 |
end; |
| 1264 |
|
| 1265 |
procedure TCastleLayerCollisions.UpdateRigidBodies; |
| 1266 |
var |
| 1267 |
RigidBodyList: TCastleBehaviorList; |
| 1268 |
RootTransform: TCastleAbstractRootTransform; |
| 1269 |
Behavior: TCastleBehavior; |
| 1270 |
begin |
| 1271 |
if not (Owner is TPhysicsProperties) then |
| 1272 |
Exit; |
| 1273 |
|
| 1274 |
if Owner.Owner is TCastleAbstractRootTransform then |
| 1275 |
begin |
| 1276 |
RootTransform := Owner.Owner as TCastleAbstractRootTransform; |
| 1277 |
RigidBodyList := RootTransform.FindAllBehaviors(TCastleRigidBody); |
| 1278 |
try |
| 1279 |
for Behavior in RigidBodyList do |
| 1280 |
TCastleRigidBody(Behavior).UpdateLayer; |
| 1281 |
finally |
| 1282 |
FreeAndNil(RigidBodyList); |
| 1283 |
end; |
| 1284 |
end; |
| 1285 |
end; |
| 1286 |
|
| 1287 |
constructor TCastleLayerCollisions.Create(AOwner: TComponent); |
| 1288 |
var |
| 1289 |
L: TPhysicsLayer; |
| 1290 |
begin |
| 1291 |
inherited Create(AOwner); |
| 1292 |
|
| 1293 |
// assign default state for FCollides |
| 1294 |
for L := Low(L) to High(L) do |
| 1295 |
FCollides[L] := DefaultCollides(L); |
| 1296 |
UpdateRigidBodies; |
| 1297 |
end; |
| 1298 |
|
| 1299 |
function TCastleLayerCollisions.DefaultCollides(const Layer: TPhysicsLayer): TPhysicsLayers; |
| 1300 |
begin |
| 1301 |
// By default each layer collides with itself |
| 1302 |
Result := [Layer]; |
| 1303 |
end; |
| 1304 |
|
| 1305 |
procedure TCastleLayerCollisions.CustomSerialization( |
| 1306 |
const SerializationProcess: TSerializationProcess); |
| 1307 |
|
| 1308 |
procedure FixBirectionalCollisions(var NeedsUpdate: Boolean); |
| 1309 |
var |
| 1310 |
L1, L2: TPhysicsLayer; |
| 1311 |
begin |
| 1312 |
for L1 := Low(TPhysicsLayer) to High(TPhysicsLayer) do |
| 1313 |
for L2 := Low(TPhysicsLayer) to High(TPhysicsLayer) do |
| 1314 |
if ((L2 in FCollides[L1]) <> (L1 in FCollides[L2])) then |
| 1315 |
begin |
| 1316 |
// if there's a mismatch, assume the right state is "collides" |
| 1317 |
Include(FCollides[L1], L2); |
| 1318 |
Include(FCollides[L2], L1); |
| 1319 |
NeedsUpdate := true; |
| 1320 |
end; |
| 1321 |
end; |
| 1322 |
|
| 1323 |
var |
| 1324 |
I: TPhysicsLayer; |
| 1325 |
OldCollidesWithInt, NewCollidesWithInt: Int32; |
| 1326 |
NeedsUpdate: Boolean; |
| 1327 |
begin |
| 1328 |
inherited; |
| 1329 |
|
| 1330 |
Assert(SizeOf(Int32) = SizeOf(TPhysicsLayers)); |
| 1331 |
|
| 1332 |
NeedsUpdate := false; |
| 1333 |
for I := Low(TPhysicsLayer) to High(TPhysicsLayer) do |
| 1334 |
begin |
| 1335 |
Move(FCollides[I], OldCollidesWithInt, SizeOf(Int32)); |
| 1336 |
NewCollidesWithInt := OldCollidesWithInt; |
| 1337 |
|
| 1338 |
SerializationProcess.ReadWriteInteger('Collides' + IntToStr(I), |
| 1339 |
NewCollidesWithInt, FCollides[I] <> DefaultCollides(I)); |
| 1340 |
|
| 1341 |
if OldCollidesWithInt <> NewCollidesWithInt then |
| 1342 |
begin |
| 1343 |
NeedsUpdate := true; |
| 1344 |
Move(NewCollidesWithInt, FCollides[I], SizeOf(Int32)); |
| 1345 |
end; |
| 1346 |
end; |
| 1347 |
|
| 1348 |
FixBirectionalCollisions(NeedsUpdate); |
| 1349 |
|
| 1350 |
if NeedsUpdate then |
| 1351 |
UpdateRigidBodies; |
| 1352 |
end; |
| 1353 |
|
| 1354 |
{ TCastleLayerNames --------------------------------------------------------- } |
| 1355 |
|
| 1356 |
function TCastleLayerNames.GetLayerNames(const Layer: TPhysicsLayer): String; |
| 1357 |
begin |
| 1358 |
Result := FLayerNames[Layer]; |
| 1359 |
end; |
| 1360 |
|
| 1361 |
procedure TCastleLayerNames.SetLayerNames(const Layer: TPhysicsLayer; |
| 1362 |
const AValue: String); |
| 1363 |
begin |
| 1364 |
FLayerNames[Layer] := AValue; |
| 1365 |
end; |
| 1366 |
|
| 1367 |
function TCastleLayerNames.GetLayerDescriptions( |
| 1368 |
const Layer: TPhysicsLayer): String; |
| 1369 |
begin |
| 1370 |
Result := FLayerDescriptions[Layer]; |
| 1371 |
end; |
| 1372 |
|
| 1373 |
procedure TCastleLayerNames.SetLayerDescriptions(const Layer: TPhysicsLayer; |
| 1374 |
const AValue: String); |
| 1375 |
begin |
| 1376 |
FLayerDescriptions[Layer] := AValue; |
| 1377 |
end; |
| 1378 |
|
| 1379 |
procedure TCastleLayerNames.CustomSerialization( |
| 1380 |
const SerializationProcess: TSerializationProcess); |
| 1381 |
var |
| 1382 |
I: TPhysicsLayer; |
| 1383 |
Value: String; |
| 1384 |
begin |
| 1385 |
inherited; |
| 1386 |
|
| 1387 |
for I := Low(TPhysicsLayer) to High(TPhysicsLayer) do |
| 1388 |
begin |
| 1389 |
Value := FLayerNames[I]; |
| 1390 |
SerializationProcess.ReadWriteString('Name' + IntToStr(I), Value, Value <> ''); |
| 1391 |
FLayerNames[I] := Value; |
| 1392 |
|
| 1393 |
Value := FLayerDescriptions[I]; |
| 1394 |
SerializationProcess.ReadWriteString('Description' + IntToStr(I), Value, Value <> ''); |
| 1395 |
FLayerDescriptions[I] := Value; |
| 1396 |
end; |
| 1397 |
end; |
| 1398 |
|
| 1399 |
{ TPhysicsCollisionDetails --------------------------------------------------- } |
| 1400 |
|
| 1401 |
function TPhysicsCollisionDetails.Sender: TCastleTransform; |
| 1402 |
begin |
| 1403 |
Result := Transforms[0]; |
| 1404 |
end; |
| 1405 |
|
| 1406 |
function TPhysicsCollisionDetails.OtherTransform: TCastleTransform; |
| 1407 |
begin |
| 1408 |
Result := Transforms[1]; |
| 1409 |
end; |
| 1410 |
|
| 1411 |
{ TPhysicsProperties --------------------------------------------------------- } |
| 1412 |
|
| 1413 |
constructor TPhysicsProperties.Create(AOwner: TComponent); |
| 1414 |
begin |
| 1415 |
inherited Create(AOwner); |
| 1416 |
FAngularVelocityRK4Integration := DefaultAngularVelocityRK4Integration; |
| 1417 |
FLinearVelocityRK4Integration := DefaultLinearVelocityRK4Integration; |
| 1418 |
FFrequency := DefaultFrequency; |
| 1419 |
FGravityStrength := DefaultGravityStrength; |
| 1420 |
FPhysicsTimeStep := 1.0 / FFrequency; |
| 1421 |
FMaxPhysicsTicksPerUpdate := DefaultMaxPhysicsTicksPerUpdate; |
| 1422 |
FContinuousCollisionDetection := DefaultContinuousCollisionDetection; |
| 1423 |
FLayerNames := TCastleLayerNames.Create(Self); |
| 1424 |
FLayerNames.Name := 'LayerNames'; |
| 1425 |
FLayerNames.SetSubComponent(true); |
| 1426 |
FLayerCollisions := TCastleLayerCollisions.Create(Self); |
| 1427 |
FLayerCollisions.Name := 'LayerCollisions'; |
| 1428 |
FLayerCollisions.SetSubComponent(true); |
| 1429 |
end; |
| 1430 |
|
| 1431 |
destructor TPhysicsProperties.Destroy; |
| 1432 |
begin |
| 1433 |
FreeAndNil(FLayerNames); |
| 1434 |
FreeAndNil(FLayerCollisions); |
| 1435 |
inherited Destroy; |
| 1436 |
end; |
| 1437 |
|
| 1438 |
procedure TPhysicsProperties.SetAngularVelocityRK4Integration(const AValue: Boolean); |
| 1439 |
begin |
| 1440 |
if FAngularVelocityRK4Integration <> AValue then |
| 1441 |
begin |
| 1442 |
FAngularVelocityRK4Integration := AValue; |
| 1443 |
if Assigned(RootTransform.FKraftEngine) then |
| 1444 |
RootTransform.FKraftEngine.AngularVelocityRK4Integration := AValue; |
| 1445 |
end; |
| 1446 |
end; |
| 1447 |
|
| 1448 |
procedure TPhysicsProperties.SetFrequency(const AValue: Single); |
| 1449 |
begin |
| 1450 |
if FFrequency <> AValue then |
| 1451 |
begin |
| 1452 |
FFrequency := AValue; |
| 1453 |
FPhysicsTimeStep := 1.0 / FFrequency; |
| 1454 |
|
| 1455 |
if Assigned(RootTransform.FKraftEngine) then |
| 1456 |
RootTransform.FKraftEngine.SetFrequency(AValue); |
| 1457 |
end; |
| 1458 |
end; |
| 1459 |
|
| 1460 |
procedure TPhysicsProperties.SetContinuousCollisionDetection( |
| 1461 |
const AValue: Boolean); |
| 1462 |
begin |
| 1463 |
if FContinuousCollisionDetection <> AValue then |
| 1464 |
begin |
| 1465 |
FContinuousCollisionDetection := AValue; |
| 1466 |
if Assigned(RootTransform.FKraftEngine) then |
| 1467 |
if AValue then |
| 1468 |
RootTransform.FKraftEngine.ContinuousMode := kcmTimeOfImpactSubSteps |
| 1469 |
else |
| 1470 |
RootTransform.FKraftEngine.ContinuousMode := kcmNone; |
| 1471 |
end; |
| 1472 |
end; |
| 1473 |
|
| 1474 |
{ |
| 1475 |
procedure TPhysicsProperties.SetLayerNames(const AValue: TStrings); |
| 1476 |
begin |
| 1477 |
FLayerNames.Assign(AValue); |
| 1478 |
end; |
| 1479 |
} |
| 1480 |
|
| 1481 |
procedure TPhysicsProperties.SetLinearVelocityRK4Integration(const AValue: Boolean); |
| 1482 |
begin |
| 1483 |
if FLinearVelocityRK4Integration <> AValue then |
| 1484 |
begin |
| 1485 |
FLinearVelocityRK4Integration := AValue; |
| 1486 |
if Assigned(RootTransform.FKraftEngine) then |
| 1487 |
RootTransform.FKraftEngine.LinearVelocityRK4Integration := AValue; |
| 1488 |
end; |
| 1489 |
end; |
| 1490 |
|
| 1491 |
{ TCastleCollider ------------------------------------------------------------ } |
| 1492 |
|
| 1493 |
constructor TCastleCollider.Create(AOwner: TComponent); |
| 1494 |
begin |
| 1495 |
inherited; |
| 1496 |
// properties defaults |
| 1497 |
FDensity := DefaultDensity; |
| 1498 |
FMass := DefaultMass; |
| 1499 |
FRestitution := DefaultRestitution; |
| 1500 |
FFriction := DefaultFriction; |
| 1501 |
FSizeScale := 1.0; |
| 1502 |
FWorldScale := NoScale; |
| 1503 |
FTranslation := TVector3.Zero; |
| 1504 |
FRotation := TVector4.Zero; |
| 1505 |
|
| 1506 |
{ Will be updated in TCastleCollider.InitializeKraft to reflect FKraftShape.LocalTransform } |
| 1507 |
FUseLocalTransform := false; |
| 1508 |
FLocalTransform := TMatrix4.Identity; |
| 1509 |
FLocalInverseTransform := TMatrix4.Identity; |
| 1510 |
FAutoSize := true; |
| 1511 |
|
| 1512 |
ListenWorldChange := true; |
| 1513 |
|
| 1514 |
{$define read_implementation_constructor} |
| 1515 |
{$I auto_generated_persistent_vectors/tcastlecollider_persistent_vectors.inc} |
| 1516 |
{$undef read_implementation_constructor} |
| 1517 |
end; |
| 1518 |
|
| 1519 |
destructor TCastleCollider.Destroy; |
| 1520 |
begin |
| 1521 |
{$define read_implementation_destructor} |
| 1522 |
{$I auto_generated_persistent_vectors/tcastlecollider_persistent_vectors.inc} |
| 1523 |
{$undef read_implementation_destructor} |
| 1524 |
inherited; |
| 1525 |
end; |
| 1526 |
|
| 1527 |
procedure TCastleCollider.UpdateVisualization; |
| 1528 |
begin |
| 1529 |
if FVisualizationParent <> nil then |
| 1530 |
begin |
| 1531 |
{ We need to multiply Translation * TotalScale, |
| 1532 |
testcases: |
| 1533 |
- "Show Colliders" on examples/physics/physics_test_scale_colliders/ |
| 1534 |
- "Show Colliders" on TCastleBoxCollider with Size = (0.05 0.05 0.02) |
| 1535 |
and Translation = (0.00 0.02 0.00) } |
| 1536 |
FVisualizationParent.Translation := Translation * TotalScale; |
| 1537 |
FVisualizationParent.Rotation := Rotation; |
| 1538 |
end; |
| 1539 |
end; |
| 1540 |
|
| 1541 |
procedure TCastleCollider.InternalDesigningBegin; |
| 1542 |
begin |
| 1543 |
inherited; |
| 1544 |
if FVisualizationParent = nil then |
| 1545 |
begin |
| 1546 |
FVisualizationParent := TCastleTransform.Create(nil); |
| 1547 |
FVisualizationParent.InternalIgnoreParentScale := true; |
| 1548 |
ColliderVisualizationConfigBase(FVisualizationParent); |
| 1549 |
Parent.Add(FVisualizationParent); |
| 1550 |
// descendants will call UpdateVisualization |
| 1551 |
end; |
| 1552 |
end; |
| 1553 |
|
| 1554 |
procedure TCastleCollider.InternalDesigningEnd; |
| 1555 |
begin |
| 1556 |
FreeAndNil(FVisualizationParent); |
| 1557 |
inherited; |
| 1558 |
end; |
| 1559 |
|
| 1560 |
procedure TCastleCollider.ParentBeforeDetach; |
| 1561 |
begin |
| 1562 |
InternalDesigningEnd; |
| 1563 |
inherited; |
| 1564 |
end; |
| 1565 |
|
| 1566 |
procedure TCastleCollider.UpdateLocalTransform; |
| 1567 |
var |
| 1568 |
T: TTransformation; |
| 1569 |
RBody: TCastleRigidBody; |
| 1570 |
begin |
| 1571 |
{ Initialize FLocalTransform, FLocalInverseTransform and pass transform to FKraftShape } |
| 1572 |
T.Init; |
| 1573 |
|
| 1574 |
{ TCastleCollider.Translation below is multiplied by WorldScaleScalar |
| 1575 |
and not by TotalScale. Because: |
| 1576 |
- Conceptually, all distances are scaled by |
| 1577 |
WorldScaleScalar, including TCastleCollider.Translation. |
| 1578 |
E.g. TCastleCollider.Translation = (20,0,0) |
| 1579 |
under TCastleTransform with Scale = 10 |
| 1580 |
actually moves by 10. |
| 1581 |
- But TCastleCollider.SizeScale is more local, it doesn't affect distance |
| 1582 |
by TCastleCollider.Translation. |
| 1583 |
- The end result is that TCastleCollider.Translation / Rotation / SizeScale |
| 1584 |
should behave analogous to local TCastleTransform transformation, |
| 1585 |
and be affected by parent TCastleTransform transformations in the same way. |
| 1586 |
- Testcase: physics_test_scale_colliders |
| 1587 |
} |
| 1588 |
|
| 1589 |
T.Multiply(Rotation, NoScale, Translation * WorldScaleScalar); |
| 1590 |
FLocalTransform := T.Transform; |
| 1591 |
FLocalInverseTransform := T.InverseTransform; |
| 1592 |
if FKraftShape <> nil then |
| 1593 |
begin |
| 1594 |
Assert(Parent <> nil); |
| 1595 |
RBody := Parent.FindBehavior(TCastleRigidBody) as TCastleRigidBody; |
| 1596 |
Assert(RBody <> nil); |
| 1597 |
|
| 1598 |
FKraftShape.LocalTransform := MatrixToKraft(FLocalTransform); |
| 1599 |
RBody.FKraftBody.SynchronizeTransformIncludingShapes; |
| 1600 |
FKraftShape.StoreWorldTransform; |
| 1601 |
end; |
| 1602 |
|
| 1603 |
{ After setting the appropriate transformation, we can optimize the matrix |
| 1604 |
multiplication when rotation = 0, translation = 0,0,0 . |
| 1605 |
TotalScale (FWorldScale, FSizeScale) is not checked here because it must be |
| 1606 |
1,1,1 in Kraft and it's added later at the creation of collider shape. } |
| 1607 |
FUseLocalTransform := not ( |
| 1608 |
FTranslation.IsPerfectlyZero and |
| 1609 |
(FRotation.W = 0) |
| 1610 |
); |
| 1611 |
UpdateVisualization; |
| 1612 |
end; |
| 1613 |
|
| 1614 |
procedure TCastleCollider.InitializeKraft(const APhysics: TKraft; |
| 1615 |
const ACastleRigidBody: TCastleRigidBody); |
| 1616 |
begin |
| 1617 |
Assert(ACastleRigidBody.FKraftBody <> nil, |
| 1618 |
'Trying initialize kraft shape when rigid body not initialized!'); |
| 1619 |
|
| 1620 |
ACastleRigidBody.DeinitializeCollider; |
| 1621 |
{ If shape count is > 0 we need delete previous shape. } |
| 1622 |
{if ACastleRigidBody.FKraftBody.ShapeCount > 0 then |
| 1623 |
begin |
| 1624 |
Assert(ACastleRigidBody.FKraftBody.ShapeCount = 1, 'More than one shape in rigid body.'); |
| 1625 |
Assert(ACastleRigidBody.FKraftBody.ShapeFirst <> FKraftShape, 'Mixed kraft shapes'); |
| 1626 |
FreeAndNil(FKraftShape); |
| 1627 |
end;} |
| 1628 |
|
| 1629 |
FKraftShape := CreateKraftShape(APhysics, ACastleRigidBody.FKraftBody); |
| 1630 |
Assert(FKraftShape <> nil); |
| 1631 |
|
| 1632 |
// assign common collider properties to Kraft shape |
| 1633 |
FKraftShape.Density := Density; |
| 1634 |
FKraftShape.Restitution := Restitution; |
| 1635 |
FKraftShape.Friction := Friction; |
| 1636 |
if not ACastleRigidBody.ExistsInRoot then |
| 1637 |
FKraftShape.Flags := FKraftShape.Flags - [ksfCollision, ksfRayCastable]; |
| 1638 |
|
| 1639 |
UpdateLocalTransform; |
| 1640 |
end; |
| 1641 |
|
| 1642 |
function TCastleCollider.GetRigidBody: TCastleRigidBody; |
| 1643 |
begin |
| 1644 |
if Parent <> nil then |
| 1645 |
Result := Parent.FindBehavior(TCastleRigidBody) as TCastleRigidBody |
| 1646 |
else |
| 1647 |
Result := nil; |
| 1648 |
end; |
| 1649 |
|
| 1650 |
procedure TCastleCollider.SetDensity(const AValue: Single); |
| 1651 |
var |
| 1652 |
RigidBody: TCastleRigidBody; |
| 1653 |
begin |
| 1654 |
if FDensity <> AValue then |
| 1655 |
begin |
| 1656 |
FDensity := AValue; |
| 1657 |
|
| 1658 |
if FKraftShape <> nil then |
| 1659 |
begin |
| 1660 |
FKraftShape.Density := FDensity; |
| 1661 |
|
| 1662 |
// Similar as in SetMass, we need to call KraftForceUpdatingReadyBody |
| 1663 |
RigidBody := GetRigidBody; |
| 1664 |
if RigidBody <> nil then |
| 1665 |
RigidBody.KraftForceUpdatingReadyBody; |
| 1666 |
end; |
| 1667 |
end; |
| 1668 |
end; |
| 1669 |
|
| 1670 |
procedure TCastleCollider.SetMass(const AValue: Single); |
| 1671 |
var |
| 1672 |
RigidBody: TCastleRigidBody; |
| 1673 |
begin |
| 1674 |
if FMass <> AValue then |
| 1675 |
begin |
| 1676 |
FMass := AValue; |
| 1677 |
|
| 1678 |
RigidBody := GetRigidBody; |
| 1679 |
if (RigidBody <> nil) and (RigidBody.FKraftBody <> nil) then |
| 1680 |
begin |
| 1681 |
RigidBody.FKraftBody.ForcedMass := FMass; |
| 1682 |
|
| 1683 |
{ Without KraftForceUpdatingReadyBody (FKraftBody.Finish), |
| 1684 |
merely updating FKraftBody.ForcedMass doesn't have an effect, |
| 1685 |
Kraft still uses old mass. |
| 1686 |
|
| 1687 |
Testcase: |
| 1688 |
- in editor, set Mass of some bullet to 10. |
| 1689 |
- Play physics. |
| 1690 |
- change Mass to 10000. |
| 1691 |
- Play physics -- without FKraftBody.Finish, |
| 1692 |
it will behave as if Mass was still 10. |
| 1693 |
- Stopping and playing physics again will update it OK (because at this point, |
| 1694 |
stopping physics reloads the design, initializing everything). |
| 1695 |
So the buggy effect is that you need to "play physics twice" |
| 1696 |
to actually see the new Mass. |
| 1697 |
} |
| 1698 |
RigidBody.KraftForceUpdatingReadyBody; |
| 1699 |
end; |
| 1700 |
end; |
| 1701 |
end; |
| 1702 |
|
| 1703 |
procedure TCastleCollider.SetRestitution(const AValue: Single); |
| 1704 |
begin |
| 1705 |
if FRestitution <> AValue then |
| 1706 |
begin |
| 1707 |
FRestitution := AValue; |
| 1708 |
if FKraftShape <> nil then |
| 1709 |
FKraftShape.Restitution := FRestitution; |
| 1710 |
end; |
| 1711 |
end; |
| 1712 |
|
| 1713 |
procedure TCastleCollider.SetFriction(const AValue: Single); |
| 1714 |
begin |
| 1715 |
if FFriction <> AValue then |
| 1716 |
begin |
| 1717 |
FFriction := AValue; |
| 1718 |
if FKraftShape <> nil then |
| 1719 |
FKraftShape.Friction := FFriction; |
| 1720 |
end; |
| 1721 |
end; |
| 1722 |
|
| 1723 |
procedure TCastleCollider.SetTranslation(const AValue: TVector3); |
| 1724 |
begin |
| 1725 |
if not TVector3.PerfectlyEquals(AValue, FTranslation) then |
| 1726 |
begin |
| 1727 |
FTranslation := AValue; |
| 1728 |
DisableAutoSize; |
| 1729 |
UpdateLocalTransform; |
| 1730 |
end; |
| 1731 |
end; |
| 1732 |
|
| 1733 |
procedure TCastleCollider.SetRotation(const AValue: TVector4); |
| 1734 |
begin |
| 1735 |
if not TVector4.PerfectlyEquals(AValue, FRotation) then |
| 1736 |
begin |
| 1737 |
FRotation := AValue; |
| 1738 |
DisableAutoSize; |
| 1739 |
UpdateLocalTransform; |
| 1740 |
UpdateVisualization; |
| 1741 |
end; |
| 1742 |
end; |
| 1743 |
|
| 1744 |
procedure TCastleCollider.SetSizeScale(const AValue: Single); |
| 1745 |
begin |
| 1746 |
if FSizeScale <> AValue then |
| 1747 |
begin |
| 1748 |
FSizeScale := AValue; |
| 1749 |
// FSizeScale is used by collider at the shape creation |
| 1750 |
ShapeChangedNotifyRigidBody; |
| 1751 |
UpdateVisualization; |
| 1752 |
end; |
| 1753 |
end; |
| 1754 |
|
| 1755 |
procedure TCastleCollider.SetAutoSize(const AValue: Boolean); |
| 1756 |
begin |
| 1757 |
if FAutoSize <> AValue then |
| 1758 |
begin |
| 1759 |
FAutoSize := AValue; |
| 1760 |
InternalAutoSize; |
| 1761 |
end; |
| 1762 |
end; |
| 1763 |
|
| 1764 |
procedure TCastleCollider.ShapeChangedNotifyRigidBody; |
| 1765 |
var |
| 1766 |
CastleRBody: TCastleRigidBody; |
| 1767 |
begin |
| 1768 |
if Parent <> nil then |
| 1769 |
begin |
| 1770 |
CastleRBody := Parent.FindBehavior(TCastleRigidBody) as TCastleRigidBody; |
| 1771 |
if CastleRBody <> nil then |
| 1772 |
CastleRBody.ReinitializeCastleCollider; |
| 1773 |
end; |
| 1774 |
end; |
| 1775 |
|
| 1776 |
procedure TCastleCollider.WorldAfterAttach; |
| 1777 |
var |
| 1778 |
CastleRigidBody: TCastleRigidBody; |
| 1779 |
begin |
| 1780 |
{ Check there is a rigid body and we should try initialize collider. |
| 1781 |
This is the case when rigid body was added first to behaviors list } |
| 1782 |
CastleRigidBody := Parent.FindBehavior(TCastleRigidBody) as TCastleRigidBody; |
| 1783 |
if CastleRigidBody <> nil then |
| 1784 |
CastleRigidBody.CheckInitialization(Self); |
| 1785 |
|
| 1786 |
InternalAutoSize; |
| 1787 |
|
| 1788 |
UpdateWorldScale; |
| 1789 |
|
| 1790 |
inherited WorldAfterAttach; |
| 1791 |
end; |
| 1792 |
|
| 1793 |
procedure TCastleCollider.WorldBeforeDetach; |
| 1794 |
var |
| 1795 |
CastleRBody: TCastleRigidBody; |
| 1796 |
begin |
| 1797 |
CastleRBody := Parent.FindBehavior(TCastleRigidBody) as TCastleRigidBody; |
| 1798 |
if CastleRBody <> nil then |
| 1799 |
begin |
| 1800 |
// deinitialize collider |
| 1801 |
CastleRBody.DeinitializeCollider; |
| 1802 |
end; |
| 1803 |
|
| 1804 |
inherited WorldBeforeDetach; |
| 1805 |
end; |
| 1806 |
|
| 1807 |
function TCastleCollider.CanAttachToParent(const NewParent: TCastleTransform; |
| 1808 |
out ReasonWhyCannot: String): Boolean; |
| 1809 |
begin |
| 1810 |
Result := inherited; |
| 1811 |
if not Result then Exit; |
| 1812 |
|
| 1813 |
if NewParent.FindBehavior(TCastleCollider) <> nil then |
| 1814 |
begin |
| 1815 |
ReasonWhyCannot := 'Only one TCastleCollider behavior can be added to a given TCastleTransform'; |
| 1816 |
Result := false; |
| 1817 |
end; |
| 1818 |
end; |
| 1819 |
|
| 1820 |
procedure TCastleCollider.DisableAutoSize; |
| 1821 |
begin |
| 1822 |
if FCalculatingSize then |
| 1823 |
Exit; |
| 1824 |
|
| 1825 |
if IsLoading then |
| 1826 |
Exit; |
| 1827 |
|
| 1828 |
AutoSize := false; |
| 1829 |
end; |
| 1830 |
|
| 1831 |
procedure TCastleCollider.CalculateSizeCore; |
| 1832 |
begin |
| 1833 |
Translation := TVector3.Zero; |
| 1834 |
Rotation := TVector4.Zero; |
| 1835 |
end; |
| 1836 |
|
| 1837 |
procedure TCastleCollider.CalculateSize; |
| 1838 |
begin |
| 1839 |
FCalculatingSize := true; |
| 1840 |
try |
| 1841 |
CalculateSizeCore; |
| 1842 |
finally FCalculatingSize := false end; |
| 1843 |
end; |
| 1844 |
|
| 1845 |
function TCastleCollider.WorldScaleScalar: Single; |
| 1846 |
begin |
| 1847 |
if Mode2D then |
| 1848 |
begin |
| 1849 |
if (not WarningNonUniformScaleDone) and |
| 1850 |
(not SameValue(FWorldScale.X, FWorldScale.Y)) then |
| 1851 |
begin |
| 1852 |
WritelnWarning('Using non-uniform 2D scale %s for physics body (collider %s) is not fully supported', [ |
| 1853 |
FWorldScale.XY.ToString, |
| 1854 |
Name |
| 1855 |
]); |
| 1856 |
WarningNonUniformScaleDone := true; |
| 1857 |
end; |
| 1858 |
Result := Approximate2DScale(FWorldScale.XY) |
| 1859 |
end else |
| 1860 |
begin |
| 1861 |
if (not WarningNonUniformScaleDone) and |
| 1862 |
( (not SameValue(FWorldScale.X, FWorldScale.Y)) or |
| 1863 |
(not SameValue(FWorldScale.X, FWorldScale.Z)) |
| 1864 |
) then |
| 1865 |
begin |
| 1866 |
WritelnWarning('Using non-uniform scale %s for physics body (collider %s) is not fully supported', [ |
| 1867 |
FWorldScale.ToString, |
| 1868 |
Name |
| 1869 |
]); |
| 1870 |
WarningNonUniformScaleDone := true; |
| 1871 |
end; |
| 1872 |
Result := Approximate3DScale(FWorldScale); |
| 1873 |
end; |
| 1874 |
end; |
| 1875 |
|
| 1876 |
function TCastleCollider.TotalScale: Single; |
| 1877 |
begin |
| 1878 |
Result := WorldScaleScalar * FSizeScale; |
| 1879 |
end; |
| 1880 |
|
| 1881 |
procedure TCastleCollider.UpdateWorldScale; |
| 1882 |
var |
| 1883 |
NewScale: TVector3; |
| 1884 |
begin |
| 1885 |
if Parent.HasWorldTransform then |
| 1886 |
NewScale := ScaleFromMatrix(Parent.WorldTransform) |
| 1887 |
else |
| 1888 |
NewScale := Parent.Scale; |
| 1889 |
|
| 1890 |
{ Never use a negative scale for colliders } |
| 1891 |
NewScale := NewScale.Abs; |
| 1892 |
|
| 1893 |
if not TVector3.PerfectlyEquals(FWorldScale, NewScale) then |
| 1894 |
begin |
| 1895 |
FWorldScale := NewScale; |
| 1896 |
{ FWorldScale is used in CreateCraftShape so we need to notify |
| 1897 |
RigidBody to recreate it. } |
| 1898 |
ShapeChangedNotifyRigidBody; |
| 1899 |
end; |
| 1900 |
end; |
| 1901 |
|
| 1902 |
function TCastleCollider.StoredWithAutoSize: Boolean; |
| 1903 |
begin |
| 1904 |
Result := not AutoSize; |
| 1905 |
end; |
| 1906 |
|
| 1907 |
function TCastleCollider.PropertySections( |
| 1908 |
const PropertyName: String): TPropertySections; |
| 1909 |
begin |
| 1910 |
if ArrayContainsString(PropertyName, [ |
| 1911 |
'Density', 'Friction', 'Mass', 'Restitution', 'SizeScale', 'LayerCollisions', |
| 1912 |
'LayerNames', 'RotationPersistent', 'TranslationPersistent' |
| 1913 |
]) then |
| 1914 |
Result := [psBasic] |
| 1915 |
else |
| 1916 |
Result := inherited PropertySections(PropertyName); |
| 1917 |
end; |
| 1918 |
|
| 1919 |
procedure TCastleCollider.InternalAutoSize; |
| 1920 |
begin |
| 1921 |
if AutoSize then |
| 1922 |
CalculateSize; |
| 1923 |
end; |
| 1924 |
|
| 1925 |
procedure TCastleCollider.InternalTransformChanged(const TransformChanged: TCastleTransform); |
| 1926 |
begin |
| 1927 |
Assert(TransformChanged <> nil); |
| 1928 |
if TransformChanged = Parent then |
| 1929 |
InternalAutoSize; |
| 1930 |
end; |
| 1931 |
|
| 1932 |
procedure TCastleCollider.CustomSerialization(const SerializationProcess: TSerializationProcess); |
| 1933 |
|
| 1934 |
procedure UpgradeOldScale(const OldScaleVectorName: String); |
| 1935 |
var |
| 1936 |
OldScale: TVector3; |
| 1937 |
TempMode2D: Boolean; |
| 1938 |
begin |
| 1939 |
OldScale := NoScale; |
| 1940 |
SerializationProcess.ReadWriteVector(OldScaleVectorName, OldScale, NoScale, false); |
| 1941 |
if not TVector3.PerfectlyEquals(OldScale, NoScale) then |
| 1942 |
begin |
| 1943 |
// read Mode2D, to work independently of whether it was initialized by normal deserialization already |
| 1944 |
SerializationProcess.ReadWriteBoolean('Mode2D', TempMode2D, false); |
| 1945 |
WritelnWarning('Design refers to TCastleCollider.%s which is renamed now to SizeScale (and of Single type). Save the design to upgrade it.', [ |
| 1946 |
OldScaleVectorName |
| 1947 |
]); |
| 1948 |
if TempMode2D then |
| 1949 |
SizeScale := Approximate2DScale(OldScale.XY) |
| 1950 |
else |
| 1951 |
SizeScale := Approximate3DScale(OldScale); |
| 1952 |
end; |
| 1953 |
end; |
| 1954 |
|
| 1955 |
begin |
| 1956 |
inherited; |
| 1957 |
{ Upgrade old ideas (they only existed on physics branch, so this upgrade code |
| 1958 |
can be really removed from master branch at some point. } |
| 1959 |
UpgradeOldScale('ScalePersistent'); |
| 1960 |
UpgradeOldScale('SizeScalePersistent'); |
| 1961 |
end; |
| 1962 |
|
| 1963 |
procedure TCastleCollider.SetMode2D(const AValue: Boolean); |
| 1964 |
begin |
| 1965 |
if FMode2D <> AValue then |
| 1966 |
begin |
| 1967 |
FMode2D := AValue; |
| 1968 |
InternalAutoSize; |
| 1969 |
// even when AutoSize=false, changing Mode2D changes how WorldScale is interpreted |
| 1970 |
ShapeChangedNotifyRigidBody; |
| 1971 |
end; |
| 1972 |
end; |
| 1973 |
|
| 1974 |
procedure TCastleCollider.DeinitializePhysicsEngineObjects; |
| 1975 |
begin |
| 1976 |
FreeAndNil(FKraftShape); |
| 1977 |
end; |
| 1978 |
|
| 1979 |
class procedure TCastleCollider.CreateComponent2D(Sender: TObject); |
| 1980 |
begin |
| 1981 |
(Sender as TCastleCollider).Mode2D := true; |
| 1982 |
end; |
| 1983 |
|
| 1984 |
{$define read_implementation_methods} |
| 1985 |
{$I auto_generated_persistent_vectors/tcastlecollider_persistent_vectors.inc} |
| 1986 |
{$undef read_implementation_methods} |
| 1987 |
|
| 1988 |
{ TCastlePlaneCollider ------------------------------------------------------- } |
| 1989 |
|
| 1990 |
constructor TCastlePlaneCollider.Create(AOwner: TComponent); |
| 1991 |
begin |
| 1992 |
inherited Create(AOwner); |
| 1993 |
|
| 1994 |
// Note: assign using Fxxx, not property setter, to avoid changing AutoSize to @false |
| 1995 |
FNormal := TVector3.One[1]; |
| 1996 |
|
| 1997 |
{$define read_implementation_constructor} |
| 1998 |
{$I auto_generated_persistent_vectors/tcastleplanecollider_persistent_vectors.inc} |
| 1999 |
{$undef read_implementation_constructor} |
| 2000 |
end; |
| 2001 |
|
| 2002 |
destructor TCastlePlaneCollider.Destroy; |
| 2003 |
begin |
| 2004 |
{$define read_implementation_destructor} |
| 2005 |
{$I auto_generated_persistent_vectors/tcastleplanecollider_persistent_vectors.inc} |
| 2006 |
{$undef read_implementation_destructor} |
| 2007 |
inherited; |
| 2008 |
end; |
| 2009 |
|
| 2010 |
procedure TCastlePlaneCollider.SetNormal(const AValue: TVector3); |
| 2011 |
begin |
| 2012 |
if not FNormal.Equals(FNormal, AValue) then |
| 2013 |
begin |
| 2014 |
FNormal := AValue; |
| 2015 |
DisableAutoSize; |
| 2016 |
ShapeChangedNotifyRigidBody; |
| 2017 |
UpdateVisualization; |
| 2018 |
end; |
| 2019 |
end; |
| 2020 |
|
| 2021 |
procedure TCastlePlaneCollider.SetDistance(const AValue: Single); |
| 2022 |
begin |
| 2023 |
if FDistance <> AValue then |
| 2024 |
begin |
| 2025 |
FDistance := AValue; |
| 2026 |
DisableAutoSize; |
| 2027 |
ShapeChangedNotifyRigidBody; |
| 2028 |
UpdateVisualization; |
| 2029 |
end; |
| 2030 |
end; |
| 2031 |
|
| 2032 |
function TCastlePlaneCollider.CalculateScaledDistance: Single; |
| 2033 |
begin |
| 2034 |
Result := Distance * TotalScale; |
| 2035 |
end; |
| 2036 |
|
| 2037 |
procedure TCastlePlaneCollider.UpdateVisualization; |
| 2038 |
begin |
| 2039 |
inherited; |
| 2040 |
if FVisualization <> nil then |
| 2041 |
begin |
| 2042 |
TCastlePlane(FVisualization).Size := Vector2(2, 2); |
| 2043 |
FVisualization.Translation := CastleVectors.Vector3(0, CalculateScaledDistance, 0); |
| 2044 |
FVisualization.Rotation := Vector4(CastleVectors.Vector3(0, 0, -1), // todo check why -1 |
| 2045 |
AngleRadBetweenVectors(CastleVectors.Vector3(0, 1, 0), FNormal.Normalize)); |
| 2046 |
end; |
| 2047 |
end; |
| 2048 |
|
| 2049 |
function TCastlePlaneCollider.CreateKraftShape(const APhysics: TKraft; |
| 2050 |
const ARigidBody: TKraftRigidBody): TKraftShape; |
| 2051 |
begin |
| 2052 |
// TCastlePlaneCollider is available only for static rigid bodies |
| 2053 |
// TODO: We force krbtStatic now. Can we allow krbtKinematic too? |
| 2054 |
ARigidBody.RigidBodyType := krbtStatic; |
| 2055 |
|
| 2056 |
Result := TKraftShapePlane.Create(APhysics, ARigidBody, |
| 2057 |
Plane(Vector3Norm(VectorToKraft(FNormal)), |
| 2058 |
CalculateScaledDistance)); |
| 2059 |
end; |
| 2060 |
|
| 2061 |
procedure TCastlePlaneCollider.CalculateSizeCore; |
| 2062 |
var |
| 2063 |
LocalBoundingBox: TBox3D; |
| 2064 |
NormalCoord: T3DCoord; |
| 2065 |
begin |
| 2066 |
inherited; // resets Translation, Rotation |
| 2067 |
|
| 2068 |
{ Defaults, in case we don't have any better value } |
| 2069 |
Normal := TVector3.One[1]; |
| 2070 |
Distance := 0; |
| 2071 |
|
| 2072 |
if Parent = nil then |
| 2073 |
Exit; |
| 2074 |
LocalBoundingBox := Parent.LocalBoundingBox; |
| 2075 |
if LocalBoundingBox.IsEmptyOrZero then |
| 2076 |
Exit; |
| 2077 |
|
| 2078 |
NormalCoord := MinAbsVectorCoord(LocalBoundingBox.Size); |
| 2079 |
Normal := TVector3.One[NormalCoord]; |
| 2080 |
Distance := |
| 2081 |
LocalBoundingBox.Max.AsArray[NormalCoord] - |
| 2082 |
LocalBoundingBox.Min.AsArray[NormalCoord]; |
| 2083 |
end; |
| 2084 |
|
| 2085 |
procedure TCastlePlaneCollider.InternalDesigningBegin; |
| 2086 |
begin |
| 2087 |
inherited; |
| 2088 |
if FVisualization = nil then |
| 2089 |
begin |
| 2090 |
FVisualization := TCastlePlane.Create(nil); |
| 2091 |
ColliderVisualizationConfig(FVisualization as TCastleAbstractPrimitive); |
| 2092 |
UpdateVisualization; |
| 2093 |
FVisualizationParent.Add(FVisualization); |
| 2094 |
end; |
| 2095 |
end; |
| 2096 |
|
| 2097 |
procedure TCastlePlaneCollider.InternalDesigningEnd; |
| 2098 |
begin |
| 2099 |
FreeAndNil(FVisualization); |
| 2100 |
inherited; |
| 2101 |
end; |
| 2102 |
|
| 2103 |
function TCastlePlaneCollider.PropertySections( |
| 2104 |
const PropertyName: String): TPropertySections; |
| 2105 |
begin |
| 2106 |
if ArrayContainsString(PropertyName, [ |
| 2107 |
'AutoSize', 'NormalPersistent', 'Distance' |
| 2108 |
]) then |
| 2109 |
Result := [psBasic] |
| 2110 |
else |
| 2111 |
Result := inherited PropertySections(PropertyName); |
| 2112 |
end; |
| 2113 |
|
| 2114 |
{$define read_implementation_methods} |
| 2115 |
{$I auto_generated_persistent_vectors/tcastleplanecollider_persistent_vectors.inc} |
| 2116 |
{$undef read_implementation_methods} |
| 2117 |
|
| 2118 |
{ TCastleBoxCollider --------------------------------------------------------- } |
| 2119 |
|
| 2120 |
constructor TCastleBoxCollider.Create(AOwner: TComponent); |
| 2121 |
begin |
| 2122 |
inherited Create(AOwner); |
| 2123 |
|
| 2124 |
// Note: assign using Fxxx, not property setter, to avoid changing AutoSize to @false |
| 2125 |
FSize := CastleVectors.Vector3(2, 2, 2); |
| 2126 |
|
| 2127 |
{$define read_implementation_constructor} |
| 2128 |
{$I auto_generated_persistent_vectors/tcastleboxcollider_persistent_vectors.inc} |
| 2129 |
{$undef read_implementation_constructor} |
| 2130 |
end; |
| 2131 |
|
| 2132 |
destructor TCastleBoxCollider.Destroy; |
| 2133 |
begin |
| 2134 |
{$define read_implementation_destructor} |
| 2135 |
{$I auto_generated_persistent_vectors/tcastleboxcollider_persistent_vectors.inc} |
| 2136 |
{$undef read_implementation_destructor} |
| 2137 |
inherited; |
| 2138 |
end; |
| 2139 |
|
| 2140 |
procedure TCastleBoxCollider.SetSize(const AValue: TVector3); |
| 2141 |
begin |
| 2142 |
if not TVector3.PerfectlyEquals(FSize, AValue) then |
| 2143 |
begin |
| 2144 |
FSize := AValue; |
| 2145 |
DisableAutoSize; |
| 2146 |
ShapeChangedNotifyRigidBody; |
| 2147 |
UpdateVisualization; |
| 2148 |
end; |
| 2149 |
end; |
| 2150 |
|
| 2151 |
function TCastleBoxCollider.CalculateScaledSize: TVector3; |
| 2152 |
begin |
| 2153 |
Result := FSize * TotalScale; |
| 2154 |
end; |
| 2155 |
|
| 2156 |
function TCastleBoxCollider.CreateKraftShape(const APhysics: TKraft; |
| 2157 |
const ARigidBody: TKraftRigidBody): TKraftShape; |
| 2158 |
var |
| 2159 |
ScaledSize: TVector3; |
| 2160 |
begin |
| 2161 |
ScaledSize := CalculateScaledSize; |
| 2162 |
|
| 2163 |
{ Check it ourselves, otherwise Kraft will crash on such invalid box with segfault. |
| 2164 |
First Kraft raises nice |
| 2165 |
EKraftDegeneratedConvexHull.Create('Degenerated convex hull'); |
| 2166 |
but then makes SIGSEGV at |
| 2167 |
fPhysics.fStaticAABBTree.DestroyProxy(fStaticAABBTreeProxy) |
| 2168 |
in TKraftShape.Destroy. } |
| 2169 |
|
| 2170 |
if (ScaledSize[0] <= 0) or |
| 2171 |
(ScaledSize[1] <= 0) or |
| 2172 |
(ScaledSize[2] <= 0) then |
| 2173 |
raise EPhysicsError.Create('You must assign positive Size to TCastleBoxCollider'); |
| 2174 |
Result := TKraftShapeBox.Create(APhysics, ARigidBody, VectorToKraft(ScaledSize / 2)); |
| 2175 |
end; |
| 2176 |
|
| 2177 |
procedure TCastleBoxCollider.CalculateSizeCore; |
| 2178 |
var |
| 2179 |
LocalBoundingBox: TBox3D; |
| 2180 |
TempSize: TVector3; |
| 2181 |
MinThickness: TVector3; |
| 2182 |
begin |
| 2183 |
inherited; // resets Translation, Rotation |
| 2184 |
|
| 2185 |
if Mode2D then |
| 2186 |
MinThickness := CastleVectors.Vector3(AutoSizeMinThickness2D, AutoSizeMinThickness2D, AutoSizeMinThickness2DDepth) |
| 2187 |
else |
| 2188 |
MinThickness := CastleVectors.Vector3(AutoSizeMinThickness, AutoSizeMinThickness, AutoSizeMinThickness); |
| 2189 |
|
| 2190 |
if (Parent = nil) or (Parent.BoundingBox.IsEmptyOrZero) then |
| 2191 |
begin |
| 2192 |
Size := MinThickness; |
| 2193 |
Exit; |
| 2194 |
end; |
| 2195 |
|
| 2196 |
LocalBoundingBox := Parent.LocalBoundingBox; |
| 2197 |
TempSize := LocalBoundingBox.Size; |
| 2198 |
|
| 2199 |
if TempSize.X < MinThickness.X then |
| 2200 |
TempSize.X := MinThickness.X; |
| 2201 |
|
| 2202 |
if TempSize.Y < MinThickness.Y then |
| 2203 |
TempSize.Y := MinThickness.Y; |
| 2204 |
|
| 2205 |
if TempSize.Z < MinThickness.Z then |
| 2206 |
TempSize.Z := MinThickness.Z; |
| 2207 |
|
| 2208 |
Size := TempSize; |
| 2209 |
Translation := LocalBoundingBox.Center; |
| 2210 |
end; |
| 2211 |
|
| 2212 |
procedure TCastleBoxCollider.UpdateVisualization; |
| 2213 |
begin |
| 2214 |
inherited; |
| 2215 |
if FVisualization <> nil then |
| 2216 |
begin |
| 2217 |
TCastleBox(FVisualization).Size := CalculateScaledSize; |
| 2218 |
end; |
| 2219 |
end; |
| 2220 |
|
| 2221 |
procedure TCastleBoxCollider.InternalDesigningBegin; |
| 2222 |
begin |
| 2223 |
inherited; |
| 2224 |
if FVisualization = nil then |
| 2225 |
begin |
| 2226 |
FVisualization := TCastleBox.Create(nil); |
| 2227 |
ColliderVisualizationConfig(FVisualization as TCastleAbstractPrimitive); |
| 2228 |
UpdateVisualization; |
| 2229 |
FVisualizationParent.Add(FVisualization); |
| 2230 |
end; |
| 2231 |
end; |
| 2232 |
|
| 2233 |
procedure TCastleBoxCollider.InternalDesigningEnd; |
| 2234 |
begin |
| 2235 |
FreeAndNil(FVisualization); |
| 2236 |
inherited; |
| 2237 |
end; |
| 2238 |
|
| 2239 |
function TCastleBoxCollider.PropertySections(const PropertyName: String): TPropertySections; |
| 2240 |
begin |
| 2241 |
if ArrayContainsString(PropertyName, [ |
| 2242 |
'AutoSize', 'Mode2D', 'SizePersistent' |
| 2243 |
]) then |
| 2244 |
Result := [psBasic] |
| 2245 |
else |
| 2246 |
Result := inherited PropertySections(PropertyName); |
| 2247 |
end; |
| 2248 |
|
| 2249 |
{$define read_implementation_methods} |
| 2250 |
{$I auto_generated_persistent_vectors/tcastleboxcollider_persistent_vectors.inc} |
| 2251 |
{$undef read_implementation_methods} |
| 2252 |
|
| 2253 |
{ TCastleSphereCollider ------------------------------------------------------ } |
| 2254 |
|
| 2255 |
constructor TCastleSphereCollider.Create(AOwner: TComponent); |
| 2256 |
begin |
| 2257 |
inherited; |
| 2258 |
|
| 2259 |
// Note: assign using Fxxx, not property setter, to avoid changing AutoSize to @false |
| 2260 |
FRadius := 1; |
| 2261 |
end; |
| 2262 |
|
| 2263 |
procedure TCastleSphereCollider.SetRadius(const AValue: Single); |
| 2264 |
var |
| 2265 |
BigChange: Boolean; |
| 2266 |
begin |
| 2267 |
if FRadius <> AValue then |
| 2268 |
begin |
| 2269 |
BigChange := not SameValue(FRadius, AValue); |
| 2270 |
FRadius := AValue; |
| 2271 |
DisableAutoSize; |
| 2272 |
if BigChange then // do not rebuild collider without real need, as it is costly |
| 2273 |
begin |
| 2274 |
ShapeChangedNotifyRigidBody; |
| 2275 |
UpdateVisualization; |
| 2276 |
end; |
| 2277 |
end; |
| 2278 |
end; |
| 2279 |
|
| 2280 |
function TCastleSphereCollider.CreateKraftShape(const APhysics: TKraft; |
| 2281 |
const ARigidBody: TKraftRigidBody): TKraftShape; |
| 2282 |
begin |
| 2283 |
Result := TKraftShapeSphere.Create(APhysics, ARigidBody, CalculateScaledRadius); |
| 2284 |
end; |
| 2285 |
|
| 2286 |
procedure TCastleSphereCollider.UpdateVisualization; |
| 2287 |
begin |
| 2288 |
inherited; |
| 2289 |
if FVisualization <> nil then |
| 2290 |
begin |
| 2291 |
TCastleSphere(FVisualization).Radius := CalculateScaledRadius; |
| 2292 |
end; |
| 2293 |
end; |
| 2294 |
|
| 2295 |
procedure TCastleSphereCollider.CalculateSizeCore; |
| 2296 |
var |
| 2297 |
LocalBoundingBox: TBox3D; |
| 2298 |
MinThickness: Single; |
| 2299 |
begin |
| 2300 |
inherited; // resets Translation, Rotation |
| 2301 |
|
| 2302 |
if Mode2D then |
| 2303 |
MinThickness := AutoSizeMinThickness2D |
| 2304 |
else |
| 2305 |
MinThickness := AutoSizeMinThickness; |
| 2306 |
|
| 2307 |
if (Parent = nil) or (Parent.BoundingBox.IsEmptyOrZero) then |
| 2308 |
begin |
| 2309 |
Radius := MinThickness; |
| 2310 |
Exit; |
| 2311 |
end; |
| 2312 |
|
| 2313 |
LocalBoundingBox := Parent.LocalBoundingBox; |
| 2314 |
if Mode2D then |
| 2315 |
Radius := LocalBoundingBox.AverageSize2D(false, 2, 2) / 2 |
| 2316 |
else |
| 2317 |
Radius := LocalBoundingBox.AverageSize(false, 2) / 2; |
| 2318 |
|
| 2319 |
{ Check minimal size } |
| 2320 |
Radius := Max(Radius, MinThickness); |
| 2321 |
Translation := LocalBoundingBox.Center; |
| 2322 |
end; |
| 2323 |
|
| 2324 |
function TCastleSphereCollider.PropertySections(const PropertyName: String): TPropertySections; |
| 2325 |
begin |
| 2326 |
if ArrayContainsString(PropertyName, [ |
| 2327 |
'AutoSize', 'Mode2D', 'Radius' |
| 2328 |
]) then |
| 2329 |
Result := [psBasic] |
| 2330 |
else |
| 2331 |
Result := inherited PropertySections(PropertyName); |
| 2332 |
end; |
| 2333 |
|
| 2334 |
procedure TCastleSphereCollider.InternalDesigningBegin; |
| 2335 |
begin |
| 2336 |
inherited; |
| 2337 |
if FVisualization = nil then |
| 2338 |
begin |
| 2339 |
FVisualization := TCastleSphere.Create(nil); |
| 2340 |
ColliderVisualizationConfig(FVisualization as TCastleAbstractPrimitive); |
| 2341 |
UpdateVisualization; |
| 2342 |
FVisualizationParent.Add(FVisualization); |
| 2343 |
end; |
| 2344 |
end; |
| 2345 |
|
| 2346 |
procedure TCastleSphereCollider.InternalDesigningEnd; |
| 2347 |
begin |
| 2348 |
FreeAndNil(FVisualization); |
| 2349 |
inherited; |
| 2350 |
end; |
| 2351 |
|
| 2352 |
function TCastleSphereCollider.CalculateScaledRadius: Single; |
| 2353 |
begin |
| 2354 |
Result := FRadius * TotalScale; |
| 2355 |
end; |
| 2356 |
|
| 2357 |
{ TCastleCapsuleCollider ----------------------------------------------------- } |
| 2358 |
|
| 2359 |
constructor TCastleCapsuleCollider.Create(AOwner: TComponent); |
| 2360 |
begin |
| 2361 |
inherited; |
| 2362 |
|
| 2363 |
// Note: assign using Fxxx, not property setter, to avoid changing AutoSize to @false |
| 2364 |
FRadius := 1; |
| 2365 |
FHeight := 2; |
| 2366 |
end; |
| 2367 |
|
| 2368 |
procedure TCastleCapsuleCollider.SetRadius(const AValue: Single); |
| 2369 |
var |
| 2370 |
BigChange: Boolean; |
| 2371 |
begin |
| 2372 |
if FRadius <> AValue then |
| 2373 |
begin |
| 2374 |
BigChange := not SameValue(FRadius, AValue); |
| 2375 |
FRadius := AValue; |
| 2376 |
DisableAutoSize; |
| 2377 |
if BigChange then // do not rebuild collider without real need, as it is costly |
| 2378 |
begin |
| 2379 |
ShapeChangedNotifyRigidBody; |
| 2380 |
UpdateVisualization; |
| 2381 |
end; |
| 2382 |
end; |
| 2383 |
end; |
| 2384 |
|
| 2385 |
procedure TCastleCapsuleCollider.SetHeight(const AValue: Single); |
| 2386 |
var |
| 2387 |
BigChange: Boolean; |
| 2388 |
begin |
| 2389 |
if FHeight <> AValue then |
| 2390 |
begin |
| 2391 |
BigChange := not SameValue(FHeight, AValue); |
| 2392 |
FHeight := AValue; |
| 2393 |
DisableAutoSize; |
| 2394 |
if BigChange then // do not rebuild collider without real need, as it is costly |
| 2395 |
begin |
| 2396 |
ShapeChangedNotifyRigidBody; |
| 2397 |
UpdateVisualization; |
| 2398 |
end; |
| 2399 |
end; |
| 2400 |
end; |
| 2401 |
|
| 2402 |
function TCastleCapsuleCollider.CreateKraftShape(const APhysics: TKraft; |
| 2403 |
const ARigidBody: TKraftRigidBody): TKraftShape; |
| 2404 |
begin |
| 2405 |
Result := TKraftShapeCapsule.Create(APhysics, ARigidBody, CalculateScaledRadius, |
| 2406 |
CalculateScaledHeight); |
| 2407 |
end; |
| 2408 |
|
| 2409 |
procedure TCastleCapsuleCollider.UpdateVisualization; |
| 2410 |
var |
| 2411 |
VRadius: Single; |
| 2412 |
VHeight: Single; |
| 2413 |
begin |
| 2414 |
inherited; |
| 2415 |
if FVisualization <> nil then |
| 2416 |
begin |
| 2417 |
VRadius := CalculateScaledRadius; |
| 2418 |
VHeight := CalculateScaledHeight; |
| 2419 |
TCastleSphere(FVisualizationTop).Radius := VRadius; |
| 2420 |
TCastleSphere(FVisualizationTop).Translation := CastleVectors.Vector3(0, VHeight / 2, 0); |
| 2421 |
TCastleSphere(FVisualizationBottom).Radius := VRadius; |
| 2422 |
TCastleSphere(FVisualizationBottom).Translation := CastleVectors.Vector3(0, - VHeight / 2, 0); |
| 2423 |
TCastleCylinder(FVisualizationCylinder).Height := VHeight; |
| 2424 |
TCastleCylinder(FVisualizationCylinder).Radius := VRadius; |
| 2425 |
end; |
| 2426 |
end; |
| 2427 |
|
| 2428 |
procedure TCastleCapsuleCollider.InternalDesigningBegin; |
| 2429 |
begin |
| 2430 |
inherited; |
| 2431 |
|
| 2432 |
if FVisualization = nil then |
| 2433 |
begin |
| 2434 |
FVisualization := TCastleTransform.Create(nil); |
| 2435 |
FVisualization.SetTransient; |
| 2436 |
|
| 2437 |
FVisualizationCylinder := TCastleCylinder.Create(FVisualization); |
| 2438 |
ColliderVisualizationConfig(FVisualizationCylinder as TCastleAbstractPrimitive); |
| 2439 |
FVisualization.Add(FVisualizationCylinder); |
| 2440 |
|
| 2441 |
FVisualizationTop := TCastleSphere.Create(FVisualization); |
| 2442 |
ColliderVisualizationConfig(FVisualizationTop as TCastleAbstractPrimitive); |
| 2443 |
FVisualization.Add(FVisualizationTop); |
| 2444 |
|
| 2445 |
FVisualizationBottom := TCastleSphere.Create(FVisualization); |
| 2446 |
ColliderVisualizationConfig(FVisualizationBottom as TCastleAbstractPrimitive); |
| 2447 |
FVisualization.Add(FVisualizationBottom); |
| 2448 |
|
| 2449 |
UpdateVisualization; |
| 2450 |
FVisualizationParent.Add(FVisualization); |
| 2451 |
end; |
| 2452 |
end; |
| 2453 |
|
| 2454 |
procedure TCastleCapsuleCollider.InternalDesigningEnd; |
| 2455 |
begin |
| 2456 |
FreeAndNil(FVisualization); |
| 2457 |
inherited; |
| 2458 |
end; |
| 2459 |
|
| 2460 |
function TCastleCapsuleCollider.CalculateScaledHeight: Single; |
| 2461 |
begin |
| 2462 |
Result := FHeight * TotalScale; |
| 2463 |
end; |
| 2464 |
|
| 2465 |
function TCastleCapsuleCollider.CalculateScaledRadius: Single; |
| 2466 |
begin |
| 2467 |
Result := FRadius * TotalScale; |
| 2468 |
end; |
| 2469 |
|
| 2470 |
procedure TCastleCapsuleCollider.CalculateSizeCore; |
| 2471 |
var |
| 2472 |
LocalBoundingBox: TBox3D; |
| 2473 |
MinThickness: Single; |
| 2474 |
begin |
| 2475 |
inherited; // resets Translation, Rotation |
| 2476 |
|
| 2477 |
if Mode2D then |
| 2478 |
MinThickness := AutoSizeMinThickness2D |
| 2479 |
else |
| 2480 |
MinThickness := AutoSizeMinThickness; |
| 2481 |
|
| 2482 |
if (Parent = nil) or (Parent.BoundingBox.IsEmptyOrZero) then |
| 2483 |
begin |
| 2484 |
Radius := MinThickness; |
| 2485 |
Height := MinThickness; |
| 2486 |
Exit; |
| 2487 |
end; |
| 2488 |
|
| 2489 |
LocalBoundingBox := Parent.LocalBoundingBox; |
| 2490 |
|
| 2491 |
if Mode2D then |
| 2492 |
Radius := LocalBoundingBox.SizeX * 0.50 |
| 2493 |
else |
| 2494 |
Radius := ((LocalBoundingBox.SizeX * 0.50) + (LocalBoundingBox.SizeZ * 0.50)) / 2; |
| 2495 |
|
| 2496 |
{ If radius * 2 is bigger than height make it smaller. } |
| 2497 |
if Radius * 2 > LocalBoundingBox.SizeY then |
| 2498 |
Radius := LocalBoundingBox.SizeY / 2 - 0.001; |
| 2499 |
{ Radius must be at least MinThickness } |
| 2500 |
Radius := Max(Radius, MinThickness); |
| 2501 |
|
| 2502 |
Height := Max(LocalBoundingBox.SizeY - Radius * 2, 0.001); |
| 2503 |
|
| 2504 |
Translation := LocalBoundingBox.Center; |
| 2505 |
end; |
| 2506 |
|
| 2507 |
function TCastleCapsuleCollider.PropertySections( |
| 2508 |
const PropertyName: String): TPropertySections; |
| 2509 |
begin |
| 2510 |
if ArrayContainsString(PropertyName, [ |
| 2511 |
'AutoSize', 'Mode2D', 'Height', 'Radius' |
| 2512 |
]) then |
| 2513 |
Result := [psBasic] |
| 2514 |
else |
| 2515 |
Result := inherited PropertySections(PropertyName); |
| 2516 |
end; |
| 2517 |
|
| 2518 |
{ TCastleMeshCollider -------------------------------------------------------- } |
| 2519 |
|
| 2520 |
procedure TCastleMeshCollider.AddTriangle(Shape: TObject; |
| 2521 |
const Position: TTriangle3; |
| 2522 |
const Normal: TTriangle3; const TexCoord: TTriangle4; |
| 2523 |
const Face: TFaceIndex); |
| 2524 |
begin |
| 2525 |
{ TODO: it's probably not optimal to call AddTriangle |
| 2526 |
for each triangle, we should instead call Load with a list. } |
| 2527 |
|
| 2528 |
FKraftMesh.AddTriangle( |
| 2529 |
FKraftMesh.AddVertex(VectorToKraft(Position.Data[0])), |
| 2530 |
FKraftMesh.AddVertex(VectorToKraft(Position.Data[1])), |
| 2531 |
FKraftMesh.AddVertex(VectorToKraft(Position.Data[2])), |
| 2532 |
FKraftMesh.AddNormal(VectorToKraft(Normal.Data[0])), |
| 2533 |
FKraftMesh.AddNormal(VectorToKraft(Normal.Data[1])), |
| 2534 |
FKraftMesh.AddNormal(VectorToKraft(Normal.Data[2])) |
| 2535 |
); |
| 2536 |
|
| 2537 |
if DoubleSided then |
| 2538 |
begin |
| 2539 |
{ We also add triangles for the other side. |
| 2540 |
Kraft RayCast does not check inverted triangles. } |
| 2541 |
FKraftMesh.AddTriangle( |
| 2542 |
FKraftMesh.AddVertex(VectorToKraft(Position.Data[2])), |
| 2543 |
FKraftMesh.AddVertex(VectorToKraft(Position.Data[1])), |
| 2544 |
FKraftMesh.AddVertex(VectorToKraft(Position.Data[0])), |
| 2545 |
FKraftMesh.AddNormal(VectorToKraft(-Normal.Data[2])), |
| 2546 |
FKraftMesh.AddNormal(VectorToKraft(-Normal.Data[1])), |
| 2547 |
FKraftMesh.AddNormal(VectorToKraft(-Normal.Data[0])) |
| 2548 |
); |
| 2549 |
end; |
| 2550 |
end; |
| 2551 |
|
| 2552 |
function TCastleMeshCollider.CreateKraftShape(const APhysics: TKraft; |
| 2553 |
const ARigidBody: TKraftRigidBody): TKraftShape; |
| 2554 |
begin |
| 2555 |
{ TODO: We force krbtStatic now. Can we allow krbtKinematic too? } |
| 2556 |
ARigidBody.RigidBodyType := krbtStatic; |
| 2557 |
|
| 2558 |
FKraftMesh := TKraftMesh.Create(APhysics); |
| 2559 |
|
| 2560 |
if FMesh = nil then |
| 2561 |
begin |
| 2562 |
{ Do not warn about it now, as it would be too eager during loading. |
| 2563 |
Mesh may remain nil, and it may even remain nil at Loaded (when IsLoading stops |
| 2564 |
being true) if it refers to some component defined later in design. |
| 2565 |
Testcase: tests/data/designs/test_mesh_collider_ref.castle-user-interface . |
| 2566 |
|
| 2567 |
To really make a warning about it, we should have some method like |
| 2568 |
CompleteDesignLoaded. |
| 2569 |
But maybe we should just tolerate it, as valid state? |
| 2570 |
|
| 2571 |
WritelnWarning('TCastleMeshCollider "%s": Mesh not set, so it will not collide.', [ |
| 2572 |
Name |
| 2573 |
]); |
| 2574 |
} |
| 2575 |
end else |
| 2576 |
if not FMesh.HasColliderMesh then |
| 2577 |
begin |
| 2578 |
WritelnWarning('TCastleMeshCollider "%s": Mesh "%s:%s" does not define any collidable triangles (HasColliderMesh is false). Use a different class for the TCastleMeshCollider.Mesh, like TCastleScene.', [ |
| 2579 |
Name, |
| 2580 |
FMesh.Name, |
| 2581 |
FMesh.ClassName |
| 2582 |
]); |
| 2583 |
end else |
| 2584 |
begin |
| 2585 |
FMesh.ColliderMesh({$ifdef FPC}@{$endif} AddTriangle); |
| 2586 |
if FKraftMesh.CountVertices = 0 then |
| 2587 |
WritelnWarning('TCastleMeshCollider "%s": Mesh "%s:%s" is empty (has no collidable triangles)', [ |
| 2588 |
Name, |
| 2589 |
FMesh.Name, |
| 2590 |
FMesh.ClassName |
| 2591 |
]); |
| 2592 |
end; |
| 2593 |
|
| 2594 |
FKraftMesh.Finish; |
| 2595 |
|
| 2596 |
Result := TKraftShapeMesh.Create(APhysics, ARigidBody, FKraftMesh); |
| 2597 |
end; |
| 2598 |
|
| 2599 |
procedure TCastleMeshCollider.DeinitializePhysicsEngineObjects; |
| 2600 |
begin |
| 2601 |
inherited; |
| 2602 |
|
| 2603 |
{ TKraftMesh needs to be freed explicitly, Kraft collider will not do it. |
| 2604 |
Testcase: Memory leak reported in |
| 2605 |
https://forum.castle-engine.io/t/was-how-to-call-terrain-updategeometry-now-running-out-of-memory-updating-geometry-50x/849/8 |
| 2606 |
} |
| 2607 |
FreeAndNil(FKraftMesh); |
| 2608 |
end; |
| 2609 |
|
| 2610 |
procedure TCastleMeshCollider.SetMesh(const AValue: TCastleTransform); |
| 2611 |
begin |
| 2612 |
if FMesh <> AValue then |
| 2613 |
begin |
| 2614 |
{ During loading, because of how references are resolved, we may have SetMesh |
| 2615 |
temporarily called with a dummy empty TCastleTransform instance. |
| 2616 |
Ignore it (do not make warning from TCastleMeshCollider.CreateKraftShape, |
| 2617 |
actually don't even set FMesh to don't treat shape as ready to be initialized), |
| 2618 |
as this is normal. } |
| 2619 |
if IsLoading and |
| 2620 |
(AValue.ClassType = TCastleTransform) and |
| 2621 |
(AValue.Name = '') then |
| 2622 |
Exit; |
| 2623 |
|
| 2624 |
FMesh := AValue; |
| 2625 |
ShapeChangedNotifyRigidBody; |
| 2626 |
end; |
| 2627 |
end; |
| 2628 |
|
| 2629 |
procedure TCastleMeshCollider.SetDoubleSided(const Value: Boolean); |
| 2630 |
begin |
| 2631 |
if FDoubleSided <> Value then |
| 2632 |
begin |
| 2633 |
FDoubleSided := Value; |
| 2634 |
ShapeChangedNotifyRigidBody; |
| 2635 |
end; |
| 2636 |
end; |
| 2637 |
|
| 2638 |
function TCastleMeshCollider.PropertySections( |
| 2639 |
const PropertyName: String): TPropertySections; |
| 2640 |
begin |
| 2641 |
if ArrayContainsString(PropertyName, [ |
| 2642 |
'AutoSize', 'Mesh', 'DoubleSided' |
| 2643 |
]) then |
| 2644 |
Result := [psBasic] |
| 2645 |
else |
| 2646 |
Result := inherited PropertySections(PropertyName); |
| 2647 |
end; |
| 2648 |
|
| 2649 |
procedure TCastleMeshCollider.MeshChanged; |
| 2650 |
begin |
| 2651 |
ShapeChangedNotifyRigidBody; |
| 2652 |
end; |
| 2653 |
|
| 2654 |
procedure TCastleMeshCollider.InternalTransformChanged(const TransformChanged: TCastleTransform); |
| 2655 |
begin |
| 2656 |
inherited; |
| 2657 |
if TransformChanged = Mesh then |
| 2658 |
MeshChanged; |
| 2659 |
end; |
| 2660 |
|
| 2661 |
procedure TCastleMeshCollider.DesignerWarnings(const SList: TStrings); |
| 2662 |
begin |
| 2663 |
inherited; |
| 2664 |
if Mesh = nil then |
| 2665 |
SList.Add('Mesh is unassigned, TCastleMeshCollider effectively doesn''t work'); |
| 2666 |
end; |
| 2667 |
|
| 2668 |
{ TCastleRigidBody ----------------------------------------------------------- } |
| 2669 |
|
| 2670 |
constructor TCastleRigidBody.Create(AOwner: TComponent); |
| 2671 |
begin |
| 2672 |
inherited; |
| 2673 |
{ We need WorldAfterAttach, WorldBeforeDetach } |
| 2674 |
ListenWorldChange := true; |
| 2675 |
|
| 2676 |
FDuringSettingTransformationFromPhysicsEngine := false; |
| 2677 |
|
| 2678 |
// properties defaults |
| 2679 |
FGravity := true; |
| 2680 |
FDynamic := true; |
| 2681 |
FExists := true; |
| 2682 |
// default damp values from Kraft |
| 2683 |
FLinearVelocityDamp := 0.1; |
| 2684 |
FAngularVelocityDamp := 0.1; |
| 2685 |
|
| 2686 |
FKraftBody := nil; |
| 2687 |
FCollisionList := TCastleTransformList.Create(false); |
| 2688 |
FPrevCollisions := TCastleRigidBodyList.Create; |
| 2689 |
FCurrentCollisions := TCastleRigidBodyList.Create; |
| 2690 |
|
| 2691 |
FOnCollisionEnter := nil; |
| 2692 |
FOnCollisionExit := nil; |
| 2693 |
FTransform := nil; |
| 2694 |
FState := stateNone; |
| 2695 |
FLockRotation := []; |
| 2696 |
FLockTranslation := []; |
| 2697 |
FLayer := 0; |
| 2698 |
|
| 2699 |
{$define read_implementation_constructor} |
| 2700 |
{$I auto_generated_persistent_vectors/tcastlerigidbody_persistent_vectors.inc} |
| 2701 |
{$undef read_implementation_constructor} |
| 2702 |
end; |
| 2703 |
|
| 2704 |
destructor TCastleRigidBody.Destroy; |
| 2705 |
begin |
| 2706 |
{ The FKraftBody will be freed now if you free TCastleRigidBody |
| 2707 |
instance explicitly. In most other cases, DeinitializePhysicsEngineObjects |
| 2708 |
already freed FKraftBody and set it nil. } |
| 2709 |
|
| 2710 |
FreeAndNil(FKraftBody); |
| 2711 |
FreeAndNil(FCollisionList); |
| 2712 |
FreeAndNil(FPrevCollisions); |
| 2713 |
FreeAndNil(FCurrentCollisions); |
| 2714 |
|
| 2715 |
{$define read_implementation_destructor} |
| 2716 |
{$I auto_generated_persistent_vectors/tcastlerigidbody_persistent_vectors.inc} |
| 2717 |
{$undef read_implementation_destructor} |
| 2718 |
inherited; |
| 2719 |
end; |
| 2720 |
|
| 2721 |
procedure TCastleRigidBody.Setup2D; |
| 2722 |
begin |
| 2723 |
LockTranslation := [2]; |
| 2724 |
LockRotation := [0, 1]; |
| 2725 |
end; |
| 2726 |
|
| 2727 |
function ZeroLockedComponents(const V: TVector3; |
| 2728 |
const Locked: T3DCoords): TVector3; |
| 2729 |
begin |
| 2730 |
Result := V; |
| 2731 |
if 0 in Locked then Result.X := 0; |
| 2732 |
if 1 in Locked then Result.Y := 0; |
| 2733 |
if 2 in Locked then Result.Z := 0; |
| 2734 |
end; |
| 2735 |
|
| 2736 |
procedure TCastleRigidBody.InitializePhysicsEngineObjects; |
| 2737 |
begin |
| 2738 |
Assert(FKraftBody = nil, 'Kraft body is initialized!'); |
| 2739 |
|
| 2740 |
if Parent = nil then |
| 2741 |
raise Exception.Create('Cannot initialize physics in behavior not added to transform.'); |
| 2742 |
|
| 2743 |
{ We don't really need to access Parent.Parent, but |
| 2744 |
|
| 2745 |
- We need WorldTransform (so unique Parent.Parent or Parent.Parent = nil) |
| 2746 |
|
| 2747 |
- We do not sensibly work on Viewport.Items root -- |
| 2748 |
such body movement would affect also all children. |
| 2749 |
|
| 2750 |
So in practice we need Parent.Parent <> nil. } |
| 2751 |
if Parent.Parent = nil then |
| 2752 |
raise EMultipleReferencesInWorld.CreateFmt('Cannot use physics on %s. Reason is either:' + NL + |
| 2753 |
NL + |
| 2754 |
'1. It is the root transformation (Viewport.Items). You should instead: move the rigid body and collider behaviors to some child TCastleTransform.' + NL + |
| 2755 |
NL + |
| 2756 |
'2 It is inserted multiple times into the Viewport.Items. You should instead: Duplicate (clone) the instance. Or use TCastleTransformReference to refer to the TCastleTransform multiple times (and attach collider/rigid body to TCastleTransformReference).', [ |
| 2757 |
Parent.Name |
| 2758 |
]); |
| 2759 |
|
| 2760 |
FTransform := Parent; |
| 2761 |
InitializeEngineRigidBody; |
| 2762 |
InitializeCollider; |
| 2763 |
end; |
| 2764 |
|
| 2765 |
procedure TCastleRigidBody.DeinitializePhysicsEngineObjects; |
| 2766 |
begin |
| 2767 |
Assert(FKraftBody <> nil, 'Second deinitialization!'); |
| 2768 |
|
| 2769 |
Assert(Parent = FTransform, |
| 2770 |
'Parent should be the transform for which physics engine objects was initiated.'); |
| 2771 |
|
| 2772 |
Assert(Parent.World <> nil, |
| 2773 |
'Transform.World should be assigned at the time of TCastleRigidBody.DeinitializePhysicsEngineObjects call'); |
| 2774 |
|
| 2775 |
Assert(not ((Parent.World.FKraftEngine = nil) and (FKraftBody <> nil)), |
| 2776 |
'KraftBody should not live longer than KraftEngine!'); |
| 2777 |
|
| 2778 |
DeinitializeCollider; |
| 2779 |
|
| 2780 |
FreeAndNil(FKraftBody); |
| 2781 |
|
| 2782 |
FTransform := nil; |
| 2783 |
FState := stateNone; |
| 2784 |
end; |
| 2785 |
|
| 2786 |
procedure TCastleRigidBody.UpdateKraftRigidBodyType; |
| 2787 |
begin |
| 2788 |
if FState = stateNone then |
| 2789 |
begin |
| 2790 |
if FKraftBody <> nil then |
| 2791 |
begin |
| 2792 |
if FDynamic then |
| 2793 |
FKraftBody.SetRigidBodyType(krbtDynamic) |
| 2794 |
else |
| 2795 |
if FAnimated then |
| 2796 |
FKraftBody.SetRigidBodyType(krbtKinematic) |
| 2797 |
else |
| 2798 |
FKraftBody.SetRigidBodyType(krbtStatic); |
| 2799 |
end; |
| 2800 |
end else |
| 2801 |
begin |
| 2802 |
{ In Kraft you can't change body type when it was once created. |
| 2803 |
So we recreate rigid body physics objects. } |
| 2804 |
DeinitializePhysicsEngineObjects; |
| 2805 |
InitializePhysicsEngineObjects; |
| 2806 |
end; |
| 2807 |
end; |
| 2808 |
|
| 2809 |
procedure TCastleRigidBody.UpdateKraftGravity; |
| 2810 |
begin |
| 2811 |
if FKraftBody <> nil then |
| 2812 |
FKraftBody.GravityScale := Iff(Gravity, 1.0, 0.0); |
| 2813 |
end; |
| 2814 |
|
| 2815 |
procedure TCastleRigidBody.InitializeEngineRigidBody; |
| 2816 |
begin |
| 2817 |
World.InitializePhysicsEngine; |
| 2818 |
|
| 2819 |
FKraftBody := TKraftRigidBody.Create(World.FKraftEngine); |
| 2820 |
FKraftBody.UserData := Self; |
| 2821 |
|
| 2822 |
UpdateKraftRigidBodyType; |
| 2823 |
|
| 2824 |
FKraftBody.GravityScale := Iff(Gravity, 1.0, 0.0); |
| 2825 |
UpdateLockRotation; |
| 2826 |
UpdateLockTranslation; |
| 2827 |
|
| 2828 |
UpdateExistBody; |
| 2829 |
UpdateCollisionDetection; |
| 2830 |
UpdateLayer; |
| 2831 |
|
| 2832 |
if FTrigger then |
| 2833 |
FKraftBody.Flags := FKraftBody.Flags + [krbfSensor]; |
| 2834 |
|
| 2835 |
FState := stateMissingCollider; |
| 2836 |
end; |
| 2837 |
|
| 2838 |
procedure TCastleRigidBody.InitializeCollider; |
| 2839 |
|
| 2840 |
{ Returns TCastleCollider bahavior or @nil (when no TCastleCollider (behavior) is present in |
| 2841 |
the Parent or Parent = @nil). } |
| 2842 |
function GetCastleColliderFromParent: TCastleCollider; |
| 2843 |
begin |
| 2844 |
if Parent <> nil then |
| 2845 |
Result := Parent.FindBehavior(TCastleCollider) as TCastleCollider |
| 2846 |
else |
| 2847 |
Result := nil; |
| 2848 |
end; |
| 2849 |
|
| 2850 |
procedure FinishInitialization; |
| 2851 |
const |
| 2852 |
AllCollisionGroups = [ |
| 2853 |
Low (TKraftRigidBodyCollisionGroup).. |
| 2854 |
High(TKraftRigidBodyCollisionGroup)]; |
| 2855 |
var |
| 2856 |
V: TVector3; |
| 2857 |
begin |
| 2858 |
FKraftBody.ForcedMass := FCastleCollider.Mass; |
| 2859 |
|
| 2860 |
FKraftBody.Finish; |
| 2861 |
|
| 2862 |
if (not FAngularVelocity.IsPerfectlyZero) or |
| 2863 |
(not FLinearVelocity.IsPerfectlyZero) then |
| 2864 |
begin |
| 2865 |
{ The behavior is more natural when we zero the XxxVelocity |
| 2866 |
components that are locked. (Otherwise testing e.g. Setup2D in a 3D |
| 2867 |
world makes a little unexpected motions). } |
| 2868 |
|
| 2869 |
V := ZeroLockedComponents(FAngularVelocity, FLockRotation); |
| 2870 |
FKraftBody.AngularVelocity := VectorToKraft(V); |
| 2871 |
|
| 2872 |
V := ZeroLockedComponents(FLinearVelocity, FLockTranslation); |
| 2873 |
FKraftBody.LinearVelocity := VectorToKraft(V); |
| 2874 |
|
| 2875 |
FKraftBody.SetToAwake; |
| 2876 |
end; |
| 2877 |
|
| 2878 |
FKraftBody.LinearVelocityDamp := FLinearVelocityDamp; |
| 2879 |
FKraftBody.MaximalLinearVelocity := FMaxLinearVelocity / FTransform.World.FKraftEngine.WorldFrequency; |
| 2880 |
|
| 2881 |
FKraftBody.AngularVelocityDamp := FAngularVelocityDamp; |
| 2882 |
FKraftBody.MaximalAngularVelocity := FMaxAngularVelocity / FTransform.World.FKraftEngine.WorldFrequency; |
| 2883 |
|
| 2884 |
FState := stateReady; // before SetWorldTransformation that checks it |
| 2885 |
|
| 2886 |
{ Set initial transformation } |
| 2887 |
SetWorldTransformation(FTransform.WorldTransform); |
| 2888 |
|
| 2889 |
CheckPhysicsPostStepNeeded; |
| 2890 |
NotifyOnInitialized; |
| 2891 |
end; |
| 2892 |
|
| 2893 |
var |
| 2894 |
CastleColliderFromTransform: TCastleCollider; |
| 2895 |
begin |
| 2896 |
if FState = stateNone then |
| 2897 |
raise Exception.Create( |
| 2898 |
'InitializeCollider: Trying to add collider but rigid body not initialized.'); |
| 2899 |
|
| 2900 |
CastleColliderFromTransform := GetCastleColliderFromParent; |
| 2901 |
if (FCastleCollider <> CastleColliderFromTransform) and (FCastleCollider <> nil) then |
| 2902 |
begin |
| 2903 |
{ Trying to initialize rigid body with another collider without deinitialization |
| 2904 |
of the previous one. This should never occur. } |
| 2905 |
raise Exception.Create('Reinitialize with new collider but old one not deinitialized.'); |
| 2906 |
end; |
| 2907 |
|
| 2908 |
if CastleColliderFromTransform <> nil then |
| 2909 |
begin |
| 2910 |
CastleColliderFromTransform.InitializeKraft(Parent.World.FKraftEngine, Self); |
| 2911 |
FCastleCollider := CastleColliderFromTransform; |
| 2912 |
FinishInitialization; |
| 2913 |
Exit; |
| 2914 |
end; |
| 2915 |
end; |
| 2916 |
|
| 2917 |
procedure TCastleRigidBody.CheckInitialization(const ACastleCollider: TCastleCollider); |
| 2918 |
begin |
| 2919 |
{ FCastleCollider has pointer to castle collider behavior that was used to |
| 2920 |
initialize rigid body so we didn't need do anything. } |
| 2921 |
if FCastleCollider = ACastleCollider then |
| 2922 |
Exit; |
| 2923 |
|
| 2924 |
if (FState = stateMissingCollider) then |
| 2925 |
begin |
| 2926 |
// TODO: doesn't this miss FCastleCollider := ACastleCollider ? |
| 2927 |
if FCastleCollider = nil then |
| 2928 |
begin |
| 2929 |
InitializeCollider; |
| 2930 |
end else |
| 2931 |
if FCastleCollider <> ACastleCollider then |
| 2932 |
begin |
| 2933 |
{ Trying to initialize rigid body with another collider without deinitialization |
| 2934 |
of the previous one. This should never occur. } |
| 2935 |
raise Exception.Create('Reinitialize with new collider but old one not deinitialized.'); |
| 2936 |
end; |
| 2937 |
end; |
| 2938 |
end; |
| 2939 |
|
| 2940 |
procedure TCastleRigidBody.DeinitializeCollider; |
| 2941 |
|
| 2942 |
procedure RemoveSelfFromOtherRigidBodiesCollisionLists; |
| 2943 |
var |
| 2944 |
OtherRigidBody: TCastleRigidBody; |
| 2945 |
CollisionDetails: TPhysicsCollisionDetails; |
| 2946 |
ContactPairEdge: PKraftContactPairEdge; |
| 2947 |
begin |
| 2948 |
if FKraftBody = nil then |
| 2949 |
Exit; |
| 2950 |
|
| 2951 |
{ We don't use here FPrevCollisions list because it can be empty when |
| 2952 |
this rigid body didn't assign any FOnCollisionXXX event. } |
| 2953 |
ContactPairEdge := FKraftBody.ContactPairEdgeFirst; |
| 2954 |
while Assigned(ContactPairEdge) do |
| 2955 |
begin |
| 2956 |
if kcfColliding in ContactPairEdge^.ContactPair^.Flags then |
| 2957 |
begin |
| 2958 |
OtherRigidBody := TCastleRigidBody(ContactPairEdge^.OtherRigidBody.UserData); |
| 2959 |
|
| 2960 |
{ We need check that only when other body has OnCollisionExit or |
| 2961 |
OnCollisionStay event assigned. } |
| 2962 |
if Assigned(OtherRigidBody.FOnCollisionExit) or |
| 2963 |
Assigned(OtherRigidBody.FOnCollisionStay) then |
| 2964 |
begin |
| 2965 |
{ First we need send OnCollisionExit event if needed. } |
| 2966 |
if Assigned(OtherRigidBody.FOnCollisionExit) then |
| 2967 |
begin |
| 2968 |
CollisionDetails.Transforms[0] := OtherRigidBody.FTransform; |
| 2969 |
CollisionDetails.Transforms[1] := FTransform; |
| 2970 |
OtherRigidBody.FOnCollisionExit(CollisionDetails); |
| 2971 |
end; |
| 2972 |
|
| 2973 |
{ Now we can simply remove Self from other rigid body FPrevCollisions list } |
| 2974 |
OtherRigidBody.FPrevCollisions.Remove(Self); |
| 2975 |
{ Currently not needed because it's not used directly from other functions |
| 2976 |
than PhysicsPostStep() but this can change in the future. } |
| 2977 |
OtherRigidBody.FCurrentCollisions.Remove(Self); |
| 2978 |
end; |
| 2979 |
end; |
| 2980 |
ContactPairEdge := ContactPairEdge^.Next; |
| 2981 |
end; |
| 2982 |
end; |
| 2983 |
|
| 2984 |
begin |
| 2985 |
if FState = stateReady then |
| 2986 |
NotifyBeforeDeinitialized; |
| 2987 |
|
| 2988 |
{ Deinitialize rigid body when it's in collision with other rigid body make |
| 2989 |
this body will be dangling pointer on it's FPrevCollisions list. |
| 2990 |
So other rigid body can crash when it try to send FOnCollisionExit event. |
| 2991 |
Collisons must be handled before CastleCollider deinitialization because |
| 2992 |
kraft resets collisons when you remove collider. } |
| 2993 |
if FCastleCollider <> nil then |
| 2994 |
RemoveSelfFromOtherRigidBodiesCollisionLists; |
| 2995 |
|
| 2996 |
{ FCastleCollider.FKraftShape is owned by FKraftBody, |
| 2997 |
we need to free it (or nil) ASAP otherwise it will be freed |
| 2998 |
implicitly by FKraftBody freeing. } |
| 2999 |
if FCastleCollider <> nil then |
| 3000 |
begin |
| 3001 |
if FKraftBody.ShapeCount > 0 then |
| 3002 |
begin |
| 3003 |
Assert(FKraftBody.ShapeCount = 1, 'More than one shape in rigid body.'); |
| 3004 |
Assert(FKraftBody.ShapeFirst = FCastleCollider.FKraftShape, 'Mixed kraft shapes'); |
| 3005 |
end else |
| 3006 |
begin |
| 3007 |
Assert(FCastleCollider.FKraftShape = nil, 'FKraftBody.ShapeCount = 0 but FCastleCollider.FKraftShape <> nil.'); |
| 3008 |
end; |
| 3009 |
FCastleCollider.DeinitializePhysicsEngineObjects; |
| 3010 |
FCastleCollider := nil; |
| 3011 |
FState := stateMissingCollider; |
| 3012 |
end; |
| 3013 |
end; |
| 3014 |
|
| 3015 |
procedure TCastleRigidBody.ReinitializeCastleCollider; |
| 3016 |
begin |
| 3017 |
{ Don't try reinitialization when TCastleRigidBody is stateNone } |
| 3018 |
if FState = stateNone then |
| 3019 |
Exit; |
| 3020 |
|
| 3021 |
InitializeCollider; |
| 3022 |
end; |
| 3023 |
|
| 3024 |
class procedure TCastleRigidBody.CreateComponent2D(Sender: TObject); |
| 3025 |
begin |
| 3026 |
(Sender as TCastleRigidBody).Setup2D; |
| 3027 |
end; |
| 3028 |
|
| 3029 |
procedure TCastleRigidBody.AddNotificationOnInitialized( |
| 3030 |
const AEvent: TComponentEvent); |
| 3031 |
begin |
| 3032 |
if FNotifyOnInitialized = nil then |
| 3033 |
FNotifyOnInitialized := TCastleComponentNotification.Create(Self); |
| 3034 |
|
| 3035 |
FNotifyOnInitialized.AddNotification(AEvent); |
| 3036 |
end; |
| 3037 |
|
| 3038 |
procedure TCastleRigidBody.NotifyOnInitialized; |
| 3039 |
begin |
| 3040 |
if FNotifyOnInitialized = nil then |
| 3041 |
Exit; |
| 3042 |
|
| 3043 |
FNotifyOnInitialized.Notify(Self); |
| 3044 |
end; |
| 3045 |
|
| 3046 |
procedure TCastleRigidBody.RemoveNotificationOnInitialized( |
| 3047 |
const AEvent: TComponentEvent); |
| 3048 |
begin |
| 3049 |
if FNotifyOnInitialized = nil then |
| 3050 |
Exit; |
| 3051 |
|
| 3052 |
FNotifyOnInitialized.RemoveNotification(AEvent); |
| 3053 |
end; |
| 3054 |
|
| 3055 |
procedure TCastleRigidBody.AddNotificationBeforeDeinitialized( |
| 3056 |
const AEvent: TComponentEvent); |
| 3057 |
begin |
| 3058 |
if FNotifyBeforeDeinitialized = nil then |
| 3059 |
FNotifyBeforeDeinitialized := TCastleComponentNotification.Create(Self); |
| 3060 |
|
| 3061 |
FNotifyBeforeDeinitialized.AddNotification(AEvent); |
| 3062 |
end; |
| 3063 |
|
| 3064 |
procedure TCastleRigidBody.NotifyBeforeDeinitialized; |
| 3065 |
begin |
| 3066 |
if FNotifyBeforeDeinitialized = nil then |
| 3067 |
Exit; |
| 3068 |
|
| 3069 |
FNotifyBeforeDeinitialized.Notify(Self); |
| 3070 |
end; |
| 3071 |
|
| 3072 |
procedure TCastleRigidBody.RemoveNotificationBeforeDeinitialized( |
| 3073 |
const AEvent: TComponentEvent); |
| 3074 |
begin |
| 3075 |
if FNotifyBeforeDeinitialized = nil then |
| 3076 |
Exit; |
| 3077 |
|
| 3078 |
FNotifyBeforeDeinitialized.RemoveNotification(AEvent); |
| 3079 |
end; |
| 3080 |
|
| 3081 |
function TCastleRigidBody.IsInitialized: Boolean; |
| 3082 |
begin |
| 3083 |
Result := (FState = stateReady); |
| 3084 |
end; |
| 3085 |
|
| 3086 |
procedure TCastleRigidBody.PhysicsPostStep(const RigidBody: TKraftRigidBody; const TimeStep: TKraftTimeStep); |
| 3087 |
var |
| 3088 |
ContactPairEdge: PKraftContactPairEdge; |
| 3089 |
RBody: TCastleRigidBody; |
| 3090 |
CollisionDetails: TPhysicsCollisionDetails; |
| 3091 |
I: Integer; |
| 3092 |
begin |
| 3093 |
FCurrentCollisions.Clear; |
| 3094 |
ContactPairEdge := FKraftBody.ContactPairEdgeFirst; |
| 3095 |
while Assigned(ContactPairEdge) do |
| 3096 |
begin |
| 3097 |
{ Without this check, OnCollisonEnter reports fake collisons when |
| 3098 |
one of colliding body has non regular shape (for example when |
| 3099 |
TCastleBoxCollider is rotated). |
| 3100 |
kcfColliding = From kraft source comment: "Set when contact |
| 3101 |
collides during a step" } |
| 3102 |
if kcfColliding in ContactPairEdge^.ContactPair^.Flags then |
| 3103 |
begin |
| 3104 |
RBody := TCastleRigidBody(ContactPairEdge^.OtherRigidBody.UserData); |
| 3105 |
|
| 3106 |
// Do not send events for next collision points with the same body. |
| 3107 |
if FCurrentCollisions.IndexOf(RBody) = - 1 then |
| 3108 |
begin |
| 3109 |
// Add to current collisions. |
| 3110 |
FCurrentCollisions.Add(RBody); |
| 3111 |
|
| 3112 |
// Prepare collision data. |
| 3113 |
CollisionDetails.Transforms[0] := FTransform; |
| 3114 |
CollisionDetails.Transforms[1] := RBody.FTransform; |
| 3115 |
|
| 3116 |
// New and ongoing collisions. |
| 3117 |
if FPrevCollisions.IndexOf(RBody) = -1 then |
| 3118 |
begin |
| 3119 |
// New collision. |
| 3120 |
if Assigned(FOnCollisionEnter) then |
| 3121 |
begin |
| 3122 |
if not CollisionDetails.Transforms[0].RigidBody.Exists then |
| 3123 |
WriteLnWarning('TCastleRigidBody: Calling OnCollisionEnter when 1st TCastleRigidBody has Exists=false, submit a bug with testcase'); |
| 3124 |
if not CollisionDetails.Transforms[1].RigidBody.Exists then |
| 3125 |
WriteLnWarning('TCastleRigidBody: Calling OnCollisionEnter when 2nd TCastleRigidBody has Exists=false, submit a bug with testcase'); |
| 3126 |
FOnCollisionEnter(CollisionDetails); |
| 3127 |
end; |
| 3128 |
end else |
| 3129 |
begin |
| 3130 |
// Still in collision. |
| 3131 |
if Assigned(FOnCollisionStay) then |
| 3132 |
FOnCollisionStay(CollisionDetails); |
| 3133 |
|
| 3134 |
// Remove used collision. |
| 3135 |
FPrevCollisions.Remove(RBody); |
| 3136 |
end; |
| 3137 |
end; |
| 3138 |
end; |
| 3139 |
|
| 3140 |
ContactPairEdge := ContactPairEdge^.Next; |
| 3141 |
end; |
| 3142 |
|
| 3143 |
// check collision exit |
| 3144 |
if Assigned(FOnCollisionExit) then |
| 3145 |
begin |
| 3146 |
CollisionDetails.Transforms[0] := FTransform; |
| 3147 |
|
| 3148 |
for I := 0 to FPrevCollisions.Count - 1 do |
| 3149 |
begin |
| 3150 |
CollisionDetails.Transforms[1] := TCastleRigidBody(FPrevCollisions[I]).FTransform; |
| 3151 |
FOnCollisionExit(CollisionDetails); |
| 3152 |
end; |
| 3153 |
end; |
| 3154 |
|
| 3155 |
// Make previous list from current list. |
| 3156 |
FPrevCollisions.Clear; |
| 3157 |
FPrevCollisions.AddRange(FCurrentCollisions); |
| 3158 |
end; |
| 3159 |
|
| 3160 |
procedure TCastleRigidBody.CheckPhysicsPostStepNeeded; |
| 3161 |
begin |
| 3162 |
if not Assigned(FKraftBody) then |
| 3163 |
Exit; |
| 3164 |
|
| 3165 |
if Assigned(FOnCollisionEnter) or Assigned(FOnCollisionStay) or Assigned(FOnCollisionExit) then |
| 3166 |
FKraftBody.OnPostStep := {$ifdef FPC}@{$endif}PhysicsPostStep |
| 3167 |
else |
| 3168 |
FKraftBody.OnPostStep := nil; |
| 3169 |
end; |
| 3170 |
|
| 3171 |
function TCastleRigidBody.GetKraftShape: TKraftShape; |
| 3172 |
begin |
| 3173 |
if FCastleCollider <> nil then |
| 3174 |
Result := FCastleCollider.FKraftShape |
| 3175 |
else |
| 3176 |
Result := nil; |
| 3177 |
end; |
| 3178 |
|
| 3179 |
procedure TCastleRigidBody.UpdateExist; |
| 3180 |
|
| 3181 |
{ Call TCastleCollider.InternalAutoSize if we use the collider now. |
| 3182 |
|
| 3183 |
This is necessary to be called when size changed, and automatic size |
| 3184 |
(determined by TCastleCollider.AutoSize) should be recalculated. |
| 3185 |
Examples when it needs to be called: |
| 3186 |
If TCastleTransform did not exist in root at initialization or |
| 3187 |
TCastleScene URL changes. |
| 3188 |
|
| 3189 |
TODO: It is not sure whether its really needed to be called here, from UpdateExist. } |
| 3190 |
procedure UpdateColliderAutoSize; |
| 3191 |
begin |
| 3192 |
if ExistsInRoot and (FCastleCollider <> nil) then |
| 3193 |
begin |
| 3194 |
FCastleCollider.InternalAutoSize; |
| 3195 |
end; |
| 3196 |
end; |
| 3197 |
|
| 3198 |
var |
| 3199 |
KraftShape: TKraftShape; |
| 3200 |
begin |
| 3201 |
UpdateExistBody; |
| 3202 |
|
| 3203 |
KraftShape := GetKraftShape; |
| 3204 |
|
| 3205 |
if Assigned(KraftShape) then |
| 3206 |
begin |
| 3207 |
{ Note: ksfRayCastable flag determines whether body is detected by PhysicsRayCast. } |
| 3208 |
if ExistsInRoot then |
| 3209 |
KraftShape.Flags := KraftShape.Flags + [ksfCollision, |
| 3210 |
ksfRayCastable] |
| 3211 |
else |
| 3212 |
KraftShape.Flags := KraftShape.Flags - [ksfCollision, |
| 3213 |
ksfRayCastable]; |
| 3214 |
end; |
| 3215 |
|
| 3216 |
UpdateColliderAutoSize; |
| 3217 |
end; |
| 3218 |
|
| 3219 |
procedure TCastleRigidBody.UpdateExistBody; |
| 3220 |
begin |
| 3221 |
if Assigned(FKraftBody) then |
| 3222 |
begin |
| 3223 |
if ExistsInRoot then |
| 3224 |
FKraftBody.Flags := FKraftBody.Flags + [krbfActive] |
| 3225 |
else |
| 3226 |
FKraftBody.Flags := FKraftBody.Flags - [krbfActive]; |
| 3227 |
end; |
| 3228 |
end; |
| 3229 |
|
| 3230 |
procedure TCastleRigidBody.UpdateCollisionDetection; |
| 3231 |
begin |
| 3232 |
if Assigned(FKraftBody) then |
| 3233 |
begin |
| 3234 |
{ We set here krbfContinuous, krbfContinuousAgainstDynamics because |
| 3235 |
continuous works only when: |
| 3236 |
- one of bodies has krbfContinuous and they are dynamic bodies |
| 3237 |
- ContinuousAgainstDynamics is set to true in FKraftEngine |
| 3238 |
and one of bodies has krbfContinuousAgainstDynamics flag } |
| 3239 |
case FCollisionDetection of |
| 3240 |
cdDiscrete: |
| 3241 |
FKraftBody.Flags := FKraftBody.Flags - [krbfContinuous, krbfContinuousAgainstDynamics]; |
| 3242 |
cdContinuous: |
| 3243 |
FKraftBody.Flags := FKraftBody.Flags + [krbfContinuous, krbfContinuousAgainstDynamics]; |
| 3244 |
end; |
| 3245 |
end; |
| 3246 |
end; |
| 3247 |
|
| 3248 |
procedure TCastleRigidBody.KraftForceUpdatingReadyBody; |
| 3249 |
begin |
| 3250 |
if FState = stateReady then |
| 3251 |
begin |
| 3252 |
Assert(FKraftBody <> nil); // FState = stateReady already implies this |
| 3253 |
FKraftBody.Finish; |
| 3254 |
end; |
| 3255 |
end; |
| 3256 |
|
| 3257 |
procedure TCastleRigidBody.UpdateLockTranslation; |
| 3258 |
const |
| 3259 |
LockTranslationFlag: array [T3DCoord] of TKraftRigidBodyFlag = ( |
| 3260 |
krbfLockTranslationAxisX, |
| 3261 |
krbfLockTranslationAxisY, |
| 3262 |
krbfLockTranslationAxisZ |
| 3263 |
); |
| 3264 |
var |
| 3265 |
I: T3DCoord; |
| 3266 |
begin |
| 3267 |
if Assigned(FKraftBody) then |
| 3268 |
begin |
| 3269 |
for I := Low(I) to High(I) do |
| 3270 |
if I in FLockTranslation then |
| 3271 |
FKraftBody.Flags := FKraftBody.Flags + [LockTranslationFlag[I]] |
| 3272 |
else |
| 3273 |
FKraftBody.Flags := FKraftBody.Flags - [LockTranslationFlag[I]]; |
| 3274 |
KraftForceUpdatingReadyBody; |
| 3275 |
end; |
| 3276 |
end; |
| 3277 |
|
| 3278 |
procedure TCastleRigidBody.UpdateLockRotation; |
| 3279 |
const |
| 3280 |
LockRotationFlag: array [T3DCoord] of TKraftRigidBodyFlag = ( |
| 3281 |
krbfLockRotationAxisX, |
| 3282 |
krbfLockRotationAxisY, |
| 3283 |
krbfLockRotationAxisZ |
| 3284 |
); |
| 3285 |
var |
| 3286 |
I: T3DCoord; |
| 3287 |
begin |
| 3288 |
if Assigned(FKraftBody) then |
| 3289 |
begin |
| 3290 |
for I := Low(I) to High(I) do |
| 3291 |
if I in FLockRotation then |
| 3292 |
FKraftBody.Flags := FKraftBody.Flags + [LockRotationFlag[I]] |
| 3293 |
else |
| 3294 |
FKraftBody.Flags := FKraftBody.Flags - [LockRotationFlag[I]]; |
| 3295 |
KraftForceUpdatingReadyBody; |
| 3296 |
end; |
| 3297 |
end; |
| 3298 |
|
| 3299 |
procedure TCastleRigidBody.UpdateLayer; |
| 3300 |
var |
| 3301 |
CollideWith: TPhysicsLayer; |
| 3302 |
KraftCollideWith: TKraftRigidBodyCollisionGroups; |
| 3303 |
begin |
| 3304 |
if FKraftBody <> nil then |
| 3305 |
begin |
| 3306 |
FKraftBody.CollisionGroups := [FLayer]; |
| 3307 |
|
| 3308 |
// calculate KraftCollideWith and pass to Kraft |
| 3309 |
KraftCollideWith := []; |
| 3310 |
for CollideWith in FTransform.World.PhysicsProperties.LayerCollisions.FCollides[FLayer] do |
| 3311 |
Include(KraftCollideWith, CollideWith); |
| 3312 |
FKraftBody.CollideWithCollisionGroups := KraftCollideWith; |
| 3313 |
end; |
| 3314 |
end; |
| 3315 |
|
| 3316 |
procedure TCastleRigidBody.SetMaxAngularVelocity(const AValue: Single); |
| 3317 |
begin |
| 3318 |
FMaxAngularVelocity := AValue; |
| 3319 |
{ Kraft uses max velocity for delta time which is physics update frequency. } |
| 3320 |
if FKraftBody <> nil then |
| 3321 |
FKraftBody.MaximalAngularVelocity := AValue / FTransform.World.FKraftEngine.WorldFrequency; |
| 3322 |
end; |
| 3323 |
|
| 3324 |
procedure TCastleRigidBody.SetMaxLinearVelocity(const AValue: Single); |
| 3325 |
begin |
| 3326 |
FMaxLinearVelocity := AValue; |
| 3327 |
{ Kraft uses max velocity for delta time which is physics update frequency. } |
| 3328 |
if FKraftBody <> nil then |
| 3329 |
FKraftBody.MaximalLinearVelocity := AValue / FTransform.World.FKraftEngine.WorldFrequency; |
| 3330 |
end; |
| 3331 |
|
| 3332 |
procedure TCastleRigidBody.SetOnCollisionEnter(const AValue: TCollisionEvent); |
| 3333 |
begin |
| 3334 |
FOnCollisionEnter := AValue; |
| 3335 |
CheckPhysicsPostStepNeeded; |
| 3336 |
end; |
| 3337 |
|
| 3338 |
procedure TCastleRigidBody.SetOnCollisionStay(const AValue: TCollisionEvent); |
| 3339 |
begin |
| 3340 |
FOnCollisionStay := AValue; |
| 3341 |
CheckPhysicsPostStepNeeded; |
| 3342 |
end; |
| 3343 |
|
| 3344 |
procedure TCastleRigidBody.SetOnCollisionExit(const AValue: TCollisionEvent); |
| 3345 |
begin |
| 3346 |
FOnCollisionExit := AValue; |
| 3347 |
CheckPhysicsPostStepNeeded; |
| 3348 |
end; |
| 3349 |
|
| 3350 |
procedure TCastleRigidBody.SetCollisionDetection(const AValue: TCollisionDetection); |
| 3351 |
begin |
| 3352 |
if FCollisionDetection = AValue then |
| 3353 |
Exit; |
| 3354 |
|
| 3355 |
FCollisionDetection := AValue; |
| 3356 |
UpdateCollisionDetection; |
| 3357 |
end; |
| 3358 |
|
| 3359 |
procedure TCastleRigidBody.SetLayer(const AValue: TPhysicsLayer); |
| 3360 |
begin |
| 3361 |
if FLayer <> AValue then |
| 3362 |
begin |
| 3363 |
FLayer := AValue; |
| 3364 |
UpdateLayer; |
| 3365 |
end; |
| 3366 |
end; |
| 3367 |
|
| 3368 |
procedure TCastleRigidBody.SetDynamic(const AValue: Boolean); |
| 3369 |
begin |
| 3370 |
if FDynamic <> AValue then |
| 3371 |
begin |
| 3372 |
FDynamic := AValue; |
| 3373 |
UpdateKraftRigidBodyType; |
| 3374 |
end; |
| 3375 |
end; |
| 3376 |
|
| 3377 |
procedure TCastleRigidBody.SetAnimated(const AValue: Boolean); |
| 3378 |
begin |
| 3379 |
if FAnimated <> AValue then |
| 3380 |
begin |
| 3381 |
FAnimated := AValue; |
| 3382 |
UpdateKraftRigidBodyType; |
| 3383 |
end; |
| 3384 |
end; |
| 3385 |
|
| 3386 |
procedure TCastleRigidBody.SetGravity(const AValue: Boolean); |
| 3387 |
begin |
| 3388 |
if FGravity <> AValue then |
| 3389 |
begin |
| 3390 |
FGravity := AValue; |
| 3391 |
UpdateKraftGravity; |
| 3392 |
end; |
| 3393 |
end; |
| 3394 |
|
| 3395 |
procedure TCastleRigidBody.SetAngularVelocityDamp(const AValue: Single); |
| 3396 |
begin |
| 3397 |
FAngularVelocityDamp := AValue; |
| 3398 |
if FKraftBody <> nil then |
| 3399 |
FKraftBody.AngularVelocityDamp := AValue; |
| 3400 |
end; |
| 3401 |
|
| 3402 |
procedure TCastleRigidBody.SetLinearVelocityDamp(const AValue: Single); |
| 3403 |
begin |
| 3404 |
FLinearVelocityDamp := AValue; |
| 3405 |
if FKraftBody <> nil then |
| 3406 |
FKraftBody.LinearVelocityDamp := AValue; |
| 3407 |
end; |
| 3408 |
|
| 3409 |
procedure TCastleRigidBody.SynchronizeFromKraft; |
| 3410 |
begin |
| 3411 |
if FKraftBody = nil then |
| 3412 |
Exit; |
| 3413 |
|
| 3414 |
FLinearVelocity := VectorFromKraft(FKraftBody.LinearVelocity); |
| 3415 |
FAngularVelocity := VectorFromKraft(FKraftBody.AngularVelocity); |
| 3416 |
end; |
| 3417 |
|
| 3418 |
procedure TCastleRigidBody.SetWorldTransformation(const WorldTransform: TMatrix4); |
| 3419 |
var |
| 3420 |
Translation, Scale: TVector3; |
| 3421 |
Rotation: TVector4; |
| 3422 |
T: TTransformation; |
| 3423 |
begin |
| 3424 |
{ If we just set transformation from physics engine this is a guard |
| 3425 |
to not update rigid body transformation. See TransformationFromKraft } |
| 3426 |
if FDuringSettingTransformationFromPhysicsEngine then |
| 3427 |
Exit; |
| 3428 |
|
| 3429 |
if FState <> stateReady then |
| 3430 |
Exit; |
| 3431 |
|
| 3432 |
{ Remove scale from world transform because using scale in kraft |
| 3433 |
leads to an undefined state. } |
| 3434 |
MatrixDecompose(WorldTransform, Translation, Rotation, Scale); |
| 3435 |
|
| 3436 |
T.Init; |
| 3437 |
T.Multiply(Rotation, NoScale, Translation); |
| 3438 |
|
| 3439 |
FKraftBody.SetWorldTransformation(MatrixToKraft(T.Transform)); |
| 3440 |
|
| 3441 |
{ Synchronize Kraft rigid body and shapes (colliders) transform to make |
| 3442 |
collider position correct. Without the SynchronizeTransformIncludingShapes, |
| 3443 |
first (before physics step) TransformationFromKraft |
| 3444 |
would set weird TCastleTransform position. |
| 3445 |
|
| 3446 |
Testcase: run physics_2d_collisions, press space (pause) and R (restart). |
| 3447 |
The plane should jump to predictable initial position (TPlane.Create). |
| 3448 |
Without the SynchronizeTransformIncludingShapes call, it jumps to |
| 3449 |
an incorrect position. |
| 3450 |
|
| 3451 |
Also, because we use shape InterpolatedWorldTransform we need to store |
| 3452 |
it for correct result. } |
| 3453 |
FKraftBody.SynchronizeTransformIncludingShapes; |
| 3454 |
GetKraftShape.StoreWorldTransform; |
| 3455 |
end; |
| 3456 |
|
| 3457 |
procedure TCastleRigidBody.SetLockTranslation(const AValue: T3DCoords); |
| 3458 |
begin |
| 3459 |
if FLockTranslation = AValue then |
| 3460 |
Exit; |
| 3461 |
|
| 3462 |
FLockTranslation := AValue; |
| 3463 |
UpdateLockTranslation; |
| 3464 |
end; |
| 3465 |
|
| 3466 |
procedure TCastleRigidBody.SetLockRotation(const AValue: T3DCoords); |
| 3467 |
begin |
| 3468 |
if FLockRotation = AValue then |
| 3469 |
Exit; |
| 3470 |
|
| 3471 |
FLockRotation := AValue; |
| 3472 |
UpdateLockRotation; |
| 3473 |
end; |
| 3474 |
|
| 3475 |
procedure TCastleRigidBody.Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); |
| 3476 |
|
| 3477 |
// function TranslationFromMatrix(const M: TMatrix4): TVector3; |
| 3478 |
// begin |
| 3479 |
// Result := PVector3(@M.Data[3])^; |
| 3480 |
// end; |
| 3481 |
|
| 3482 |
{ Update current transformation from Kraft rigid body parameters. } |
| 3483 |
procedure TransformationFromKraft; |
| 3484 |
var |
| 3485 |
// Q: TKraftQuaternion; |
| 3486 |
// Axis: TKraftVector3; |
| 3487 |
// Angle: TKraftScalar; |
| 3488 |
Shape: TKraftShape; |
| 3489 |
LocalTransform: TMatrix4; |
| 3490 |
Translation, Scale: TVector3; |
| 3491 |
Rotation: TVector4; |
| 3492 |
begin |
| 3493 |
FDuringSettingTransformationFromPhysicsEngine := true; |
| 3494 |
try |
| 3495 |
Shape := GetKraftShape; |
| 3496 |
|
| 3497 |
if Shape = nil then |
| 3498 |
Exit; |
| 3499 |
|
| 3500 |
LocalTransform := Parent.CheckParent.WorldInverseTransform * |
| 3501 |
MatrixFromKraft(Shape.InterpolatedWorldTransform); |
| 3502 |
if (FCastleCollider <> nil) and |
| 3503 |
(FCastleCollider.FUseLocalTransform) then |
| 3504 |
LocalTransform := LocalTransform * FCastleCollider.FLocalInverseTransform; |
| 3505 |
|
| 3506 |
{ Don't use Scale form Kraft. |
| 3507 |
It should be always 1. We set CGE scale by changing Kraft collider sizes. |
| 3508 |
See SetWorldTransformation() for more information. } |
| 3509 |
MatrixDecompose(LocalTransform, Translation, Rotation, Scale); |
| 3510 |
Parent.Rotation := Rotation; |
| 3511 |
Parent.Translation := Translation; |
| 3512 |
|
| 3513 |
{ This is an alternative version using Kraft to do matrix decomposition. } |
| 3514 |
// Q := QuaternionFromMatrix4x4(MatrixToKraft(LocalTransform)); |
| 3515 |
// QuaternionToAxisAngle(Q, Axis, Angle); |
| 3516 |
// Transform.Rotation := Vector4(Axis.X, Axis.Y, Axis.Z, Angle); |
| 3517 |
|
| 3518 |
// Transform.Translation := TranslationFromMatrix(LocalTransform); |
| 3519 |
finally |
| 3520 |
FDuringSettingTransformationFromPhysicsEngine := false; |
| 3521 |
end; |
| 3522 |
end; |
| 3523 |
|
| 3524 |
begin |
| 3525 |
inherited; |
| 3526 |
|
| 3527 |
{ Disable updating physics in design mode } |
| 3528 |
if CastleApplicationMode in [appDesign, appSimulationPaused] then |
| 3529 |
Exit; |
| 3530 |
|
| 3531 |
if Parent = nil then |
| 3532 |
Exit; |
| 3533 |
|
| 3534 |
if (Parent.World <> nil) and (not Parent.World.EnablePhysics) then |
| 3535 |
Exit; |
| 3536 |
|
| 3537 |
if Dynamic then |
| 3538 |
begin |
| 3539 |
TransformationFromKraft; |
| 3540 |
SynchronizeFromKraft; |
| 3541 |
end |
| 3542 |
|
| 3543 |
{ Note: We don't do anything special for Animated here. |
| 3544 |
And we allow changing TCastleTransform from code regardless of whether |
| 3545 |
Animated = true or false. |
| 3546 |
So Animated is really just an "optimization hint" passed to Kraft |
| 3547 |
(determines if we should set body as krbtKinematic or krbtStatic, when Dynamic = false). |
| 3548 |
Nothing more. } |
| 3549 |
end; |
| 3550 |
|
| 3551 |
function TCastleRigidBody.CanAttachToParent(const NewParent: TCastleTransform; |
| 3552 |
out ReasonWhyCannot: String): Boolean; |
| 3553 |
begin |
| 3554 |
Result := inherited; |
| 3555 |
if not Result then Exit; |
| 3556 |
|
| 3557 |
if NewParent.FindBehavior(TCastleRigidBody) <> nil then |
| 3558 |
begin |
| 3559 |
ReasonWhyCannot := 'Only one TCastleRigidBody behavior can be added to a given TCastleTransform'; |
| 3560 |
Result := false; |
| 3561 |
end; |
| 3562 |
end; |
| 3563 |
|
| 3564 |
procedure TCastleRigidBody.WorldAfterAttach; |
| 3565 |
begin |
| 3566 |
inherited; |
| 3567 |
|
| 3568 |
if World <> nil then |
| 3569 |
InitializePhysicsEngineObjects; |
| 3570 |
end; |
| 3571 |
|
| 3572 |
procedure TCastleRigidBody.WorldBeforeDetach; |
| 3573 |
begin |
| 3574 |
if FState <> stateNone then |
| 3575 |
begin |
| 3576 |
Assert(Parent = FTransform, 'Parent and FTransform should be the same.'); |
| 3577 |
DeinitializePhysicsEngineObjects; |
| 3578 |
end; |
| 3579 |
|
| 3580 |
inherited; |
| 3581 |
end; |
| 3582 |
|
| 3583 |
function TCastleRigidBody.GetCollidingTransforms: TCastleTransformList; |
| 3584 |
var |
| 3585 |
ContactPairEdge: PKraftContactPairEdge; |
| 3586 |
CastleTransform:TCastleTransform; |
| 3587 |
begin |
| 3588 |
Result := FCollisionList; |
| 3589 |
FCollisionList.Clear; |
| 3590 |
ContactPairEdge := FKraftBody.ContactPairEdgeFirst; |
| 3591 |
while Assigned(ContactPairEdge) do |
| 3592 |
begin |
| 3593 |
if not (kcfColliding in ContactPairEdge^.ContactPair^.Flags) then |
| 3594 |
begin |
| 3595 |
ContactPairEdge := ContactPairEdge^.Next; |
| 3596 |
continue; |
| 3597 |
end; |
| 3598 |
|
| 3599 |
CastleTransform := (TCastleRigidBody(ContactPairEdge^.OtherRigidBody.UserData)).FTransform; |
| 3600 |
if FCollisionList.IndexOf(CastleTransform) = -1 then |
| 3601 |
FCollisionList.Add(CastleTransform); |
| 3602 |
ContactPairEdge := ContactPairEdge^.Next; |
| 3603 |
end; |
| 3604 |
end; |
| 3605 |
|
| 3606 |
function TCastleRigidBody.PhysicsRayCast(const RayOrigin, RayDirection: TVector3; |
| 3607 |
const MaxDistance: Single): TPhysicsRayCastResult; |
| 3608 |
var |
| 3609 |
RayOriginWorld, RayDirectionWorld: TVector3; |
| 3610 |
MaxDistanceWorld: Single; |
| 3611 |
begin |
| 3612 |
if FTransform = nil then |
| 3613 |
begin |
| 3614 |
WritelnWarning('Attempt to cast a ray from TCastleRigidBody not connected to any TCastleTransform. Possibly you forgot to add it using TCastleTransform.AddBehavior.'); |
| 3615 |
FillChar(Result, SizeOf(Result), 0); // this in particular sets Result.Hit = false |
| 3616 |
Exit; |
| 3617 |
end; |
| 3618 |
|
| 3619 |
if FTransform.World = nil then |
| 3620 |
begin |
| 3621 |
WritelnWarning('Attempt to cast a ray from TCastleRigidBody not connected to any World. Possibly you forgot to add the TCastleTransform to TCastleViewport.Items.'); |
| 3622 |
FillChar(Result, SizeOf(Result), 0); // this in particular sets Result.Hit = false |
| 3623 |
Exit; |
| 3624 |
end; |
| 3625 |
|
| 3626 |
if FTransform.Parent <> nil then |
| 3627 |
begin |
| 3628 |
RayOriginWorld := FTransform.Parent.LocalToWorld(RayOrigin); |
| 3629 |
RayDirectionWorld := FTransform.Parent.LocalToWorldDirection(RayDirection); |
| 3630 |
MaxDistanceWorld := FTransform.Parent.LocalToWorldDistance(MaxDistance); |
| 3631 |
end else |
| 3632 |
begin |
| 3633 |
RayOriginWorld := RayOrigin; |
| 3634 |
RayDirectionWorld := RayDirection; |
| 3635 |
MaxDistanceWorld := MaxDistance; |
| 3636 |
end; |
| 3637 |
|
| 3638 |
Result := FTransform.World.PhysicsRayCast(RayOriginWorld, RayDirectionWorld, |
| 3639 |
MaxDistanceWorld, Self); |
| 3640 |
|
| 3641 |
if Result.Hit and (FTransform.Parent <> nil) then |
| 3642 |
begin |
| 3643 |
Result.Distance := FTransform.Parent.WorldToLocalDistance(Result.Distance); |
| 3644 |
Result.Point := FTransform.Parent.WorldToLocal(Result.Point); |
| 3645 |
Result.Normal := FTransform.Parent.WorldToLocalDirection(Result.Normal); |
| 3646 |
end; |
| 3647 |
end; |
| 3648 |
|
| 3649 |
function TCastleRigidBody.PropertySections( |
| 3650 |
const PropertyName: String): TPropertySections; |
| 3651 |
begin |
| 3652 |
if ArrayContainsString(PropertyName, [ |
| 3653 |
'Dynamic', 'Animated', 'Trigger', 'Gravity', 'LockTranslation', 'Exists', |
| 3654 |
'AngularVelocityPersistent', 'AngularVelocityDamp', 'MaxAngularVelocity', |
| 3655 |
'LinearVelocityPersistent', 'LinearVelocityDamp', 'MaxLinearVelocity', |
| 3656 |
'CollisionDetection', 'LockRotation', 'Layer' |
| 3657 |
]) then |
| 3658 |
Result := [psBasic] |
| 3659 |
else |
| 3660 |
Result := inherited PropertySections(PropertyName); |
| 3661 |
end; |
| 3662 |
|
| 3663 |
procedure TCastleRigidBody.AddForceAtPosition(const Force, Position: TVector3); |
| 3664 |
begin |
| 3665 |
if FKraftBody <> nil then |
| 3666 |
begin |
| 3667 |
if ExistsInRoot then |
| 3668 |
begin |
| 3669 |
FKraftBody.AddForceAtPosition(VectorToKraft(Force), VectorToKraft(Position)); |
| 3670 |
WakeUp; |
| 3671 |
end; |
| 3672 |
end else |
| 3673 |
WritelnWarning('Attempting to add force before physics engine initialization.'); |
| 3674 |
end; |
| 3675 |
|
| 3676 |
procedure TCastleRigidBody.AddForce(const Force: TVector3; const ForceInLocalCoordinates: Boolean); |
| 3677 |
begin |
| 3678 |
if FKraftBody <> nil then |
| 3679 |
begin |
| 3680 |
if ExistsInRoot then |
| 3681 |
begin |
| 3682 |
if ForceInLocalCoordinates then |
| 3683 |
FKraftBody.AddBodyForce(VectorToKraft(Force)) |
| 3684 |
else |
| 3685 |
FKraftBody.AddWorldForce(VectorToKraft(Force)); |
| 3686 |
WakeUp; |
| 3687 |
end; |
| 3688 |
end else |
| 3689 |
WritelnWarning('Attempting to add force before physics engine initialization.'); |
| 3690 |
end; |
| 3691 |
|
| 3692 |
procedure TCastleRigidBody.AddTorque(const Torque: TVector3); |
| 3693 |
begin |
| 3694 |
if FKraftBody <> nil then |
| 3695 |
begin |
| 3696 |
if ExistsInRoot then |
| 3697 |
begin |
| 3698 |
FKraftBody.AddWorldTorque(VectorToKraft(Torque)); |
| 3699 |
WakeUp; |
| 3700 |
end; |
| 3701 |
end else |
| 3702 |
WritelnWarning('Attempting to add torque before physics engine initialization.'); |
| 3703 |
end; |
| 3704 |
|
| 3705 |
procedure TCastleRigidBody.ApplyImpulse(const Impulse, Point: TVector3); |
| 3706 |
begin |
| 3707 |
if FKraftBody <> nil then |
| 3708 |
begin |
| 3709 |
if ExistsInRoot then |
| 3710 |
begin |
| 3711 |
FKraftBody.ApplyImpulseAtPosition(VectorToKraft(Point), VectorToKraft(Impulse)); |
| 3712 |
WakeUp; |
| 3713 |
end; |
| 3714 |
end else |
| 3715 |
WritelnWarning('Attempting to apply impulse before physics engine initialization.'); |
| 3716 |
end; |
| 3717 |
|
| 3718 |
function TCastleRigidBody.ExistsInRoot: Boolean; |
| 3719 |
begin |
| 3720 |
if Exists = false then |
| 3721 |
Exit(false); |
| 3722 |
|
| 3723 |
if Parent = nil then |
| 3724 |
Exit(false); |
| 3725 |
|
| 3726 |
Result := Parent.ExistsInRoot; |
| 3727 |
end; |
| 3728 |
|
| 3729 |
procedure TCastleRigidBody.WakeUp; |
| 3730 |
begin |
| 3731 |
FKraftBody.SetToAwake; |
| 3732 |
end; |
| 3733 |
|
| 3734 |
{ // commented out as should never be needed by actual user code |
| 3735 |
|
| 3736 |
procedure TCastleRigidBody.Sleep; |
| 3737 |
begin |
| 3738 |
FKraftBody.SetToSleep; |
| 3739 |
end; |
| 3740 |
} |
| 3741 |
|
| 3742 |
procedure TCastleRigidBody.SetLinearVelocity(const LVelocity: TVector3); |
| 3743 |
begin |
| 3744 |
FLinearVelocity := LVelocity; |
| 3745 |
if FKraftBody <> nil then |
| 3746 |
begin |
| 3747 |
FKraftBody.LinearVelocity := VectorToKraft(ZeroLockedComponents(LVelocity, FLockTranslation)); |
| 3748 |
if not LVelocity.IsPerfectlyZero then |
| 3749 |
FKraftBody.SetToAwake; |
| 3750 |
end; |
| 3751 |
end; |
| 3752 |
|
| 3753 |
procedure TCastleRigidBody.SetAngularVelocity(const AVelocity: TVector3); |
| 3754 |
begin |
| 3755 |
FAngularVelocity := AVelocity; |
| 3756 |
if FKraftBody <> nil then |
| 3757 |
begin |
| 3758 |
FKraftBody.AngularVelocity := VectorToKraft(ZeroLockedComponents(AVelocity, FLockRotation)); |
| 3759 |
if not AVelocity.IsPerfectlyZero then |
| 3760 |
FKraftBody.SetToAwake; |
| 3761 |
end; |
| 3762 |
end; |
| 3763 |
|
| 3764 |
procedure TCastleRigidBody.SetExists(const Value: Boolean); |
| 3765 |
begin |
| 3766 |
if FExists = Value then |
| 3767 |
Exit; |
| 3768 |
|
| 3769 |
FExists := Value; |
| 3770 |
|
| 3771 |
if FTransform <> nil then |
| 3772 |
UpdateExist; |
| 3773 |
end; |
| 3774 |
|
| 3775 |
procedure TCastleRigidBody.SetTrigger(const Value: Boolean); |
| 3776 |
begin |
| 3777 |
if FTrigger = Value then |
| 3778 |
Exit; |
| 3779 |
|
| 3780 |
FTrigger := Value; |
| 3781 |
|
| 3782 |
if Assigned(FKraftBody) then |
| 3783 |
begin |
| 3784 |
if FTrigger then |
| 3785 |
FKraftBody.Flags := FKraftBody.Flags + [krbfSensor] |
| 3786 |
else |
| 3787 |
FKraftBody.Flags := FKraftBody.Flags - [krbfSensor]; |
| 3788 |
end; |
| 3789 |
end; |
| 3790 |
|
| 3791 |
{$define read_implementation_methods} |
| 3792 |
{$I auto_generated_persistent_vectors/tcastlerigidbody_persistent_vectors.inc} |
| 3793 |
{$undef read_implementation_methods} |
| 3794 |
|
| 3795 |
{ TCastleAbstractRootTransform ------------------------------------------------------------------- } |
| 3796 |
|
| 3797 |
procedure TCastleAbstractRootTransform.InitializePhysicsEngine; |
| 3798 |
begin |
| 3799 |
if FKraftEngine = nil then |
| 3800 |
begin |
| 3801 |
FKraftEngine := TKraft.Create(-1); |
| 3802 |
{ Kraft sets MaximalLinearVelocity in TKraft Constructor to 2. |
| 3803 |
With this limit can't make velocity greater than about 120 |
| 3804 |
(2 * engine step frequency = 2 * 60 = 120). That makes physics |
| 3805 |
very slow, so we need remove this limitation. } |
| 3806 |
FKraftEngine.MaximalLinearVelocity := 0; |
| 3807 |
FKraftEngine.SetFrequency(PhysicsProperties.Frequency); |
| 3808 |
FKraftEngine.AngularVelocityRK4Integration := PhysicsProperties.AngularVelocityRK4Integration; |
| 3809 |
FKraftEngine.LinearVelocityRK4Integration := PhysicsProperties.LinearVelocityRK4Integration; |
| 3810 |
if PhysicsProperties.ContinuousCollisionDetection then |
| 3811 |
begin |
| 3812 |
{ Andrzej says: I tested all options: |
| 3813 |
|
| 3814 |
- kcmSpeculativeContacts: |
| 3815 |
it's fake so sometime we have fake collisons |
| 3816 |
|
| 3817 |
- kcmTimeOfImpactSubSteps: |
| 3818 |
bullets in platformer sometimes pass through the walls, |
| 3819 |
all TimeOfImpactAlgorithm algorithms have this issue. |
| 3820 |
|
| 3821 |
- kcmMotionClamping: |
| 3822 |
works best I think (but may lead to a momentary loss of time in a collision). |
| 3823 |
|
| 3824 |
Future: Maybe give user ability to choose ContinuousMode. } |
| 3825 |
FKraftEngine.ContinuousMode := kcmMotionClamping; |
| 3826 |
{ We need to set this because continuous works only when: |
| 3827 |
- one of the bodies has krbfContinuous and they are dynamic |
| 3828 |
- ContinuousAgainstDynamics is set to true in |
| 3829 |
FKraftEngine and one of bodies has krbfContinuousAgainstDynamics flag } |
| 3830 |
FKraftEngine.ContinuousAgainstDynamics := true; |
| 3831 |
{ Below are useful only for kcmTimeOfImpactSubSteps mode } |
| 3832 |
// FKraftEngine.TimeOfImpactAlgorithm := ktoiaConservativeAdvancement; |
| 3833 |
// FKraftEngine.MaximalSubSteps := 16; |
| 3834 |
end else |
| 3835 |
begin |
| 3836 |
FKraftEngine.ContinuousMode := kcmNone; |
| 3837 |
FKraftEngine.ContinuousAgainstDynamics := false; |
| 3838 |
end; |
| 3839 |
end; |
| 3840 |
end; |
| 3841 |
|
| 3842 |
procedure TCastleAbstractRootTransform.DestroyPhysicsEngine; |
| 3843 |
var |
| 3844 |
CastleRigidBody: TCastleRigidBody; |
| 3845 |
KraftRigidBody: TKraftRigidBody; |
| 3846 |
NextKraftRigidBody: TKraftRigidBody; |
| 3847 |
begin |
| 3848 |
if FKraftEngine <> nil then |
| 3849 |
begin |
| 3850 |
KraftRigidBody := FKraftEngine.RigidBodyFirst; |
| 3851 |
|
| 3852 |
while Assigned(KraftRigidBody) do |
| 3853 |
begin |
| 3854 |
NextKraftRigidBody := KraftRigidBody.RigidBodyNext; |
| 3855 |
if Assigned(KraftRigidBody.UserData) then |
| 3856 |
begin |
| 3857 |
CastleRigidBody := TCastleRigidBody(KraftRigidBody.UserData); |
| 3858 |
CastleRigidBody.DeinitializePhysicsEngineObjects; |
| 3859 |
end; |
| 3860 |
KraftRigidBody := NextKraftRigidBody; |
| 3861 |
end; |
| 3862 |
|
| 3863 |
FreeAndNil(FKraftEngine); |
| 3864 |
end; |
| 3865 |
end; |
| 3866 |
|
| 3867 |
procedure TCastleAbstractRootTransform.Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); |
| 3868 |
var |
| 3869 |
KraftGravity: TVector3; |
| 3870 |
PhysicsTicksCount:Integer; |
| 3871 |
{$ifdef CASTLE_LOG_PHYSICS_DROPS_FRAMES} |
| 3872 |
OldTimeAccumulator: TFloatTime; |
| 3873 |
{$endif} |
| 3874 |
begin |
| 3875 |
if not Exists then Exit; |
| 3876 |
|
| 3877 |
{ Avoid doing this two times within the same FrameId. |
| 3878 |
Important if the same TCastleAbstractRootTransform is present in multiple viewports. } |
| 3879 |
if UpdateFrameId = TFramesPerSecond.FrameId then |
| 3880 |
Exit; |
| 3881 |
UpdateFrameId := TFramesPerSecond.FrameId; |
| 3882 |
|
| 3883 |
if IsPhysicsRunning then |
| 3884 |
begin |
| 3885 |
FrameProfiler.Start(fmUpdatePhysics); |
| 3886 |
|
| 3887 |
// update FKraftEngine.Gravity |
| 3888 |
// TODO: do we really need to be prepared that it changes each frame? |
| 3889 |
KraftGravity := -GravityUp * PhysicsProperties.GravityStrength; |
| 3890 |
FKraftEngine.Gravity.Vector := VectorToKraft(KraftGravity); |
| 3891 |
|
| 3892 |
PhysicsTicksCount := 0; |
| 3893 |
|
| 3894 |
if not WasPhysicsStep then |
| 3895 |
begin |
| 3896 |
FKraftEngine.StoreWorldTransforms; |
| 3897 |
FKraftEngine.InterpolateWorldTransforms(0.0); |
| 3898 |
WasPhysicsStep := true; |
| 3899 |
end else |
| 3900 |
begin |
| 3901 |
TimeAccumulator := TimeAccumulator + SecondsPassed; |
| 3902 |
while TimeAccumulator >= PhysicsProperties.FPhysicsTimeStep do |
| 3903 |
begin |
| 3904 |
TimeAccumulator := TimeAccumulator - PhysicsProperties.FPhysicsTimeStep; |
| 3905 |
FKraftEngine.StoreWorldTransforms; |
| 3906 |
FKraftEngine.Step(PhysicsProperties.FPhysicsTimeStep); |
| 3907 |
|
| 3908 |
Inc(PhysicsTicksCount); |
| 3909 |
|
| 3910 |
{ To avoid the spiral of death, we ignore some accumulated time |
| 3911 |
(we will not account for this time in the physics simulation, |
| 3912 |
so physics simulation may be slower than time perceived by user, |
| 3913 |
than non-physics animations etc.). |
| 3914 |
An alternative approach would be to prolong the simulation step |
| 3915 |
sometimes, but this could lead to unreliable collision detection. |
| 3916 |
See description of this in |
| 3917 |
https://github.com/castle-engine/castle-engine/pull/144#issuecomment-562850820 } |
| 3918 |
if (TimeAccumulator >= PhysicsProperties.FPhysicsTimeStep) and (PhysicsProperties.MaxPhysicsTicksPerUpdate <> 0) and |
| 3919 |
(PhysicsTicksCount >= PhysicsProperties.MaxPhysicsTicksPerUpdate) then |
| 3920 |
begin |
| 3921 |
{$ifdef CASTLE_LOG_PHYSICS_DROPS_FRAMES} |
| 3922 |
OldTimeAccumulator := TimeAccumulator; |
| 3923 |
{$endif} |
| 3924 |
|
| 3925 |
TimeAccumulator := TimeAccumulator - (PhysicsProperties.FPhysicsTimeStep * Floor(TimeAccumulator / PhysicsProperties.FPhysicsTimeStep)); |
| 3926 |
|
| 3927 |
// This log is valid, but too spammy now. |
| 3928 |
{$ifdef CASTLE_LOG_PHYSICS_DROPS_FRAMES} |
| 3929 |
WritelnLog('Max physics ticks in TCastleAbstractRootTransform.Update() exceeded (' |
| 3930 |
+ IntToStr(PhysicsTicksCount) + '). TimeAccumulator reduced from ' |
| 3931 |
+ FloatToStrDot(OldTimeAccumulator) + ' to ' + FloatToStrDot(TimeAccumulator)); |
| 3932 |
{$endif} |
| 3933 |
|
| 3934 |
break; |
| 3935 |
end; |
| 3936 |
end; |
| 3937 |
|
| 3938 |
{ One can wonder why we do interpolate below between |
| 3939 |
- previous-to-last calculated physics state |
| 3940 |
- and the last calculated physics state |
| 3941 |
|
| 3942 |
It seems that we should interpolate instead between |
| 3943 |
- the last calculated physics state |
| 3944 |
- and the "future" physics state, so we should make one more |
| 3945 |
"FKraftEngine.Step" call (and remember to make one less |
| 3946 |
"FKraftEngine.Step" call in the next loop run). |
| 3947 |
|
| 3948 |
This contains an explanation: |
| 3949 |
http://web.archive.org/web/20160205035208/http://gafferongames.com/game-physics/fix-your-timestep/ |
| 3950 |
|
| 3951 |
""" |
| 3952 |
You’re actually delaying the simulation by one frame |
| 3953 |
and then doing the interpolation to ensure smoothness. |
| 3954 |
""" |
| 3955 |
|
| 3956 |
(The original https://gafferongames.com/post/fix_your_timestep/ no longer |
| 3957 |
has comments.) |
| 3958 |
} |
| 3959 |
FKraftEngine.InterpolateWorldTransforms(TimeAccumulator / PhysicsProperties.FPhysicsTimeStep); |
| 3960 |
end; |
| 3961 |
FrameProfiler.Stop(fmUpdatePhysics); |
| 3962 |
end; |
| 3963 |
|
| 3964 |
{ call inherited at the end, |
| 3965 |
to update transformation of all items in their TCastleRigidBody.Update |
| 3966 |
called from TCastleTransform.Update } |
| 3967 |
inherited; |
| 3968 |
end; |
| 3969 |
|
| 3970 |
function TCastleAbstractRootTransform.PhysicsRayCast( |
| 3971 |
const RayOrigin, RayDirection: TVector3; |
| 3972 |
const MaxDistance: Single; const IgnoreBody: TCastleRigidBody): TPhysicsRayCastResult; |
| 3973 |
|
| 3974 |
procedure Core; |
| 3975 |
var |
| 3976 |
KraftShape: TKraftShape; |
| 3977 |
KraftDistance: TKraftScalar; |
| 3978 |
KraftPoint: TKraftVector3; |
| 3979 |
KraftNormal: TKraftVector3; |
| 3980 |
begin |
| 3981 |
{ make sure everything is zero when no hit } |
| 3982 |
FillChar(Result, SizeOf(Result), 0); |
| 3983 |
|
| 3984 |
{ Note: In Kraft, the distance parameters are called "time" |
| 3985 |
(MaxTime, Time instead of more natural MaxDistance, Distance). |
| 3986 |
But all research shows that it is actually "distance" and that is also how |
| 3987 |
other physics engines call it. |
| 3988 |
|
| 3989 |
TODO: Check time does not depend on physics frequency? } |
| 3990 |
|
| 3991 |
if FKraftEngine.RayCast( |
| 3992 |
// inputs |
| 3993 |
VectorToKraft(RayOrigin), VectorToKraft(RayDirection), MaxDistance, |
| 3994 |
// outputs |
| 3995 |
KraftShape, KraftDistance, KraftPoint, KraftNormal) then |
| 3996 |
begin |
| 3997 |
Result.Hit := true; |
| 3998 |
Result.Transform := TCastleRigidBody(KraftShape.RigidBody.UserData).FTransform; |
| 3999 |
Result.Point := VectorFromKraft(KraftPoint); |
| 4000 |
Result.Normal := VectorFromKraft(KraftNormal); |
| 4001 |
Result.Distance := KraftDistance; |
| 4002 |
end; |
| 4003 |
end; |
| 4004 |
|
| 4005 |
var |
| 4006 |
OldIgnoreShapeFlags: TKraftShapeFlags; |
| 4007 |
IgnoreShape: TKraftShape; |
| 4008 |
begin |
| 4009 |
// calculate IgnoreShape |
| 4010 |
if IgnoreBody <> nil then |
| 4011 |
IgnoreShape := IgnoreBody.GetKraftShape |
| 4012 |
else |
| 4013 |
IgnoreShape := nil; |
| 4014 |
|
| 4015 |
// protect IgnoreShape from being hit, use Core |
| 4016 |
if IgnoreShape <> nil then |
| 4017 |
begin |
| 4018 |
OldIgnoreShapeFlags := IgnoreShape.Flags; |
| 4019 |
try |
| 4020 |
// We use ksfRayCastable flag to not hit the IgnoreBody |
| 4021 |
IgnoreShape.Flags := IgnoreShape.Flags - [ksfRayCastable]; |
| 4022 |
Core; |
| 4023 |
finally |
| 4024 |
IgnoreShape.Flags := OldIgnoreShapeFlags; |
| 4025 |
end; |
| 4026 |
end else |
| 4027 |
Core; |
| 4028 |
end; |
| 4029 |
|
| 4030 |
{$endif read_implementation} |