File size: 4,386 Bytes
80f0adb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Runtime monkey-patch that adds `RigidEntity.detect_collision_parallel` and
`RigidLink.detect_collision` to upstream Genesis.

The methods are pure-Python — they only read fields already exposed by the
upstream `RigidEntity` / `RigidLink` / collider state — so we can attach them
at runtime instead of forking Genesis.

IMPORTANT: `apply()` must be called AFTER `gs.init()`. Importing
`genesis.engine.entities.rigid_entity.rigid_entity` before `gs.init()` raises
`Genesis hasn't been initialized.` from `genesis.utils.array_class`, so all
genesis-internal imports are deferred until inside `apply()`.

Usage:

    import genesis as gs
    import genesis_patch
    gs.init(...)
    genesis_patch.apply()
    # now RigidEntity.detect_collision_parallel is available
"""

import numpy as np


_APPLIED = False


def apply():
    """Install detect_collision_parallel / detect_collision on Genesis classes.

    Idempotent. Must be called after `gs.init()`.
    """
    global _APPLIED
    if _APPLIED:
        return

    import genesis as gs
    from genesis.engine.entities.rigid_entity.rigid_entity import RigidEntity
    from genesis.engine.entities.rigid_entity.rigid_link import RigidLink

    @gs.assert_built
    def detect_collision_parallel(
        self,
        with_entity=None,
        exclude_self_contact=False,
        envs_idx=None,
        *,
        unsafe=False,
    ):
        """GPU-parallel collision query against the current contact buffers.

        Parameters
        ----------
        with_entity : Entity, optional
            If given, only count contacts between `self` and this entity.
        exclude_self_contact : bool
            Ignore self-self contacts (only when `with_entity is None`).
        envs_idx : list[int], optional
            Indices of environments to report. Defaults to all envs.
        unsafe : bool
            If False (default), re-runs collision detection. Set True when
            buffers are already current.

        Returns
        -------
        numpy.ndarray
            bool array, one entry per requested env.
        """
        if not unsafe:
            self.solver.collider.clear()
            self.solver.collider.detection()

        n_collision = self.solver.collider._collider_state.n_contacts.to_numpy()
        geom_A = self.solver.collider._collider_state.contact_data.geom_a.to_numpy()
        geom_B = self.solver.collider._collider_state.contact_data.geom_b.to_numpy()

        n_collision = np.asarray(n_collision).reshape(-1)  # [B]
        geom_A = np.asarray(geom_A)                        # [max_contacts, B]
        geom_B = np.asarray(geom_B)                        # [max_contacts, B]
        max_contacts, B = geom_A.shape

        if envs_idx is None:
            envs_idx = np.arange(B, dtype=int)
        else:
            envs_idx = np.asarray(envs_idx, dtype=int)

        valid_rows = (np.arange(max_contacts)[:, None] < n_collision[None, :])

        selfA = (geom_A >= self.geom_start) & (geom_A < self.geom_end)
        selfB = (geom_B >= self.geom_start) & (geom_B < self.geom_end)

        if with_entity is not None:
            otherA = (geom_A >= with_entity.geom_start) & (geom_A < with_entity.geom_end)
            otherB = (geom_B >= with_entity.geom_start) & (geom_B < with_entity.geom_end)
            hits = ((selfA & otherB) | (selfB & otherA)) & valid_rows
        else:
            hits = (selfA | selfB) & valid_rows
            if exclude_self_contact:
                hits &= ~(selfA & selfB)

        collided = np.any(hits, axis=0)  # [B]
        return collided[envs_idx]

    @gs.assert_built
    def link_detect_collision(self, env_idx=0):
        """Single-env collision query for one rigid link. Re-detects in real
        time (does not rely on `scene.step()`)."""
        all_collision_pairs = self._solver.detect_collision(env_idx)
        collision_pairs = all_collision_pairs[
            np.logical_and(
                all_collision_pairs >= self.geom_start,
                all_collision_pairs < self.geom_end,
            ).any(axis=1)
        ]
        return collision_pairs

    if not hasattr(RigidEntity, "detect_collision_parallel"):
        RigidEntity.detect_collision_parallel = detect_collision_parallel
    if not hasattr(RigidLink, "detect_collision"):
        RigidLink.detect_collision = link_detect_collision

    _APPLIED = True