summaryrefslogtreecommitdiff
path: root/src/KingSystem/Physics/System/physRayCast.cpp
blob: 34a039268744ea6b9909d329d95b6e7da9ee7336 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
#include "KingSystem/Physics/System/physRayCast.h"
#include <Havok/Common/Base/hkBase.h>
#include <Havok/Physics2012/Collide/Agent/Collidable/hkpCdBody.h>
#include <Havok/Physics2012/Collide/Agent/Collidable/hkpCollidable.h>
#include <Havok/Physics2012/Collide/Query/CastUtil/hkpWorldRayCastInput.h>
#include <Havok/Physics2012/Collide/Query/CastUtil/hkpWorldRayCastOutput.h>
#include <Havok/Physics2012/Collide/Query/hkpRayHitCollector.h>
#include <Havok/Physics2012/Collide/Shape/Convex/Triangle/hkpTriangleShape.h>
#include <Havok/Physics2012/Collide/Shape/Query/hkpShapeRayCastInput.h>
#include <Havok/Physics2012/Dynamics/Entity/hkpRigidBody.h>
#include <Havok/Physics2012/Dynamics/World/hkpWorld.h>
#include <Havok/Physics2012/Internal/Collide/StaticCompound/hkpStaticCompoundShape.h>
#include <prim/seadScopeGuard.h>
#include "KingSystem/Physics/RigidBody/physRigidBody.h"
#include "KingSystem/Physics/System/physEntityContactListener.h"
#include "KingSystem/Physics/System/physGroupFilter.h"
#include "KingSystem/Physics/System/physSystem.h"
#include "KingSystem/Physics/physConversions.h"
#include "KingSystem/Physics/physLayerMaskBuilder.h"

namespace ksys::phys {

class RayHitCollector : public hkpRayHitCollector {
public:
    HK_DECLARE_CLASS_ALLOCATOR(RayHitCollector)

    RayHitCollector(hkpWorldRayCastOutput* output, ContactLayerType layer_type,
                    const sead::PtrArray<SystemGroupHandler>* ignored_groups,
                    GroundHit ignored_ground_hit)
        : mOutput(output), mLayerType(layer_type), mIgnoredGroups(ignored_groups),
          mIgnoredGroundHit(ignored_ground_hit) {}

    ~RayHitCollector() override;

    void addRayHit(const hkpCdBody& cdBody, const hkpShapeRayCastCollectorOutput& hitInfo) override;

protected:
    bool isIgnoredGroup(const hkpCdBody& cdBody,
                        const hkpShapeRayCastCollectorOutput& hitInfo) const;

    bool isIgnoredGroundHit(const hkpCdBody& cdBody,
                            const hkpShapeRayCastCollectorOutput& hitInfo) const;

    hkpWorldRayCastOutput* mOutput;
    ContactLayerType mLayerType;
    const sead::PtrArray<SystemGroupHandler>* mIgnoredGroups;
    GroundHit mIgnoredGroundHit;
};

class NormalCheckingRayHitCollector : public RayHitCollector {
public:
    HK_DECLARE_CLASS_ALLOCATOR(NormalCheckingRayHitCollector)

    NormalCheckingRayHitCollector(hkpWorldRayCastOutput* output, const sead::Vector3f& ray_line,
                                  RayCast::NormalCheckingMode mode, ContactLayerType layer_type,
                                  const sead::PtrArray<SystemGroupHandler>* ignored_groups,
                                  GroundHit ignored_ground_hit)
        : RayHitCollector(output, layer_type, ignored_groups, ignored_ground_hit),
          mRayLine(&ray_line), mMode(mode) {}

    ~NormalCheckingRayHitCollector() override;

    void addRayHit(const hkpCdBody& cdBody, const hkpShapeRayCastCollectorOutput& hitInfo) override;

    bool checkNormal(const hkpCdBody& cdBody, const hkpShapeRayCastCollectorOutput& hitInfo) const;

private:
    const sead::Vector3f* mRayLine;
    RayCast::NormalCheckingMode mMode;
};

RayCast::RayCast(SystemGroupHandler* group_handler, GroundHit ground_hit)
    : mGroupHandler(group_handler), mGroundHit(ground_hit) {
    reset();
}

RayCast::~RayCast() = default;

// NON_MATCHING: reorderings
void RayCast::reset() {
    mTo = sead::Vector3f::zero;
    mFrom = sead::Vector3f::zero;
    mLayerMasks = {};
    mIgnoredGroups.clear();

    resetCastResult();
}

void RayCast::resetCastResult() {
    static_cast<void>(_98.load());

    mHasHit = false;
    mHitNormal = sead::Vector3f::zero;
    mHitFraction = -1.0;
    mHitCollidable = {};
    mHitShapeKey = {};
    mHasHitSpecifiedRigidBody = false;
    _58 = {};
    _60 = {};
    _70 = {};
}

static bool isLayerValid(ContactLayer layer, ContactLayerType type) {
    if (type == ContactLayerType::Entity) {
        if (layer > ContactLayer::EntityHitOnlyGround)
            return false;
    } else {
        if (layer > ContactLayer::SensorNoHit)
            return false;
    }

    return true;
}

void RayCast::enableLayer(ContactLayer layer) {
    auto type = getContactLayerType(layer);
    if (!isLayerValid(layer, type))
        return;

    const auto mask = makeContactLayerMask(layer);
    getLayerMask(type).set(mask);
}

void RayCast::disableLayer(ContactLayer layer) {
    auto type = getContactLayerType(layer);
    if (!isLayerValid(layer, type))
        return;

    getLayerMask(type).resetBit(getContactLayerBaseRelativeValue(layer));
}

void RayCast::setLayers(const LayerMaskBuilder& builder) {
    for (int i = 0; i < NumContactLayerTypes; ++i)
        mLayerMasks[i] = builder.getMasks()[i].layers;
}

bool RayCast::isLayerEnabled(ContactLayer layer) const {
    auto type = getContactLayerType(layer);
    if (!isLayerValid(layer, type))
        return false;

    return getLayerMask(type).isOnBit(getContactLayerBaseRelativeValue(layer));
}

void RayCast::setGroundHit(GroundHit ground_hit) {
    mGroundHit = ground_hit;
}

GroundHit RayCast::getGroundHit() const {
    return mGroundHit;
}

void RayCast::setIgnoredGroundHit(GroundHit ground_hit) {
    mIgnoredGroundHit = ground_hit;
}

void RayCast::set9A(bool value) {
    _9a = value;
}

void RayCast::setStart(const sead::Vector3f& start) {
    mFrom = start;
}

void RayCast::setEnd(const sead::Vector3f& end) {
    mTo = end;
}

void RayCast::setStartAndEnd(const sead::Vector3f& start, const sead::Vector3f& end) {
    setStart(start);
    setEnd(end);
}

void RayCast::setStartAndDisplacement(const sead::Vector3f& start,
                                      const sead::Vector3f& displacement) {
    setStart(start);
    setEnd(start + displacement);
}

void RayCast::setStartAndDisplacementScaled(const sead::Vector3f& start,
                                            const sead::Vector3f& displacement,
                                            float displacement_scale) {
    setStart(start);
    setEnd(start + displacement * displacement_scale);
}

bool RayCast::addIgnoredGroup(SystemGroupHandler* group_handler) {
    if (mIgnoredGroups.size() == mIgnoredGroups.capacity() || group_handler == nullptr)
        return false;

    mIgnoredGroups.pushBack(group_handler);
    return true;
}

void RayCast::setRigidBody(RigidBody* body) {
    if (_70 != 1)
        mRigidBody = body;
}

void RayCast::fillCastInput(hkpWorldRayCastInput& input, ContactLayerType layer_type) {
    const u32 layer_mask = getLayerMask(layer_type);
    input.m_enableShapeCollectionFilter = true;
    input.m_filterInfo = getFilterInfo(layer_type, layer_mask);
    input.m_from = toHkVec4(mFrom);
    input.m_to = toHkVec4(mTo);
}

void RayCast::fillCastInput(hkpShapeRayCastInput& input, ContactLayerType layer_type) {
    input.m_filterInfo = getFilterInfo(layer_type, getLayerMask(layer_type));
}

u32 RayCast::getFilterInfo(ContactLayerType layer_type, u32 layer_mask) const {
    if (mGroupHandler != nullptr) {
        return mGroupHandler->makeQueryCollisionMask(layer_mask, mGroundHit, _9a);
    } else {
        auto* filter = System::instance()->getGroupFilter(layer_type);
        auto info = filter->makeQueryCollisionMask(layer_mask, mGroundHit, _9a);
#ifdef MATCHING_HACK_NX_CLANG
        asm("");
#endif
        return info;
    }
}

void RayCast::preCast() {
    if (_70 == 1)
        resetCastResult();
    _98 = true;
}

bool RayCast::postCast(const hkpWorldRayCastOutput& output) {
    mHasHit = output.hasHit();
    if (mHasHit) {
        updateHitInformation(output);
        getActorInfoMaybe(output);
    }
    _98 = false;
    _70 = 1;
    return mHasHit;
}

void RayCast::updateHitInformation(const hkpWorldRayCastOutput& output) {
    storeToVec3(&mHitNormal, output.m_normal);
    mHitFraction = output.m_hitFraction;
    mHitCollidable = output.m_rootCollidable;
    mHitShapeKey = output.m_shapeKeys[0];

    auto* hit_body = getRigidBody(*mHitCollidable);
    if (hit_body) {
        if (mRigidBody != nullptr && hit_body == mRigidBody)
            mHasHitSpecifiedRigidBody = true;

        onRigidBodyHit(hit_body);
        if (mRigidBodyHitCallback)
            mRigidBodyHitCallback->invoke(hit_body);
    }
}

bool RayCast::worldRayCast(ContactLayerType layer_type) {
    hkpWorldRayCastOutput output;
    preCast();
    worldRayCastImpl(&output, layer_type);
    return postCast(output);
}

void RayCast::worldRayCastImpl(hkpWorldRayCastOutput* output, ContactLayerType layer_type) {
    hkpWorldRayCastInput input;
    fillCastInput(input, layer_type);

    System::instance()->lockWorld(layer_type, "raycast", 0, OnlyLockIfNeeded::Yes);
    auto world_guard = sead::makeScopeGuard(
        [&] { System::instance()->unlockWorld(layer_type, "raycast", 0, OnlyLockIfNeeded::Yes); });

    if (mNormalCheckingMode == NormalCheckingMode::DoNotCheck) {
        if (mIgnoredGroups.size() > 0 || int(mIgnoredGroundHit) != GroundHit::Ignore) {
            RayHitCollector collector{output, layer_type,
                                      mIgnoredGroups.size() > 0 ? &mIgnoredGroups : nullptr,
                                      mIgnoredGroundHit};
            System::instance()->getHavokWorld(layer_type)->castRay(input, collector);
        } else {
            System::instance()->getHavokWorld(layer_type)->castRay(input, *output);
        }

    } else {
        sead::Vector3f ray_line = mTo - mFrom;
        ray_line.normalize();

        auto* groups = mIgnoredGroups.size() > 0 ? &mIgnoredGroups : nullptr;
        NormalCheckingRayHitCollector collector(output, ray_line, mNormalCheckingMode, layer_type,
                                                groups, mIgnoredGroundHit);
        System::instance()->getHavokWorld(layer_type)->castRay(input, collector);
    }
}

bool RayCast::shapeRayCast(RigidBody* rigid_body) {
    hkpWorldRayCastOutput output;
    preCast();
    shapeRayCastImpl(&output, rigid_body);
    return postCast(output);
}

void RayCast::shapeRayCastImpl(hkpWorldRayCastOutput* output, RigidBody* body) {
    hkpShapeRayCastInput input;
    auto layer_type = body->getLayerType();
    fillCastInput(input, layer_type);

    sead::Matrix34f transform;
    body->getTransform(&transform);
    transform.invert();
    const auto from = transform * mFrom;
    const auto to = transform * mTo;
    input.m_from = toHkVec4(from);
    input.m_to = toHkVec4(to);

    System::instance()->incrementWorldUnkCounter(ContactLayerType::Entity);
    auto world_guard = sead::makeScopeGuard(
        [&] { System::instance()->decrementWorldUnkCounter(ContactLayerType::Entity); });

    auto* collidable = body->getHkBody()->getCollidable();

    if (mNormalCheckingMode == NormalCheckingMode::DoNotCheck) {
        if (mIgnoredGroups.size() > 0 || int(mIgnoredGroundHit) != GroundHit::Ignore) {
            RayHitCollector collector{output, layer_type,
                                      mIgnoredGroups.size() > 0 ? &mIgnoredGroups : nullptr,
                                      mIgnoredGroundHit};
            collidable->getShape()->castRayWithCollector(input, *collidable, collector);
        } else {
            collidable->getShape()->castRay(input, *output);
        }

    } else {
        sead::Vector3f ray_line = mTo - mFrom;
        ray_line.normalize();

        auto* groups = mIgnoredGroups.size() > 0 ? &mIgnoredGroups : nullptr;
        NormalCheckingRayHitCollector collector(output, ray_line, mNormalCheckingMode, layer_type,
                                                groups, mIgnoredGroundHit);
        collidable->getShape()->castRayWithCollector(input, *collidable, collector);
    }
}

void RayCast::getHitPosition(sead::Vector3f* position) const {
    *position = ((1 - mHitFraction) * mFrom) + (mHitFraction * mTo);
}

void RayCast::getHitNormal(sead::Vector3f* normal) const {
    *normal = mHitNormal;
}

RayHitCollector::~RayHitCollector() = default;

bool RayHitCollector::isIgnoredGroup(const hkpCdBody& cdBody,
                                     const hkpShapeRayCastCollectorOutput& hitInfo) const {
    if (mIgnoredGroups == nullptr ||
        cdBody.getRootCollidable()->getShape()->getType() == hkcdShapeType::STATIC_COMPOUND) {
        return false;
    }

    auto filter_info = cdBody.getRootCollidable()->getCollisionFilterInfo();
    auto* group_filter = System::instance()->getGroupFilter(mLayerType);
    auto group_idx = int(group_filter->getCollisionFilterInfoGroupHandlerIdx(filter_info));

    if (group_idx != 0) {
        for (int i = 0; i < mIgnoredGroups->size(); ++i) {
            if ((*mIgnoredGroups)[i]->getIndex() == group_idx)
                return true;
        }
    }

    return false;
}

bool RayHitCollector::isIgnoredGroundHit(const hkpCdBody& cdBody,
                                         const hkpShapeRayCastCollectorOutput& hitInfo) const {
    if (mIgnoredGroundHit == GroundHit::Ignore ||
        cdBody.getRootCollidable()->getShape()->getType() == hkcdShapeType::STATIC_COMPOUND ||
        mLayerType != ContactLayerType::Entity) {
        return false;
    }

    auto filter_info = cdBody.getRootCollidable()->getCollisionFilterInfo();
    auto body_ground_hit = EntityCollisionMask(filter_info).getGroundHit();
    if (int(mIgnoredGroundHit) == body_ground_hit)
        return true;

    return false;
}

// NON_MATCHING: group_idx check should be a ccmp
void RayHitCollector::addRayHit(const hkpCdBody& cdBody,
                                const hkpShapeRayCastCollectorOutput& hitInfo) {
    bool closer = hitInfo.m_hitFraction < mOutput->m_hitFraction;
    if (!closer)
        return;

    if (isIgnoredGroup(cdBody, hitInfo))
        return;

    if (isIgnoredGroundHit(cdBody, hitInfo))
        return;

    if (System::instance()->getEntityContactListenerField91() &&
        mLayerType == ContactLayerType::Entity &&
        EntityContactListener::isObjectOrGroundOrNPCOrTree(cdBody)) {
        // XXX: Similar checks show up in various other collectors. Can this be refactored?
        return;
    }

    *static_cast<hkpShapeRayCastCollectorOutput*>(mOutput) = hitInfo;
    mOutput->m_rootCollidable = cdBody.getRootCollidable();
    shapeKeysFromCdBody(mOutput->m_shapeKeys, hkpShapeRayCastOutput::MAX_HIERARCHY_DEPTH, cdBody);
    m_earlyOutHitFraction = hitInfo.m_hitFraction;
}

NormalCheckingRayHitCollector::~NormalCheckingRayHitCollector() = default;

void NormalCheckingRayHitCollector::addRayHit(const hkpCdBody& cdBody,
                                              const hkpShapeRayCastCollectorOutput& hitInfo) {
    bool closer = hitInfo.m_hitFraction < mOutput->m_hitFraction;
    if (!closer)
        return;

    if (isIgnoredGroup(cdBody, hitInfo))
        return;

    if (isIgnoredGroundHit(cdBody, hitInfo))
        return;

    if (!checkNormal(cdBody, hitInfo))
        return;

    if (System::instance()->getEntityContactListenerField91() &&
        mLayerType == ContactLayerType::Entity &&
        EntityContactListener::isObjectOrGroundOrNPCOrTree(cdBody)) {
        return;
    }

    *static_cast<hkpShapeRayCastCollectorOutput*>(mOutput) = hitInfo;
    mOutput->m_rootCollidable = cdBody.getRootCollidable();
    shapeKeysFromCdBody(mOutput->m_shapeKeys, hkpShapeRayCastOutput::MAX_HIERARCHY_DEPTH, cdBody);
    m_earlyOutHitFraction = hitInfo.m_hitFraction;
}

template <bool Invert>
static bool checkDot(RayCast::NormalCheckingMode mode, float dot) {
    if (mode == RayCast::NormalCheckingMode::_0) {
        if constexpr (Invert)
            return !(dot < 0);
        else
            return (dot < 0);
    } else {
        if constexpr (Invert)
            return !(dot > 0);
        else
            return (dot > 0);
    }
}

bool NormalCheckingRayHitCollector::checkNormal(
    const hkpCdBody& cdBody, const hkpShapeRayCastCollectorOutput& hitInfo) const {
    if (cdBody.getShape()->getType() != hkcdShapeType::TRIANGLE)
        return checkDot<false>(mMode, mRayLine->dot(toVec3(hitInfo.m_normal)));

    auto* triangle = static_cast<const hkpTriangleShape*>(cdBody.getShape());

    auto vertexA = triangle->getVertex<0>();
    auto vertexB = triangle->getVertex<1>();
    auto vertexC = triangle->getVertex<2>();

    hkVector4f BminusA;
    BminusA.setSub(vertexB, vertexA);

    hkVector4f CminusA;
    CminusA.setSub(vertexC, vertexA);

    hkVector4f triangle_line;
    triangle_line.setCross(BminusA, CminusA);
    triangle_line.normalize<3>();

    const auto body_rotation = cdBody.getRootCollidable()->getTransform().getRotation();

    hkRotationf rotation = body_rotation;

    if (cdBody.getRootCollidable()->getShape()->getType() == hkcdShapeType::STATIC_COMPOUND) {
        auto* sc =
            static_cast<const hkpStaticCompoundShape*>(cdBody.getRootCollidable()->getShape());

        int instance_id;
        hkpShapeKey child_key;
        sc->decomposeShapeKey(cdBody.getShapeKey(), instance_id, child_key);

        hkRotationf shape_rotation;
        shape_rotation.set(sc->getInstances()[instance_id].getTransform().getRotation());
        rotation.mul(shape_rotation);
    }

    hkVector4f rotated_normal;
    rotated_normal.setRotatedDir(rotation, hitInfo.m_normal);

    return checkDot<true>(mMode, triangle_line.dot<3>(rotated_normal));
}

}  // namespace ksys::phys