# All files / src/WebGL/core Raycaster.ts

7.97% Statements 11/138
0% Branches 0/42
0% Functions 0/7
8.87% Lines 11/124

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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

    18x

    18x

    18x

    18x
    18x
    18x
    18x
    18x
    18x
    18x

    18x

     import type { Camera } from '../Camera';
    import { Ray, Matrix4, Vector3 } from "../math";
    import { Sphere, Cylinder, Triangle } from "../shapes";

    const descSort = (a: { distance: number; }, b: { distance: number; }) => {
      return a.distance - b.distance;
    };

    const viewProjectionMatrix = new Matrix4();

    export class Raycaster {
      ray: Ray;
      near: number;
      far: number;
      precision = 0.0001;
      linePrecision = 0.2;
      constructor(origin: Vector3 | undefined, direction: Vector3 | undefined, far?: number, near?: number) {
        this.ray = new Ray(origin, direction);

        Iif (this.ray.direction.lengthSq() > 0) this.ray.direction.normalize();

        this.near = near || 0;
        this.far = far || Infinity;
      }

      set(origin: Vector3, direction: Vector3): void {
        this.ray.set(origin, direction);
      }

      setFromCamera(coords: { x: any; y: any; z: any; }, camera: Camera): void {
        if (!camera.ortho) {
          this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
          this.ray.direction.set(coords.x, coords.y, coords.z);

          camera.projectionMatrixInverse.getInverse(camera.projectionMatrix);
          viewProjectionMatrix.multiplyMatrices(
            camera.matrixWorld,
            camera.projectionMatrixInverse
          );
          this.ray.direction.applyProjection(viewProjectionMatrix);
          this.ray.direction.sub(this.ray.origin).normalize();
        } else {
          this.ray.origin
            .set(
              coords.x,
              coords.y,
              (camera.near + camera.far) / (camera.near - camera.far)
            )
            .unproject(camera);
          this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
        }
      }

      intersectObjects(group: any, objects: string | any[]) {
        var intersects: any[] = [];

        for (var i = 0, l = objects.length; i < l; i++)
          intersectObject(group, objects[i], this, intersects);

        intersects.sort(descSort);

        return intersects;
      }
    }

    // [-1, 1]
    const clamp = (x: number): number => {
      return Math.min(Math.max(x, -1), 1);
    };

    var sphere = new Sphere();
    var cylinder = new Cylinder();
    var triangle = new Triangle();
    var w_0 = new Vector3(); // for cylinders, cylinder.c1 - ray.origin
    var v1 = new Vector3(); // all purpose local vector
    var v2 = new Vector3();
    var v3 = new Vector3();
    //var facePlane = new $3Dmol.Plane();
    var matrixPosition = new Vector3();

    //object is a Sphere or (Bounding) Box
    export function intersectObject(group: { matrixWorld: Matrix4; }, clickable: { intersectionShape: any; boundingSphere: Sphere | undefined; }, raycaster: Raycaster, intersects: any[]) {
      matrixPosition.getPositionFromMatrix(group.matrixWorld);

      Iif (clickable.intersectionShape === undefined) return intersects;
      var intersectionShape = clickable.intersectionShape;
      var precision = raycaster.linePrecision;
      precision *= group.matrixWorld.getMaxScaleOnAxis();
      var precisionSq = precision * precision;

      //Check for intersection with clickable's bounding sphere, if it exists
      Iif (
        clickable.boundingSphere !== undefined &&
        clickable.boundingSphere instanceof Sphere
      ) {
        sphere.copy(clickable.boundingSphere);
        sphere.applyMatrix4(group.matrixWorld);
        Iif (!raycaster.ray.isIntersectionSphere(sphere)) {
          return intersects;
        }
      }

      //Iterate through intersection objects
      var i,
        il,
        norm,
        normProj,
        cylProj,
        rayProj,
        distance,
        closestDistSq,
        denom,
        discriminant,
        s,
        t,
        s_c,
        t_c;
      //triangle faces
      for (i = 0, il = intersectionShape.triangle.length; i < il; i++) {
        Iif (intersectionShape.triangle[i] instanceof Triangle) {
          triangle.copy(intersectionShape.triangle[i]);
          triangle.applyMatrix4(group.matrixWorld);

          norm = triangle.getNormal();

          normProj = raycaster.ray.direction.dot(norm);

          //face culling
          Iif (normProj >= 0) continue;

          w_0.subVectors(triangle.a, raycaster.ray.origin);

          distance = norm.dot(w_0) / normProj;

          Iif (distance < 0) continue;

          //intersects with plane, check if P inside triangle
          v1.copy(raycaster.ray.direction)
            .multiplyScalar(distance)
            .add(raycaster.ray.origin);
          v1.sub(triangle.a); // from pt a to intersection point P

          v2.copy(triangle.b).sub(triangle.a); // from pt a to b
          v3.copy(triangle.c).sub(triangle.a); // from pt a to c
          var b_dot_c = v2.dot(v3);
          var b_sq = v2.lengthSq();
          var c_sq = v3.lengthSq();

          // P = A + s(v2) + t(v3), inside trianle if 0 <= s, t <=1  and (s + t) <=0

          t =
            (b_sq * v1.dot(v3) - b_dot_c * v1.dot(v2)) /
            (b_sq * c_sq - b_dot_c * b_dot_c);

          Iif (t < 0 || t > 1) continue;

          s = (v1.dot(v2) - t * b_dot_c) / b_sq;

          if (s < 0 || s > 1 || s + t > 1) continue;
          else {
            intersects.push({ clickable: clickable, distance: distance });
          }
        }
      }
      //cylinders
      for (i = 0, il = intersectionShape.cylinder.length; i < il; i++) {
        Iif (intersectionShape.cylinder[i] instanceof Cylinder) {
          cylinder.copy(intersectionShape.cylinder[i]);
          cylinder.applyMatrix4(group.matrixWorld);

          w_0.subVectors(cylinder.c1, raycaster.ray.origin);

          cylProj = w_0.dot(cylinder.direction); // Dela
          rayProj = w_0.dot(raycaster.ray.direction); // Epsilon

          normProj = clamp(raycaster.ray.direction.dot(cylinder.direction)); // Beta

          denom = 1 - normProj * normProj;

          Iif (denom === 0.0) continue;

          s_c = (normProj * rayProj - cylProj) / denom;
          t_c = (rayProj - normProj * cylProj) / denom;

          v1.copy(cylinder.direction).multiplyScalar(s_c).add(cylinder.c1); // Q_c
          v2.copy(raycaster.ray.direction)
            .multiplyScalar(t_c)
            .add(raycaster.ray.origin); // P_c

          closestDistSq = v3.subVectors(v1, v2).lengthSq();
          var radiusSq = cylinder.radius * cylinder.radius;

          //Smoothing?
          //if (closestDistSq > radiusSq) radiusSq += precisionSq;

          // closest distance between ray and cylinder axis not greater than cylinder radius;
          // might intersect this cylinder between atom and bond midpoint
          Iif (closestDistSq <= radiusSq) {
            //Find points where ray intersects sides of cylinder
            discriminant =
              (normProj * cylProj - rayProj) * (normProj * cylProj - rayProj) -
              denom * (w_0.lengthSq() - cylProj * cylProj - radiusSq);

            // ray tangent to cylinder?
            if (discriminant <= 0) t = distance = Math.sqrt(closestDistSq);
            else
              t = distance =
                (rayProj - normProj * cylProj - Math.sqrt(discriminant)) / denom;

            //find closest intersection point; make sure it's between atom's position and cylinder midpoint

            s = normProj * t - cylProj;

            //does not intersect cylinder between atom and midpoint,
            // or intersects cylinder behind camera
            if (s < 0 || s * s > cylinder.lengthSq() || t < 0) continue;
            else intersects.push({ clickable: clickable, distance: distance });
          }
        }
      }
      //lines
      for (i = 0, il = intersectionShape.line.length; i < il; i += 2) {
        v1.copy(intersectionShape.line[i]);
        v1.applyMatrix4(group.matrixWorld);
        v2.copy(intersectionShape.line[i + 1]);
        v2.applyMatrix4(group.matrixWorld);

        v3.subVectors(v2, v1);
        var bondLengthSq = v3.lengthSq();
        v3.normalize();

        w_0.subVectors(v1, raycaster.ray.origin);

        var lineProj = w_0.dot(v3);
        rayProj = w_0.dot(raycaster.ray.direction);

        normProj = clamp(raycaster.ray.direction.dot(v3));

        denom = 1 - normProj * normProj;

        Iif (denom === 0.0) continue;

        s_c = (normProj * rayProj - lineProj) / denom;
        t_c = (rayProj - normProj * lineProj) / denom;

        v1.add(v3.multiplyScalar(s_c)); // Q_c
        v2.copy(raycaster.ray.direction)
          .multiplyScalar(t_c)
          .add(raycaster.ray.origin); // P_c

        closestDistSq = v3.subVectors(v2, v1).lengthSq();

        Iif (closestDistSq < precisionSq && s_c * s_c < bondLengthSq)
          intersects.push({ clickable: clickable, distance: t_c });
      }
      for (i = 0, il = intersectionShape.sphere.length; i < il; i++) {
        //sphere
        Iif (intersectionShape.sphere[i] instanceof Sphere) {
          sphere.copy(intersectionShape.sphere[i]);
          sphere.applyMatrix4(group.matrixWorld);

          Iif (raycaster.ray.isIntersectionSphere(sphere)) {
            v1.subVectors(sphere.center, raycaster.ray.origin);

            //distance from ray origin to point on the ray normal to sphere's center
            //must be less than sphere's radius (since ray intersects sphere)
            var distanceToCenter = v1.dot(raycaster.ray.direction);

            discriminant =
              distanceToCenter * distanceToCenter -
              (v1.lengthSq() - sphere.radius * sphere.radius);

            //Don't select if sphere center behind camera
            Iif (distanceToCenter < 0) return intersects;

            //ray tangent to sphere?
            if (discriminant <= 0) distance = distanceToCenter;
            //This is reversed if sphere is closer than ray origin.  Do we have
            //to worry about handling that case?
            else distance = distanceToCenter - Math.sqrt(discriminant);

            intersects.push({ clickable: clickable, distance: distance });
          }
        }
      }
      return intersects;
    };