details.h 82.2 KB
Newer Older
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
/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011-2014, Willow Garage, Inc.
 *  Copyright (c) 2014-2015, Open Source Robotics Foundation
 *  Copyright (c) 2018-2019, Centre National de la Recherche Scientifique
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Open Source Robotics Foundation nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 */
/** \author Jia Pan, Florent Lamiraux */

#ifndef HPP_FCL_SRC_NARROWPHASE_DETAILS_H
# define HPP_FCL_SRC_NARROWPHASE_DETAILS_H

41
#include <hpp/fcl/internal/traversal_node_setup.h>
42
43
#include <hpp/fcl/narrowphase/narrowphase.h>

44
45
namespace hpp
{
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
namespace fcl {
  namespace details
  {
    // Compute the point on a line segment that is the closest point on the
    // segment to to another point. The code is inspired by the explanation
    // given by Dan Sunday's page:
    //   http://geomalgorithms.com/a02-_lines.html
    static inline void lineSegmentPointClosestToPoint (const Vec3f &p, const Vec3f &s1, const Vec3f &s2, Vec3f &sp) {
      Vec3f v = s2 - s1;
      Vec3f w = p - s1;

      FCL_REAL c1 = w.dot(v);
      FCL_REAL c2 = v.dot(v);

      if (c1 <= 0) {
        sp = s1;
      } else if (c2 <= c1) {
        sp = s2;
      } else {
        FCL_REAL b = c1/c2;
        Vec3f Pb = s1 + v * b;
        sp = Pb;
      }
    }

    inline bool sphereCapsuleIntersect
      (const Sphere& s1, const Transform3f& tf1,
       const Capsule& s2, const Transform3f& tf2,
74
       FCL_REAL& distance, Vec3f* contact_points, Vec3f* normal_)
75
    {
76
77
      Vec3f pos1 (tf2.transform (Vec3f (0., 0.,  s2.halfLength))); // from distance function
      Vec3f pos2 (tf2.transform (Vec3f (0., 0., -s2.halfLength)));
78
79
80
81
82
83
84
85
      Vec3f s_c = tf1.getTranslation ();

      Vec3f segment_point;

      lineSegmentPointClosestToPoint (s_c, pos1, pos2, segment_point);
      Vec3f diff = s_c - segment_point;

      FCL_REAL diffN = diff.norm();
86
      distance = diffN - s1.radius - s2.radius;
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

      if (distance > 0)
        return false;

      // Vec3f normal (-diff.normalized());

      if (normal_)
        *normal_ = -diff / diffN;

      if (contact_points) {
        *contact_points = segment_point + diff * s2.radius;
      }

      return true;
    }

    inline bool sphereCapsuleDistance
      (const Sphere& s1, const Transform3f& tf1,
       const Capsule& s2, const Transform3f& tf2,
       FCL_REAL& dist, Vec3f& p1, Vec3f& p2, Vec3f& normal)
    {
108
109
      Vec3f pos1 (tf2.transform (Vec3f (0., 0.,  s2.halfLength)));
      Vec3f pos2 (tf2.transform (Vec3f (0., 0., -s2.halfLength)));
110
111
112
113
114
115
116
117
118
      Vec3f s_c = tf1.getTranslation ();

      Vec3f segment_point;

      lineSegmentPointClosestToPoint (s_c, pos1, pos2, segment_point);
      normal = segment_point - s_c;
      FCL_REAL norm (normal.norm());
      dist = norm - s1.radius - s2.radius;

Joseph Mirabel's avatar
Joseph Mirabel committed
119
      static const FCL_REAL eps (std::numeric_limits<FCL_REAL>::epsilon());
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
      if (norm > eps) {
        normal.normalize();
      } else {
        normal << 1,0,0;
      }
      p1 = s_c + normal * s1.radius;
      p2 = segment_point - normal * s2.radius;

      if(dist <= 0) {
        p1 = p2 = .5 * (p1+p2);
        return false;
      }
      return true;
    }

135
136
137
138
139
    inline bool sphereCylinderDistance
      (const Sphere& s1, const Transform3f& tf1,
       const Cylinder& s2, const Transform3f& tf2,
       FCL_REAL& dist, Vec3f& p1, Vec3f& p2, Vec3f& normal)
    {
Joseph Mirabel's avatar
Joseph Mirabel committed
140
      static const FCL_REAL eps (sqrt (std::numeric_limits <FCL_REAL>::epsilon ()));
141
142
      FCL_REAL r1 (s1.radius);
      FCL_REAL r2 (s2.radius);
143
      FCL_REAL lz2 (s2.halfLength);
144
145
146
147
148
149
150
      // boundaries of the cylinder axis
      Vec3f A (tf2.transform (Vec3f (0, 0, -lz2)));
      Vec3f B (tf2.transform (Vec3f (0, 0,  lz2)));
      // Position of the center of the sphere
      Vec3f S (tf1.getTranslation ());
      // axis of the cylinder
      Vec3f u (tf2.getRotation ().col (2));
LucileRemigy's avatar
LucileRemigy committed
151
      /// @todo a tiny performance improvement could be achieved using the abscissa with S as the origin
152
      assert ((B - A - (s2.halfLength * 2) * u).norm () < eps);
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
      Vec3f AS (S - A);
      // abscissa of S on cylinder axis with A as the origin
      FCL_REAL s (u.dot (AS));
      Vec3f P (A + s*u);
      Vec3f PS (S - P);
      FCL_REAL dPS = PS.norm ();
      // Normal to cylinder axis such that plane (A, u, v) contains sphere
      // center
      Vec3f v (0, 0, 0);
      if (dPS > eps) {
        // S is not on cylinder axis
        v = (1/dPS) * PS;
      }
      if (s <= 0) {
        if (dPS <= r2) {
          // closest point on cylinder is on cylinder disc basis
          dist = -s - r1; p1 = S + r1 * u; p2 = A + dPS * v; normal = u;
        } else {
          // closest point on cylinder is on cylinder circle basis
          p2 = A + r2 * v;
          Vec3f Sp2 (p2 - S);
          FCL_REAL dSp2 = Sp2.norm ();
          if (dSp2 > eps) {
            normal = (1/dSp2) * Sp2;
            p1 = S + r1 * normal;
            dist = dSp2 - r1;
            assert (fabs (dist) - (p1-p2).norm () < eps);
          } else {
            // Center of sphere is on cylinder boundary
            normal = .5 * (A + B) - p2; normal.normalize ();
            p1 = p2;
            dist = -r1;
          }
        }
187
      } else if (s <= (s2.halfLength * 2)) {
188
189
190
191
192
193
194
195
196
197
198
199
200
        // 0 < s <= s2.lz
        normal = -v;
        dist = dPS - r1 - r2;
        if (dPS <= r2) {
          // Sphere center is inside cylinder
          p1 = p2 = S;
        } else {
          p2 = P + r2*v; p1 = S - r1*v;
        }
      } else {
        // lz < s
        if (dPS <= r2) {
          // closest point on cylinder is on cylinder disc basis
201
          dist = s - (s2.halfLength * 2) - r1; p1 = S - r1 * u; p2 = B + dPS * v; normal = -u;
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
        } else {
          // closest point on cylinder is on cylinder circle basis
          p2 = B + r2 * v;
          Vec3f Sp2 (p2 - S);
          FCL_REAL dSp2 = Sp2.norm ();
          if (dSp2 > eps) {
            normal = (1/dSp2) * Sp2;
            p1 = S + r1 * normal;
            dist = dSp2 - r1;
            assert (fabs (dist) - (p1-p2).norm () < eps);
          } else {
            // Center of sphere is on cylinder boundary
            normal = .5 * (A + B) - p2; normal.normalize ();
            p1 = p2;
            dist = -r1;
          }
        }
      }
      if (dist < 0) {
        p1 = p2 = .5 *  (p1 + p2);
      }
      return (dist > 0);
    }

226
227
228
    inline bool sphereSphereIntersect
      (const Sphere& s1, const Transform3f& tf1,
       const Sphere& s2, const Transform3f& tf2,
229
       FCL_REAL& distance, Vec3f* contact_points, Vec3f* normal)
230
    {
231
      const Vec3f diff = tf2.getTranslation() - tf1.getTranslation();
232
      FCL_REAL len = diff.norm();
233
234
      distance = len - s1.radius - s2.radius;
      if(distance > 0)
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
        return false;

      // If the centers of two sphere are at the same position, the normal is (0, 0, 0).
      // Otherwise, normal is pointing from center of object 1 to center of object 2
      if(normal)
        {
          if(len > 0)
            *normal = diff / len;
          else
            *normal = diff;
        }

      if(contact_points)
        *contact_points = tf1.getTranslation() + diff * s1.radius / (s1.radius + s2.radius);

      return true;
    }


    inline bool sphereSphereDistance(const Sphere& s1, const Transform3f& tf1,
                                     const Sphere& s2, const Transform3f& tf2,
                                     FCL_REAL& dist, Vec3f& p1, Vec3f& p2,
                                     Vec3f& normal)
    {
259
260
      const Vec3f & o1 = tf1.getTranslation();
      const Vec3f & o2 = tf2.getTranslation();
261
262
263
264
265
      Vec3f diff = o1 - o2;
      FCL_REAL len = diff.norm();
      normal = -diff/len;
      dist = len - s1.radius - s2.radius;

Justin Carpentier's avatar
Justin Carpentier committed
266
267
      p1.noalias() = o1 + normal * s1.radius;
      p2.noalias() = o2 - normal * s2.radius;
268
269
270
271

      return (dist >=0);
    }

Lucile Remigy's avatar
Lucile Remigy committed
272
    /** @brief the minimum distance from a point to a line */
273
274
275
276
277
278
279
280
281
    inline FCL_REAL segmentSqrDistance
      (const Vec3f& from, const Vec3f& to,const Vec3f& p, Vec3f& nearest)
    {
      Vec3f diff = p - from;
      Vec3f v = to - from;
      FCL_REAL t = v.dot(diff);

      if(t > 0)
        {
282
          FCL_REAL dotVV = v.squaredNorm();
283
284
285
286
287
288
289
290
291
292
293
294
295
296
          if(t < dotVV)
            {
              t /= dotVV;
              diff -= v * t;
            }
          else
            {
              t = 1;
              diff -= v;
            }
        }
      else
        t = 0;

297
298
      nearest.noalias() = from + v * t;
      return diff.squaredNorm();
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
    }

    /// @brief Whether a point's projection is in a triangle
    inline bool projectInTriangle (const Vec3f& p1, const Vec3f& p2,
                                   const Vec3f& p3, const Vec3f& normal,
                                   const Vec3f& p)
    {
      Vec3f edge1(p2 - p1);
      Vec3f edge2(p3 - p2);
      Vec3f edge3(p1 - p3);

      Vec3f p1_to_p(p - p1);
      Vec3f p2_to_p(p - p2);
      Vec3f p3_to_p(p - p3);

      Vec3f edge1_normal(edge1.cross(normal));
      Vec3f edge2_normal(edge2.cross(normal));
      Vec3f edge3_normal(edge3.cross(normal));

      FCL_REAL r1, r2, r3;
      r1 = edge1_normal.dot(p1_to_p);
      r2 = edge2_normal.dot(p2_to_p);
      r3 = edge3_normal.dot(p3_to_p);
      if ( ( r1 > 0 && r2 > 0 && r3 > 0 ) ||
           ( r1 <= 0 && r2 <= 0 && r3 <= 0 ) )
        return true;
      return false;
    }

    // Intersection between sphere and triangle
    // Sphere is in position tf1, Triangle is expressed in global frame
    inline bool sphereTriangleIntersect
      (const Sphere& s, const Transform3f& tf1,
       const Vec3f& P1, const Vec3f& P2, const Vec3f& P3,
       FCL_REAL& distance, Vec3f& p1, Vec3f& p2,
       Vec3f& normal_)
    {
      Vec3f normal = (P2 - P1).cross(P3 - P1);
      normal.normalize();
      const Vec3f& center = tf1.getTranslation();
      const FCL_REAL& radius = s.radius;
      assert (radius >= 0);
      Vec3f p1_to_center = center - P1;
      FCL_REAL distance_from_plane = p1_to_center.dot(normal);
343
344
      Vec3f closest_point
        (Vec3f::Constant(std::numeric_limits<FCL_REAL>::quiet_NaN()));
345
      FCL_REAL min_distance_sqr, distance_sqr;
346

347
348
349
350
      if(distance_from_plane < 0) {
        distance_from_plane *= -1;
        normal *= -1;
      }
351

352
353
354
355
356
357
358
359
360
361
362
363
      if (projectInTriangle (P1, P2, P3, normal, center)) {
        closest_point = center - normal * distance_from_plane;
        min_distance_sqr = distance_from_plane;
      } else {
        // Compute distance to each each and take minimal distance
        Vec3f nearest_on_edge;
        min_distance_sqr = segmentSqrDistance(P1, P2, center, closest_point);

        distance_sqr = segmentSqrDistance(P2, P3, center, nearest_on_edge);
        if (distance_sqr < min_distance_sqr) {
          min_distance_sqr = distance_sqr;
          closest_point = nearest_on_edge;
364
        }
365
366
367
368
        distance_sqr = segmentSqrDistance(P3, P1, center, nearest_on_edge);
        if (distance_sqr < min_distance_sqr) {
          min_distance_sqr = distance_sqr;
          closest_point = nearest_on_edge;
369
        }
370
      }
371

372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
      if (min_distance_sqr < radius * radius) {
        // Collision
        normal_ = (closest_point - center).normalized ();
        p1 = p2 = closest_point;
        distance = sqrt (min_distance_sqr) - radius;
        assert (distance < 0);
        return true;
      } else {
        normal_ = (closest_point - center).normalized ();
        p1 = center + normal_ * radius;
        p2 = closest_point;
        distance = sqrt (min_distance_sqr) - radius;
        assert (distance >= 0);
        return false;
      }
    }
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636

    inline bool sphereTriangleDistance
      (const Sphere& sp, const Transform3f& tf,
       const Vec3f& P1, const Vec3f& P2, const Vec3f& P3, FCL_REAL* dist)
    {
      // from geometric tools, very different from the collision code.

      const Vec3f& center = tf.getTranslation();
      FCL_REAL radius = sp.radius;
      Vec3f diff = P1 - center;
      Vec3f edge0 = P2 - P1;
      Vec3f edge1 = P3 - P1;
      FCL_REAL a00 = edge0.squaredNorm();
      FCL_REAL a01 = edge0.dot(edge1);
      FCL_REAL a11 = edge1.squaredNorm();
      FCL_REAL b0 = diff.dot(edge0);
      FCL_REAL b1 = diff.dot(edge1);
      FCL_REAL c = diff.squaredNorm();
      FCL_REAL det = fabs(a00*a11 - a01*a01);
      FCL_REAL s = a01*b1 - a11*b0;
      FCL_REAL t = a01*b0 - a00*b1;

      FCL_REAL sqr_dist;

      if(s + t <= det)
        {
          if(s < 0)
            {
              if(t < 0)  // region 4
                {
                  if(b0 < 0)
                    {
                      t = 0;
                      if(-b0 >= a00)
                        {
                          s = 1;
                          sqr_dist = a00 + 2*b0 + c;
                        }
                      else
                        {
                          s = -b0/a00;
                          sqr_dist = b0*s + c;
                        }
                    }
                  else
                    {
                      s = 0;
                      if(b1 >= 0)
                        {
                          t = 0;
                          sqr_dist = c;
                        }
                      else if(-b1 >= a11)
                        {
                          t = 1;
                          sqr_dist = a11 + 2*b1 + c;
                        }
                      else
                        {
                          t = -b1/a11;
                          sqr_dist = b1*t + c;
                        }
                    }
                }
              else  // region 3
                {
                  s = 0;
                  if(b1 >= 0)
                    {
                      t = 0;
                      sqr_dist = c;
                    }
                  else if(-b1 >= a11)
                    {
                      t = 1;
                      sqr_dist = a11 + 2*b1 + c;
                    }
                  else
                    {
                      t = -b1/a11;
                      sqr_dist = b1*t + c;
                    }
                }
            }
          else if(t < 0)  // region 5
            {
              t = 0;
              if(b0 >= 0)
                {
                  s = 0;
                  sqr_dist = c;
                }
              else if(-b0 >= a00)
                {
                  s = 1;
                  sqr_dist = a00 + 2*b0 + c;
                }
              else
                {
                  s = -b0/a00;
                  sqr_dist = b0*s + c;
                }
            }
          else  // region 0
            {
              // minimum at interior point
              FCL_REAL inv_det = (1)/det;
              s *= inv_det;
              t *= inv_det;
              sqr_dist = s*(a00*s + a01*t + 2*b0) + t*(a01*s + a11*t + 2*b1) + c;
            }
        }
      else
        {
          FCL_REAL tmp0, tmp1, numer, denom;

          if(s < 0)  // region 2
            {
              tmp0 = a01 + b0;
              tmp1 = a11 + b1;
              if(tmp1 > tmp0)
                {
                  numer = tmp1 - tmp0;
                  denom = a00 - 2*a01 + a11;
                  if(numer >= denom)
                    {
                      s = 1;
                      t = 0;
                      sqr_dist = a00 + 2*b0 + c;
                    }
                  else
                    {
                      s = numer/denom;
                      t = 1 - s;
                      sqr_dist = s*(a00*s + a01*t + 2*b0) + t*(a01*s + a11*t + 2*b1) + c;
                    }
                }
              else
                {
                  s = 0;
                  if(tmp1 <= 0)
                    {
                      t = 1;
                      sqr_dist = a11 + 2*b1 + c;
                    }
                  else if(b1 >= 0)
                    {
                      t = 0;
                      sqr_dist = c;
                    }
                  else
                    {
                      t = -b1/a11;
                      sqr_dist = b1*t + c;
                    }
                }
            }
          else if(t < 0)  // region 6
            {
              tmp0 = a01 + b1;
              tmp1 = a00 + b0;
              if(tmp1 > tmp0)
                {
                  numer = tmp1 - tmp0;
                  denom = a00 - 2*a01 + a11;
                  if(numer >= denom)
                    {
                      t = 1;
                      s = 0;
                      sqr_dist = a11 + 2*b1 + c;
                    }
                  else
                    {
                      t = numer/denom;
                      s = 1 - t;
                      sqr_dist = s*(a00*s + a01*t + 2*b0) + t*(a01*s + a11*t + 2*b1) + c;
                    }
                }
              else
                {
                  t = 0;
                  if(tmp1 <= 0)
                    {
                      s = 1;
                      sqr_dist = a00 + 2*b0 + c;
                    }
                  else if(b0 >= 0)
                    {
                      s = 0;
                      sqr_dist = c;
                    }
                  else
                    {
                      s = -b0/a00;
                      sqr_dist = b0*s + c;
                    }
                }
            }
          else  // region 1
            {
              numer = a11 + b1 - a01 - b0;
              if(numer <= 0)
                {
                  s = 0;
                  t = 1;
                  sqr_dist = a11 + 2*b1 + c;
                }
              else
                {
                  denom = a00 - 2*a01 + a11;
                  if(numer >= denom)
                    {
                      s = 1;
                      t = 0;
                      sqr_dist = a00 + 2*b0 + c;
                    }
                  else
                    {
                      s = numer/denom;
                      t = 1 - s;
                      sqr_dist = s*(a00*s + a01*t + 2*b0) + t*(a01*s + a11*t + 2*b1) + c;
                    }
                }
            }
        }

      // Account for numerical round-off error.
      if(sqr_dist < 0)
        sqr_dist = 0;

      if(sqr_dist > radius * radius)
        {
          if(dist) *dist = std::sqrt(sqr_dist) - radius;
          return true;
        }
      else
        {
          if(dist) *dist = -1;
          return false;
        }
    }


    inline bool sphereTriangleDistance
      (const Sphere& sp, const Transform3f& tf, const Vec3f& P1,
       const Vec3f& P2, const Vec3f& P3, FCL_REAL* dist, Vec3f* p1, Vec3f* p2)
    {
      if(p1 || p2)
        {
637
          const Vec3f & o = tf.getTranslation();
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
          Project::ProjectResult result;
          result = Project::projectTriangle(P1, P2, P3, o);
          if(result.sqr_distance > sp.radius * sp.radius)
            {
              if(dist) *dist = std::sqrt(result.sqr_distance) - sp.radius;
              Vec3f project_p = P1 * result.parameterization[0] + P2 * result.parameterization[1] + P3 * result.parameterization[2];
              Vec3f dir = o - project_p;
              dir.normalize();
              if(p1) { *p1 = o - dir * sp.radius; }
              if(p2) *p2 = project_p;
              return true;
            }
          else
            return false;
        }
      else
        {
          return sphereTriangleDistance(sp, tf, P1, P2, P3, dist);
        }
    }


    inline bool sphereTriangleDistance
      (const Sphere& sp, const Transform3f& tf1, const Vec3f& P1,
       const Vec3f& P2, const Vec3f& P3, const Transform3f& tf2,
       FCL_REAL* dist, Vec3f* p1, Vec3f* p2)
    {
      bool res = details::sphereTriangleDistance(sp, tf1, tf2.transform(P1), tf2.transform(P2), tf2.transform(P3), dist, p1, p2);
      return res;
    }



    struct ContactPoint
    {
      Vec3f normal;
      Vec3f point;
      FCL_REAL depth;
    ContactPoint(const Vec3f& n, const Vec3f& p, FCL_REAL d) : normal(n), point(p), depth(d) {}
    };


    static inline void lineClosestApproach(const Vec3f& pa, const Vec3f& ua,
                                           const Vec3f& pb, const Vec3f& ub,
                                           FCL_REAL* alpha, FCL_REAL* beta)
    {
      Vec3f p = pb - pa;
      FCL_REAL uaub = ua.dot(ub);
      FCL_REAL q1 = ua.dot(p);
      FCL_REAL q2 = -ub.dot(p);
      FCL_REAL d = 1 - uaub * uaub;
      if(d <= (FCL_REAL)(0.0001f))
        {
          *alpha = 0;
          *beta = 0;
        }
      else
        {
          d = 1 / d;
          *alpha = (q1 + uaub * q2) * d;
          *beta = (uaub * q1 + q2) * d;
        }
    }

    // find all the intersection points between the 2D rectangle with vertices
    // at (+/-h[0],+/-h[1]) and the 2D quadrilateral with vertices (p[0],p[1]),
    // (p[2],p[3]),(p[4],p[5]),(p[6],p[7]).
    //
    // the intersection points are returned as x,y pairs in the 'ret' array.
    // the number of intersection points is returned by the function (this will
    // be in the range 0 to 8).
    static int intersectRectQuad2(FCL_REAL h[2], FCL_REAL p[8], FCL_REAL ret[16])
    {
      // q (and r) contain nq (and nr) coordinate points for the current (and
      // chopped) polygons
      int nq = 4, nr = 0;
      FCL_REAL buffer[16];
      FCL_REAL* q = p;
      FCL_REAL* r = ret;
      for(int dir = 0; dir <= 1; ++dir)
        {
          // direction notation: xy[0] = x axis, xy[1] = y axis
          for(int sign = -1; sign <= 1; sign += 2)
            {
              // chop q along the line xy[dir] = sign*h[dir]
              FCL_REAL* pq = q;
              FCL_REAL* pr = r;
              nr = 0;
              for(int i = nq; i > 0; --i)
                {
                  // go through all points in q and all lines between adjacent points
                  if(sign * pq[dir] < h[dir])
                    {
                      // this point is inside the chopping line
                      pr[0] = pq[0];
                      pr[1] = pq[1];
                      pr += 2;
                      nr++;
                      if(nr & 8)
                        {
                          q = r;
                          goto done;
                        }
                    }
                  FCL_REAL* nextq = (i > 1) ? pq+2 : q;
                  if((sign*pq[dir] < h[dir]) ^ (sign*nextq[dir] < h[dir]))
                    {
                      // this line crosses the chopping line
                      pr[1-dir] = pq[1-dir] + (nextq[1-dir]-pq[1-dir]) /
                        (nextq[dir]-pq[dir]) * (sign*h[dir]-pq[dir]);
                      pr[dir] = sign*h[dir];
                      pr += 2;
                      nr++;
                      if(nr & 8)
                        {
                          q = r;
                          goto done;
                        }
                    }
                  pq += 2;
                }
              q = r;
              r = (q == ret) ? buffer : ret;
              nq = nr;
            }
        }

    done:
      if(q != ret) memcpy(ret, q, nr*2*sizeof(FCL_REAL));
      return nr;
    }

    // given n points in the plane (array p, of size 2*n), generate m points that
    // best represent the whole set. the definition of 'best' here is not
    // predetermined - the idea is to select points that give good box-box
    // collision detection behavior. the chosen point indexes are returned in the
    // array iret (of size m). 'i0' is always the first entry in the array.
    // n must be in the range [1..8]. m must be in the range [1..n]. i0 must be
    // in the range [0..n-1].
    static inline void cullPoints2(int n, FCL_REAL p[], int m, int i0, int iret[])
    {
      // compute the centroid of the polygon in cx,cy
      FCL_REAL a, cx, cy, q;
      switch(n)
        {
        case 1:
          cx = p[0];
          cy = p[1];
          break;
        case 2:
          cx = 0.5 * (p[0] + p[2]);
          cy = 0.5 * (p[1] + p[3]);
          break;
        default:
          a = 0;
          cx = 0;
          cy = 0;
          for(int i = 0; i < n-1; ++i)
            {
              q = p[i*2]*p[i*2+3] - p[i*2+2]*p[i*2+1];
              a += q;
              cx += q*(p[i*2]+p[i*2+2]);
              cy += q*(p[i*2+1]+p[i*2+3]);
            }
          q = p[n*2-2]*p[1] - p[0]*p[n*2-1];
          if(std::abs(a+q) > std::numeric_limits<FCL_REAL>::epsilon())
            a = 1/(3*(a+q));
          else
            a= 1e18f;

          cx = a*(cx + q*(p[n*2-2]+p[0]));
          cy = a*(cy + q*(p[n*2-1]+p[1]));
        }


      // compute the angle of each point w.r.t. the centroid
      FCL_REAL A[8];
      for(int i = 0; i < n; ++i)
        A[i] = atan2(p[i*2+1]-cy,p[i*2]-cx);

      // search for points that have angles closest to A[i0] + i*(2*pi/m).
      int avail[8];
      for(int i = 0; i < n; ++i) avail[i] = 1;
      avail[i0] = 0;
      iret[0] = i0;
      iret++;
      const double pi = boost::math::constants::pi<FCL_REAL>();
      for(int j = 1; j < m; ++j)
        {
          a = j*(2*pi/m) + A[i0];
          if (a > pi) a -= 2*pi;
          FCL_REAL maxdiff= 1e9, diff;

          *iret = i0;	// iret is not allowed to keep this value, but it sometimes does, when diff=#QNAN0
          for(int i = 0; i < n; ++i)
            {
              if(avail[i])
                {
                  diff = std::abs(A[i]-a);
                  if(diff > pi) diff = 2*pi - diff;
                  if(diff < maxdiff)
                    {
                      maxdiff = diff;
                      *iret = i;
                    }
                }
            }
          avail[*iret] = 0;
          iret++;
        }
    }



852
853
    inline int boxBox2(const Vec3f& halfSide1, const Matrix3f& R1, const Vec3f& T1,
                       const Vec3f& halfSide2, const Matrix3f& R2, const Vec3f& T2,
854
855
856
857
858
859
860
861
862
863
864
865
                       Vec3f& normal, FCL_REAL* depth, int* return_code,
                       int maxc, std::vector<ContactPoint>& contacts)
    {
      const FCL_REAL fudge_factor = FCL_REAL(1.05);
      Vec3f normalC;
      FCL_REAL s, s2, l;
      int invert_normal, code;

      Vec3f p (T2 - T1); // get vector from centers of box 1 to box 2, relative to box 1
      Vec3f pp (R1.transpose() * p); // get pp = p relative to body 1

      // get side lengths / 2
866
867
      const Vec3f& A (halfSide1);
      const Vec3f& B (halfSide2);
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970

      // Rij is R1'*R2, i.e. the relative rotation between R1 and R2
      Matrix3f R (R1.transpose() * R2);
      Matrix3f Q (R.cwiseAbs());


      // for all 15 possible separating axes:
      //   * see if the axis separates the boxes. if so, return 0.
      //   * find the depth of the penetration along the separating axis (s2)
      //   * if this is the largest depth so far, record it.
      // the normal vector will be set to the separating axis with the smallest
      // depth. note: normalR is set to point to a column of R1 or R2 if that is
      // the smallest depth normal so far. otherwise normalR is 0 and normalC is
      // set to a vector relative to body 1. invert_normal is 1 if the sign of
      // the normal should be flipped.

      int best_col_id = -1;
      const Matrix3f* normalR = 0;
      FCL_REAL tmp = 0;

      s = - std::numeric_limits<FCL_REAL>::max();
      invert_normal = 0;
      code = 0;

      // separating axis = u1, u2, u3
      tmp = pp[0];
      s2 = std::abs(tmp) - (Q.row(0).dot(B) + A[0]);
      if(s2 > 0) { *return_code = 0; return 0; }
      if(s2 > s)
        {
          s = s2;
          best_col_id = 0;
          normalR = &R1;
          invert_normal = (tmp < 0);
          code = 1;
        }

      tmp = pp[1];
      s2 = std::abs(tmp) - (Q.row(1).dot(B) + A[1]);
      if(s2 > 0) { *return_code = 0; return 0; }
      if(s2 > s)
        {
          s = s2;
          best_col_id = 1;
          normalR = &R1;
          invert_normal = (tmp < 0);
          code = 2;
        }

      tmp = pp[2];
      s2 = std::abs(tmp) - (Q.row(2).dot(B) + A[2]);
      if(s2 > 0) { *return_code = 0; return 0; }
      if(s2 > s)
        {
          s = s2;
          best_col_id = 2;
          normalR = &R1;
          invert_normal = (tmp < 0);
          code = 3;
        }

      // separating axis = v1, v2, v3
      tmp = R2.col(0).dot(p);
      s2 = std::abs(tmp) - (Q.col(0).dot(A) + B[0]);
      if(s2 > 0) { *return_code = 0; return 0; }
      if(s2 > s)
        {
          s = s2;
          best_col_id = 0;
          normalR = &R2;
          invert_normal = (tmp < 0);
          code = 4;
        }

      tmp = R2.col(1).dot(p);
      s2 = std::abs(tmp) - (Q.col(1).dot(A) + B[1]);
      if(s2 > 0) { *return_code = 0; return 0; }
      if(s2 > s)
        {
          s = s2;
          best_col_id = 1;
          normalR = &R2;
          invert_normal = (tmp < 0);
          code = 5;
        }

      tmp = R2.col(2).dot(p);
      s2 =  std::abs(tmp) - (Q.col(2).dot(A) + B[2]);
      if(s2 > 0) { *return_code = 0; return 0; }
      if(s2 > s)
        {
          s = s2;
          best_col_id = 2;
          normalR = &R2;
          invert_normal = (tmp < 0);
          code = 6;
        }


      FCL_REAL fudge2(1.0e-6);
      Q.array() += fudge2;

      Vec3f n;
Joseph Mirabel's avatar
Joseph Mirabel committed
971
      static const FCL_REAL eps = std::numeric_limits<FCL_REAL>::epsilon();
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434

      // separating axis = u1 x (v1,v2,v3)
      tmp = pp[2] * R(1, 0) - pp[1] * R(2, 0);
      s2 = std::abs(tmp) - (A[1] * Q(2, 0) + A[2] * Q(1, 0) + B[1] * Q(0, 2) + B[2] * Q(0, 1));
      if(s2 > 0) { *return_code = 0; return 0; }
      n = Vec3f(0, -R(2, 0), R(1, 0));
      l = n.norm();
      if(l > eps)
        {
          s2 /= l;
          if(s2 * fudge_factor > s)
            {
              s = s2;
              best_col_id = -1;
              normalC = n / l;
              invert_normal = (tmp < 0);
              code = 7;
            }
        }

      tmp = pp[2] * R(1, 1) - pp[1] * R(2, 1);
      s2 = std::abs(tmp) - (A[1] * Q(2, 1) + A[2] * Q(1, 1) + B[0] * Q(0, 2) + B[2] * Q(0, 0));
      if(s2 > 0) { *return_code = 0; return 0; }
      n = Vec3f(0, -R(2, 1), R(1, 1));
      l = n.norm();
      if(l > eps)
        {
          s2 /= l;
          if(s2 * fudge_factor > s)
            {
              s = s2;
              best_col_id = -1;
              normalC = n / l;
              invert_normal = (tmp < 0);
              code = 8;
            }
        }

      tmp = pp[2] * R(1, 2) - pp[1] * R(2, 2);
      s2 = std::abs(tmp) - (A[1] * Q(2, 2) + A[2] * Q(1, 2) + B[0] * Q(0, 1) + B[1] * Q(0, 0));
      if(s2 > 0) { *return_code = 0; return 0; }
      n = Vec3f(0, -R(2, 2), R(1, 2));
      l = n.norm();
      if(l > eps)
        {
          s2 /= l;
          if(s2 * fudge_factor > s)
            {
              s = s2;
              best_col_id = -1;
              normalC = n / l;
              invert_normal = (tmp < 0);
              code = 9;
            }
        }

      // separating axis = u2 x (v1,v2,v3)
      tmp = pp[0] * R(2, 0) - pp[2] * R(0, 0);
      s2 = std::abs(tmp) - (A[0] * Q(2, 0) + A[2] * Q(0, 0) + B[1] * Q(1, 2) + B[2] * Q(1, 1));
      if(s2 > 0) { *return_code = 0; return 0; }
      n = Vec3f(R(2, 0), 0, -R(0, 0));
      l = n.norm();
      if(l > eps)
        {
          s2 /= l;
          if(s2 * fudge_factor > s)
            {
              s = s2;
              best_col_id = -1;
              normalC = n / l;
              invert_normal = (tmp < 0);
              code = 10;
            }
        }

      tmp = pp[0] * R(2, 1) - pp[2] * R(0, 1);
      s2 = std::abs(tmp) - (A[0] * Q(2, 1) + A[2] * Q(0, 1) + B[0] * Q(1, 2) + B[2] * Q(1, 0));
      if(s2 > 0) { *return_code = 0; return 0; }
      n = Vec3f(R(2, 1), 0, -R(0, 1));
      l = n.norm();
      if(l > eps)
        {
          s2 /= l;
          if(s2 * fudge_factor > s)
            {
              s = s2;
              best_col_id = -1;
              normalC = n / l;
              invert_normal = (tmp < 0);
              code = 11;
            }
        }

      tmp = pp[0] * R(2, 2) - pp[2] * R(0, 2);
      s2 = std::abs(tmp) - (A[0] * Q(2, 2) + A[2] * Q(0, 2) + B[0] * Q(1, 1) + B[1] * Q(1, 0));
      if(s2 > 0) { *return_code = 0; return 0; }
      n = Vec3f(R(2, 2), 0, -R(0, 2));
      l = n.norm();
      if(l > eps)
        {
          s2 /= l;
          if(s2 * fudge_factor > s)
            {
              s = s2;
              best_col_id = -1;
              normalC = n / l;
              invert_normal = (tmp < 0);
              code = 12;
            }
        }

      // separating axis = u3 x (v1,v2,v3)
      tmp = pp[1] * R(0, 0) - pp[0] * R(1, 0);
      s2 = std::abs(tmp) - (A[0] * Q(1, 0) + A[1] * Q(0, 0) + B[1] * Q(2, 2) + B[2] * Q(2, 1));
      if(s2 > 0) { *return_code = 0; return 0; }
      n = Vec3f(-R(1, 0), R(0, 0), 0);
      l = n.norm();
      if(l > eps)
        {
          s2 /= l;
          if(s2 * fudge_factor > s)
            {
              s = s2;
              best_col_id = -1;
              normalC = n / l;
              invert_normal = (tmp < 0);
              code = 13;
            }
        }

      tmp = pp[1] * R(0, 1) - pp[0] * R(1, 1);
      s2 = std::abs(tmp) - (A[0] * Q(1, 1) + A[1] * Q(0, 1) + B[0] * Q(2, 2) + B[2] * Q(2, 0));
      if(s2 > 0) { *return_code = 0; return 0; }
      n = Vec3f(-R(1, 1), R(0, 1), 0);
      l = n.norm();
      if(l > eps)
        {
          s2 /= l;
          if(s2 * fudge_factor > s)
            {
              s = s2;
              best_col_id = -1;
              normalC = n / l;
              invert_normal = (tmp < 0);
              code = 14;
            }
        }

      tmp = pp[1] * R(0, 2) - pp[0] * R(1, 2);
      s2 = std::abs(tmp) - (A[0] * Q(1, 2) + A[1] * Q(0, 2) + B[0] * Q(2, 1) + B[1] * Q(2, 0));
      if(s2 > 0) { *return_code = 0; return 0; }
      n = Vec3f(-R(1, 2), R(0, 2), 0);
      l = n.norm();
      if(l > eps)
        {
          s2 /= l;
          if(s2 * fudge_factor > s)
            {
              s = s2;
              best_col_id = -1;
              normalC = n / l;
              invert_normal = (tmp < 0);
              code = 15;
            }
        }



      if (!code) { *return_code = code; return 0; }

      // if we get to this point, the boxes interpenetrate. compute the normal
      // in global coordinates.
      if(best_col_id != -1)
        normal = normalR->col(best_col_id);
      else
        normal = R1 * normalC;

      if(invert_normal)
        normal = -normal;

      *depth = -s; // s is negative when the boxes are in collision

      // compute contact point(s)

      if(code > 6)
        {
          // an edge from box 1 touches an edge from box 2.
          // find a point pa on the intersecting edge of box 1
          Vec3f pa(T1);
          FCL_REAL sign;

          for(int j = 0; j < 3; ++j)
            {
              sign = (R1.col(j).dot(normal) > 0) ? 1 : -1;
              pa += R1.col(j) * (A[j] * sign);
            }

          // find a point pb on the intersecting edge of box 2
          Vec3f pb(T2);

          for(int j = 0; j < 3; ++j)
            {
              sign = (R2.col(j).dot(normal) > 0) ? -1 : 1;
              pb += R2.col(j) * (B[j] * sign);
            }

          FCL_REAL alpha, beta;
          Vec3f ua(R1.col((code-7)/3));
          Vec3f ub(R2.col((code-7)%3));

          lineClosestApproach(pa, ua, pb, ub, &alpha, &beta);
          pa += ua * alpha;
          pb += ub * beta;


          // Vec3f pointInWorld((pa + pb) * 0.5);
          // contacts.push_back(ContactPoint(-normal, pointInWorld, -*depth));
          contacts.push_back(ContactPoint(-normal,pb,-*depth));
          *return_code = code;

          return 1;
        }

      // okay, we have a face-something intersection (because the separating
      // axis is perpendicular to a face). define face 'a' to be the reference
      // face (i.e. the normal vector is perpendicular to this) and face 'b' to be
      // the incident face (the closest face of the other box).

      const Matrix3f *Ra, *Rb;
      const Vec3f *pa, *pb, *Sa, *Sb;

      if(code <= 3)
        {
          Ra = &R1;
          Rb = &R2;
          pa = &T1;
          pb = &T2;
          Sa = &A;
          Sb = &B;
        }
      else
        {
          Ra = &R2;
          Rb = &R1;
          pa = &T2;
          pb = &T1;
          Sa = &B;
          Sb = &A;
        }

      // nr = normal vector of reference face dotted with axes of incident box.
      // anr = absolute values of nr.
      Vec3f normal2, nr, anr;
      if(code <= 3)
        normal2 = normal;
      else
        normal2 = -normal;

      nr = Rb->transpose() * normal2;
      anr = nr.cwiseAbs();

      // find the largest compontent of anr: this corresponds to the normal
      // for the indident face. the other axis numbers of the indicent face
      // are stored in a1,a2.
      int lanr, a1, a2;
      if(anr[1] > anr[0])
        {
          if(anr[1] > anr[2])
            {
              a1 = 0;
              lanr = 1;
              a2 = 2;
            }
          else
            {
              a1 = 0;
              a2 = 1;
              lanr = 2;
            }
        }
      else
        {
          if(anr[0] > anr[2])
            {
              lanr = 0;
              a1 = 1;
              a2 = 2;
            }
          else
            {
              a1 = 0;
              a2 = 1;
              lanr = 2;
            }
        }

      // compute center point of incident face, in reference-face coordinates
      Vec3f center;
      if(nr[lanr] < 0)
        center = (*pb) - (*pa) + Rb->col(lanr) * ((*Sb)[lanr]);
      else
        center = (*pb) - (*pa) - Rb->col(lanr) * ((*Sb)[lanr]);

      // find the normal and non-normal axis numbers of the reference box
      int codeN, code1, code2;
      if(code <= 3)
        codeN = code-1;
      else codeN = code-4;

      if(codeN == 0)
        {
          code1 = 1;
          code2 = 2;
        }
      else if(codeN == 1)
        {
          code1 = 0;
          code2 = 2;
        }
      else
        {
          code1 = 0;
          code2 = 1;
        }

      // find the four corners of the incident face, in reference-face coordinates
      FCL_REAL quad[8]; // 2D coordinate of incident face (x,y pairs)
      FCL_REAL c1, c2, m11, m12, m21, m22;
      c1 = Ra->col(code1).dot(center);
      c2 = Ra->col(code2).dot(center);
      // optimize this? - we have already computed this data above, but it is not
      // stored in an easy-to-index format. for now it's quicker just to recompute
      // the four dot products.
      Vec3f tempRac = Ra->col(code1);
      m11 = Rb->col(a1).dot(tempRac);
      m12 = Rb->col(a2).dot(tempRac);
      tempRac = Ra->col(code2);
      m21 = Rb->col(a1).dot(tempRac);
      m22 = Rb->col(a2).dot(tempRac);

      FCL_REAL k1 = m11 * (*Sb)[a1];
      FCL_REAL k2 = m21 * (*Sb)[a1];
      FCL_REAL k3 = m12 * (*Sb)[a2];
      FCL_REAL k4 = m22 * (*Sb)[a2];
      quad[0] = c1 - k1 - k3;
      quad[1] = c2 - k2 - k4;
      quad[2] = c1 - k1 + k3;
      quad[3] = c2 - k2 + k4;
      quad[4] = c1 + k1 + k3;
      quad[5] = c2 + k2 + k4;
      quad[6] = c1 + k1 - k3;
      quad[7] = c2 + k2 - k4;

      // find the size of the reference face
      FCL_REAL rect[2];
      rect[0] = (*Sa)[code1];
      rect[1] = (*Sa)[code2];

      // intersect the incident and reference faces
      FCL_REAL ret[16];
      int n_intersect = intersectRectQuad2(rect, quad, ret);
      if(n_intersect < 1) { *return_code = code; return 0; } // this should never happen

      // convert the intersection points into reference-face coordinates,
      // and compute the contact position and depth for each point. only keep
      // those points that have a positive (penetrating) depth. delete points in
      // the 'ret' array as necessary so that 'point' and 'ret' correspond.
      Vec3f points[8]; // penetrating contact points
      FCL_REAL dep[8]; // depths for those points
      FCL_REAL det1 = 1.f/(m11*m22 - m12*m21);
      m11 *= det1;
      m12 *= det1;
      m21 *= det1;
      m22 *= det1;
      int cnum = 0;	// number of penetrating contact points found
      for(int j = 0; j < n_intersect; ++j)
        {
          FCL_REAL k1 =  m22*(ret[j*2]-c1) - m12*(ret[j*2+1]-c2);
          FCL_REAL k2 = -m21*(ret[j*2]-c1) + m11*(ret[j*2+1]-c2);
          points[cnum] = center + Rb->col(a1) * k1 + Rb->col(a2) * k2;
          dep[cnum] = (*Sa)[codeN] - normal2.dot(points[cnum]);
          if(dep[cnum] >= 0)
            {
              ret[cnum*2] = ret[j*2];
              ret[cnum*2+1] = ret[j*2+1];
              cnum++;
            }
        }
      if(cnum < 1) { *return_code = code; return 0; } // this should never happen

      // we can't generate more contacts than we actually have
      if(maxc > cnum) maxc = cnum;
      if(maxc < 1) maxc = 1;

      if(cnum <= maxc)
        {
          if(code<4)
            {
              // we have less contacts than we need, so we use them all
              for(int j = 0; j < cnum; ++j)
                {
                  Vec3f pointInWorld = points[j] + (*pa);
                  contacts.push_back(ContactPoint(-normal, pointInWorld, -dep[j]));
                }
            }
          else
            {
              // we have less contacts than we need, so we use them all
              for(int j = 0; j < cnum; ++j)
                {
                  Vec3f pointInWorld = points[j] + (*pa) - normal * dep[j];
                  contacts.push_back(ContactPoint(-normal, pointInWorld, -dep[j]));
                }
            }
        }
      else
        {
          // we have more contacts than are wanted, some of them must be culled.
          // find the deepest point, it is always the first contact.
          int i1 = 0;
          FCL_REAL maxdepth = dep[0];
          for(int i = 1; i < cnum; ++i)
            {
              if(dep[i] > maxdepth)
                {
                  maxdepth = dep[i];
                  i1 = i;
                }
            }

          int iret[8];
          cullPoints2(cnum, ret, maxc, i1, iret);

          for(int j = 0; j < maxc; ++j)
            {
              Vec3f posInWorld = points[iret[j]] + (*pa);
              if(code < 4)
                contacts.push_back(ContactPoint(-normal, posInWorld, -dep[iret[j]]));
              else
                contacts.push_back(ContactPoint(-normal, posInWorld - normal * dep[iret[j]], -dep[iret[j]]));
            }
          cnum = maxc;
        }

      *return_code = code;
      return cnum;
    }

    inline bool compareContactPoints
      (const ContactPoint& c1,const ContactPoint& c2)
    {
      return c1.depth < c2.depth;
    } // Accending order, assuming penetration depth is a negative number!

    inline bool boxBoxIntersect(const Box& s1, const Transform3f& tf1,
                                const Box& s2, const Transform3f& tf2,
                                Vec3f* contact_points,
                                FCL_REAL* penetration_depth_, Vec3f* normal_)
    {
      std::vector<ContactPoint> contacts;
      int return_code;
      Vec3f normal;
      FCL_REAL depth;
1435
1436
      /* int cnum = */ boxBox2(s1.halfSide, tf1.getRotation(), tf1.getTranslation(),
                               s2.halfSide, tf2.getRotation(), tf2.getTranslation(),
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
                               normal, &depth, &return_code,
                               4, contacts);

      if(normal_) *normal_ = normal;
      if(penetration_depth_) *penetration_depth_ = depth;

      if(contact_points)
        {
          if(contacts.size() > 0)
            {
              std::sort(contacts.begin(), contacts.end(), compareContactPoints);
              *contact_points = contacts[0].point;
              if(penetration_depth_) *penetration_depth_ = -contacts[0].depth;
            }
        }

      return return_code != 0;
    }

    template<typename T>
      inline T halfspaceIntersectTolerance()
      {
        return 0;
      }

    template<>
      inline float halfspaceIntersectTolerance()
      {
        return 0.0001f;
      }

    template<>
      inline double halfspaceIntersectTolerance()
      {
        return 0.0000001;
      }

    inline bool sphereHalfspaceIntersect
      (const Sphere& s1, const Transform3f& tf1,
       const Halfspace& s2, const Transform3f& tf2,
       FCL_REAL& distance, Vec3f& p1, Vec3f& p2,
       Vec3f& normal)
    {
      Halfspace new_s2 = transform(s2, tf2);
      const Vec3f& center = tf1.getTranslation();
      distance = new_s2.signedDistance(center) - s1.radius;
      if(distance <= 0)
      {
        normal = -new_s2.n; // pointing from s1 to s2
        p1 = p2 = center - new_s2.n * s1.radius - (distance * 0.5) * new_s2.n;
        return true;
      }
      else {
        p1 = center - s1.radius * new_s2.n;
        p2 = p1 - distance * new_s2.n;
        return false;
      }
    }

    /// @brief box half space, a, b, c  = +/- edge size
    /// n^T * (R(o + a v1 + b v2 + c v3) + T) <= d
    /// so (R^T n) (a v1 + b v2 + c v3) + n * T <= d
    /// check whether d - n * T - (R^T n) (a v1 + b v2 + c v3) >= 0 for some a, b, c
    /// the max value of left side is d - n * T + |(R^T n) (a v1 + b v2 + c v3)|, check that is enough
    inline bool boxHalfspaceIntersect
      (const Box& s1, const Transform3f& tf1,
       const Halfspace& s2, const Transform3f& tf2)
    {
      Halfspace new_s2 = transform(s2, tf2);

      const Matrix3f& R = tf1.getRotation();
      const Vec3f& T = tf1.getTranslation();

1510
      Vec3f Q (R.transpose() * new_s2.n);
1511

1512
      FCL_REAL depth = Q.cwiseProduct(s1.halfSide).lpNorm<1>() - new_s2.signedDistance(T);
1513
1514
1515
1516
1517
1518
1519
      return (depth >= 0);
    }


    inline bool boxHalfspaceIntersect
      (const Box& s1, const Transform3f& tf1,
       const Halfspace& s2, const Transform3f& tf2,
1520
       FCL_REAL& distance, Vec3f& p1, Vec3f& p2, Vec3f& normal)
1521
    {
1522
      Halfspace new_s2 = transform(s2, tf2);
1523

1524
1525
      const Matrix3f& R = tf1.getRotation();
      const Vec3f& T = tf1.getTranslation();
1526

1527
      // Q: plane normal expressed in box frame
1528
      const Vec3f Q (R.transpose() * new_s2.n);
1529
      // A: scalar products of each side with normal
1530
      const Vec3f A (Q.cwiseProduct(s1.halfSide));
1531

1532
      distance = new_s2.signedDistance(T) - A.lpNorm<1>();
1533
      if(distance > 0) {
1534
1535
        p1.noalias() = T + R * (A.array() > 0).select (s1.halfSide, - s1.halfSide);
        p2.noalias() = p1 - distance * new_s2.n;
1536
1537
        return false;
      }
1538

1539
1540
1541
      /// find deepest point
      Vec3f p(T);
      int sign = 0;
1542

1543
1544
1545
      if(std::abs(Q[0] - 1) < halfspaceIntersectTolerance<FCL_REAL>() || std::abs(Q[0] + 1) < halfspaceIntersectTolerance<FCL_REAL>())
        {
          sign = (A[0] > 0) ? -1 : 1;
1546
          p += R.col(0) * (s1.halfSide[0] * sign);
1547
1548
1549
1550
        }
      else if(std::abs(Q[1] - 1) < halfspaceIntersectTolerance<FCL_REAL>() || std::abs(Q[1] + 1) < halfspaceIntersectTolerance<FCL_REAL>())
        {
          sign = (A[1] > 0) ? -1 : 1;
1551
          p += R.col(1) * (s1.halfSide[1] * sign);
1552
1553
1554
1555
        }
      else if(std::abs(Q[2] - 1) < halfspaceIntersectTolerance<FCL_REAL>() || std::abs(Q[2] + 1) < halfspaceIntersectTolerance<FCL_REAL>())
        {
          sign = (A[2] > 0) ? -1 : 1;
1556
          p += R.col(2) * (s1.halfSide[2] * sign);
1557
1558
1559
        }
      else
        {
1560
          p.noalias() += R * (A.array() > 0).select (-s1.halfSide, s1.halfSide);
1561
        }
1562

1563
1564
1565
      /// compute the contact point from the deepest point
      normal = -new_s2.n;
      p1 = p2 = p - new_s2.n * (distance * 0.5);
1566

1567
      return true;
1568
1569
1570
1571
1572
    }

    inline bool capsuleHalfspaceIntersect
      (const Capsule& s1, const Transform3f& tf1,
       const Halfspace& s2, const Transform3f& tf2,
1573
1574
       FCL_REAL& distance, Vec3f& p1, Vec3f& p2,
       Vec3f& normal)
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
    {
      Halfspace new_s2 = transform(s2, tf2);

      const Matrix3f& R = tf1.getRotation();
      const Vec3f& T = tf1.getTranslation();

      Vec3f dir_z = R.col(2);

      FCL_REAL cosa = dir_z.dot(new_s2.n);
      if(std::abs(cosa) < halfspaceIntersectTolerance<FCL_REAL>())
        {
1586
          // Capsule parallel to plane
1587
          FCL_REAL signed_dist = new_s2.signedDistance(T);
1588
1589
1590
1591
1592
1593
          distance = signed_dist - s1.radius;
          if(distance > 0) {
            p1 = T - s1.radius * new_s2.n;
            p2 = p1 - distance * new_s2.n;
            return false;
          }
1594

1595
1596
          normal = -new_s2.n;
          p1 = p2 = T + new_s2.n * (-0.5 * distance - s1.radius);
1597
1598
1599
1600
1601
          return true;
        }
      else
        {
          int sign = (cosa > 0) ? -1 : 1;
1602
1603
          // closest capsule vertex to halfspace if no collision,
          // or deeper inside halspace if collision
1604
          Vec3f p = T + dir_z * (s1.halfLength * sign);
1605
1606

          FCL_REAL signed_dist = new_s2.signedDistance(p);
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
          distance = signed_dist - s1.radius;
          if(distance > 0) {
            p1 = T - s1.radius * new_s2.n;
            p2 = p1 - distance * new_s2.n;
            return false;
          }
          normal = -new_s2.n;
          // deepest point
          Vec3f c = p - new_s2.n * s1.radius;
          p1 = p2 = c - (0.5 * distance) * new_s2.n;
1617
1618
1619
1620
1621
1622
1623
1624
          return true;
        }
    }


    inline bool cylinderHalfspaceIntersect
      (const Cylinder& s1, const Transform3f& tf1,
       const Halfspace& s2, const Transform3f& tf2,
1625
1626
       FCL_REAL& distance, Vec3f& p1, Vec3f& p2,
       Vec3f& normal)
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
    {
      Halfspace new_s2 = transform(s2, tf2);

      const Matrix3f& R = tf1.getRotation();
      const Vec3f& T = tf1.getTranslation();

      Vec3f dir_z = R.col(2);
      FCL_REAL cosa = dir_z.dot(new_s2.n);

      if(cosa < halfspaceIntersectTolerance<FCL_REAL>())
        {
          FCL_REAL signed_dist = new_s2.signedDistance(T);
1639
1640
1641
1642
1643
1644
          distance = signed_dist - s1.radius;
          if(distance > 0) {
            // TODO: compute closest points
            p1 = p2 = Vec3f(0, 0, 0);
            return false;
          }
1645

1646
1647
          normal = -new_s2.n;
          p1 = p2 = T - (0.5 * distance + s1.radius) * new_s2.n;
1648
1649
1650
1651
1652
          return true;
        }
      else
        {
          Vec3f C = dir_z * cosa - new_s2.n;
1653
1654
          if(std::abs(cosa + 1) < halfspaceIntersectTolerance<FCL_REAL>() ||
             std::abs(cosa - 1) < halfspaceIntersectTolerance<FCL_REAL>())
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
            C = Vec3f(0, 0, 0);
          else
            {
              FCL_REAL s = C.norm();
              s = s1.radius / s;
              C *= s;
            }

          int sign = (cosa > 0) ? -1 : 1;
          // deepest point
1665
          Vec3f p = T + dir_z * (s1.halfLength * sign) + C;
1666
1667
1668
1669
1670
1671
          distance = new_s2.signedDistance(p);
          if(distance > 0) {
            // TODO: compute closest points
            p1 = p2 = Vec3f(0, 0, 0);
            return false;
          }
1672
1673
          else
            {
1674
1675
              normal = -new_s2.n;
              p1 = p2 = p - (0.5 * distance) * new_s2.n;
1676
1677
1678
1679
1680
1681
1682
1683
1684
              return true;
            }
        }
    }


    inline bool coneHalfspaceIntersect
      (const Cone& s1, const Transform3f& tf1,
       const Halfspace& s2, const Transform3f& tf2,
1685
1686
       FCL_REAL& distance, Vec3f& p1, Vec3f& p2,
       Vec3f& normal)
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
    {
      Halfspace new_s2 = transform(s2, tf2);

      const Matrix3f& R = tf1.getRotation();
      const Vec3f& T = tf1.getTranslation();

      Vec3f dir_z = R.col(2);
      FCL_REAL cosa = dir_z.dot(new_s2.n);

      if(cosa < halfspaceIntersectTolerance<FCL_REAL>())
        {
          FCL_REAL signed_dist = new_s2.signedDistance(T);
1699
1700
1701
1702
1703
          distance = signed_dist - s1.radius;
          if(distance > 0) {
            p1 = p2 = Vec3f (0, 0, 0);
            return false;
          }
1704
1705
          else
            {
1706
              normal = -new_s2.n;
1707
              p1 = p2 = T - dir_z * (s1.halfLength) -
1708
                new_s2.n * (0.5 * distance + s1.radius);
1709
1710
1711
1712
1713
1714
              return true;
            }
        }
      else
        {
          Vec3f C = dir_z * cosa - new_s2.n;
1715
1716
          if(std::abs(cosa + 1) < halfspaceIntersectTolerance<FCL_REAL>() ||
             std::abs(cosa - 1) < halfspaceIntersectTolerance<FCL_REAL>())
1717
1718
1719
1720
1721
1722
1723
1724
            C = Vec3f(0, 0, 0);
          else
            {
              FCL_REAL s = C.norm();
              s = s1.radius / s;
              C *= s;
            }

1725
1726
          Vec3f a1 = T + dir_z * (s1.halfLength);
          Vec3f a2 = T - dir_z * (s1.halfLength) + C;
1727

1728
1729
          FCL_REAL d1 = new_s2.signedDistance(a1);
          FCL_REAL d2 = new_s2.signedDistance(a2);
1730
1731
1732
1733

          if(d1 > 0 && d2 > 0) return false;
          else
            {
1734
1735
1736
              distance = std::min(d1, d2);
              normal = -new_s2.n;
              p1 = p2 = ((d1 < d2) ? a1 : a2) - (0.5 * distance) * new_s2.n;
1737
1738
1739
1740
1741
1742
              return true;
            }
        }
    }

    inline bool convexHalfspaceIntersect
1743
      (const ConvexBase& s1, const Transform3f& tf1,
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
       const Halfspace& s2, const Transform3f& tf2,
       Vec3f* contact_points, FCL_REAL* penetration_depth, Vec3f* normal)
    {
      Halfspace new_s2 = transform(s2, tf2);

      Vec3f v;
      FCL_REAL depth = std::numeric_limits<FCL_REAL>::max();

      for(int i = 0; i < s1.num_points; ++i)
        {
          Vec3f p = tf1.transform(s1.points[i]);

          FCL_REAL d = new_s2.signedDistance(p);
          if(d < depth)
            {
              depth = d;
              v = p;
            }
        }

      if(depth <= 0)
        {
          if(contact_points) *contact_points = v - new_s2.n * (0.5 * depth);
          if(penetration_depth) *penetration_depth = depth;
          if(normal) *normal = -new_s2.n;
          return true;
        }
      else
        return false;
    }

    // Intersection between half-space and triangle
    // Half-space is in pose tf1,
    // Triangle is in pose tf2
    // Computes distance and closest points (p1, p2) if no collision,
    //          contact point (p1 = p2), normal and penetration depth (-distance)
    //          if collision
    inline bool halfspaceTriangleIntersect
      (const Halfspace& s1, const Transform3f& tf1, const Vec3f& P1,
       const Vec3f& P2, const Vec3f& P3, const Transform3f& tf2,
       FCL_REAL& distance, Vec3f& p1, Vec3f& p2, Vec3f& normal)
    {
      Halfspace new_s1 = transform(s1, tf1);

      Vec3f v = tf2.transform(P1);
      FCL_REAL depth = new_s1.signedDistance(v);

      Vec3f p = tf2.transform(P2);
      FCL_REAL d = new_s1.signedDistance(p);
      if(d < depth)
        {
          depth = d;
          v = p;
        }

      p = tf2.transform(P3);
      d = new_s1.signedDistance(p);
      if(d < depth)
        {
          depth = d;
          v = p;
        }
      // v is the vertex with minimal projection abscissa (depth) on normal to
      //plane,
      distance = depth;
      if(depth <= 0)
        {
          normal = new_s1.n;
          p1 = p2 = v - (0.5 * depth) * new_s1.n;
          return true;
        }
      else
        {
          p1 = v - depth * new_s1.n;
          p2 = v;
          return false;
        }
    }


    /// @brief return whether plane collides with halfspace
    /// if the separation plane of the halfspace is parallel with the plane
    ///     return code 1, if the plane's normal is the same with halfspace's normal and plane is inside halfspace, also return plane in pl
    ///     return code 2, if the plane's normal is oppositie to the halfspace's normal and plane is inside halfspace, also return plane in pl
    ///     plane is outside halfspace, collision-free
    /// if not parallel
    ///     return the intersection ray, return code 3. ray origin is p and direction is d
    inline bool planeHalfspaceIntersect
      (const Plane& s1, const Transform3f& tf1,
       const Halfspace& s2, const Transform3f& tf2, Plane& pl, Vec3f& p,
       Vec3f& d, FCL_REAL& penetration_depth, int& ret)
    {
      Plane new_s1 = transform(s1, tf1);
      Halfspace new_s2 = transform(s2, tf2);

      ret = 0;

1841
      penetration_depth = std::numeric_limits<FCL_REAL>::max();
1842
1843
1844
1845
1846
1847
      Vec3f dir = (new_s1.n).cross(new_s2.n);
      FCL_REAL dir_norm = dir.squaredNorm();
      if(dir_norm < std::numeric_limits<FCL_REAL>::epsilon()) // parallel
        {
          if((new_s1.n).dot(new_s2.n) > 0)
            {
1848
1849
1850
1851
              penetration_depth = new_s2.d - new_s1.d;
              if(penetration_depth < 0)
                return false;
              else
1852
1853
1854
1855
1856
1857
1858
1859
                {
                  ret = 1;
                  pl = new_s1;
                  return true;
                }
            }
          else
            {
1860
1861
              penetration_depth = -(new_s1.d + new_s2.d);
              if(penetration_depth < 0)
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
                return false;
              else
                {
                  ret = 2;
                  pl = new_s1;
                  return true;
                }
            }
        }

      Vec3f n = new_s2.n * new_s1.d - new_s1.n * new_s2.d;
      Vec3f origin = n.cross(dir);
      origin *= (1.0 / dir_norm);

      p = origin;
      d = dir;
      ret = 3;

      return true;
    }

    ///@ brief return whether two halfspace intersect
    /// if the separation planes of the two halfspaces are parallel
    ///    return code 1, if two halfspaces' normal are same and s1 is in s2, also return s1 in s;
    ///    return code 2, if two halfspaces' normal are same and s2 is in s1, also return s2 in s;
    ///    return code 3, if two halfspaces' normal are opposite and s1 and s2 are into each other;
    ///    collision free, if two halfspaces' are separate;
    /// if the separation planes of the two halfspaces are not parallel, return intersection ray, return code 4. ray origin is p and direction is d
    /// collision free return code 0
    inline bool halfspaceIntersect(const Halfspace& s1, const Transform3f& tf1,
                                   const Halfspace& s2, const Transform3f& tf2,
                                   Vec3f& p, Vec3f& d,
                                   Halfspace& s,
                                   FCL_REAL& penetration_depth, int& ret)
    {
      Halfspace new_s1 = transform(s1, tf1);
      Halfspace new_s2 = transform(s2, tf2);

      ret = 0;

1902
      penetration_depth = std::numeric_limits<FCL_REAL>::max();
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
      Vec3f dir = (new_s1.n).cross(new_s2.n);
      FCL_REAL dir_norm = dir.squaredNorm();
      if(dir_norm < std::numeric_limits<FCL_REAL>::epsilon()) // parallel
        {
          if((new_s1.n).dot(new_s2.n) > 0)
            {
              if(new_s1.d < new_s2.d) // s1 is inside s2
                {
                  ret = 1;
                  s = new_s1;
                }
              else // s2 is inside s1
                {
                  ret = 2;
                  s = new_s2;
                }
              return true;
            }
          else
            {
1923
1924
              penetration_depth = -(new_s1.d + new_s2.d);
              if(penetration_depth < 0) // not collision
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
                return false;
              else // in each other
                {
                  ret = 3;
                  return true;
                }
            }
        }

      Vec3f n = new_s2.n * new_s1.d - new_s1.n * new_s2.d;
      Vec3f origin = n.cross(dir);
      origin *= (1.0 / dir_norm);

      p = origin;
      d = dir;
      ret = 4;

      return true;
    }

    template<typename T>
      inline T planeIntersectTolerance()
      {
        return 0;
      }

    template<>
      inline double planeIntersectTolerance<double>()
      {
        return 0.0000001;
      }

    template<>
      float inline planeIntersectTolerance<float>()
      {
        return 0.0001f;
      }

    inline bool spherePlaneIntersect
      (const Sphere& s1, const Transform3f& tf1,
       const Plane& s2, const Transform3f& tf2,
1966
1967
1968
       FCL_REAL& distance, Vec3f& p1, Vec3f& p2,
       Vec3f& normal)
    //  Vec3f& contact_points, FCL_REAL& penetration_depth, Vec3f* normal)
1969
1970
1971
1972
1973
    {
      Plane new_s2 = transform(s2, tf2);

      const Vec3f& center = tf1.getTranslation();
      FCL_REAL signed_dist = new_s2.signedDistance(center);
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
      distance = std::abs(signed_dist) - s1.radius;
      if(distance <= 0)
      {
        if (signed_dist > 0)
          normal = -new_s2.n;
        else
          normal = new_s2.n;
        p1 = p2 = center - new_s2.n * signed_dist;
        return true;
      }
      else
      {
        if (signed_dist > 0)
1987
        {
1988
1989
1990
1991
1992
1993
1994