intersection.hh 24.4 KB
Newer Older
1
2
#pragma once

3
#include <typed-geometry/detail/optional.hh>
Philip Trettner's avatar
Philip Trettner committed
4
5
#include <typed-geometry/feature/assert.hh>
#include <typed-geometry/functions/basic/scalar_math.hh>
6

Philip Trettner's avatar
Philip Trettner committed
7
8
#include <typed-geometry/types/objects/capsule.hh>
#include <typed-geometry/types/objects/cylinder.hh>
Philip Trettner's avatar
Philip Trettner committed
9
#include <typed-geometry/types/objects/plane.hh>
Philip Trettner's avatar
Philip Trettner committed
10
#include <typed-geometry/types/objects/ray.hh>
11
#include <typed-geometry/types/objects/segment.hh>
Philip Trettner's avatar
Philip Trettner committed
12
13
#include <typed-geometry/types/objects/sphere.hh>
#include <typed-geometry/types/objects/triangle.hh>
14

Philip Trettner's avatar
Philip Trettner committed
15
16
17
18
#include <typed-geometry/functions/vector/cross.hh>
#include <typed-geometry/functions/vector/dot.hh>
#include <typed-geometry/functions/vector/length.hh>

19
#include "aabb.hh"
20
#include "closest_points.hh"
21
#include "contains.hh"
Philip Trettner's avatar
Philip Trettner committed
22
#include "direction.hh"
23
#include "normal.hh"
24

25
26
// family of intersection functions:

Philip Trettner's avatar
Philip Trettner committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// intersects(a, b)              -> bool
// intersection(a, b)            -> ???
// intersection_safe(a, b)       -> optional<???>
// intersection_parameter(a, b)  -> coords?
// intersection_parameters(a, b) -> pair<coords, coords>?
// intersection_exact(a, b)      -> variant
// closest_intersection(a, b)            -> ???
// closest_intersection_parameter(a, b)  -> coords?

// "intersects" returns true iff any point lies in a and in b
// "intersection" returns an object describing the intersection (NOTE: does NOT handle degenerate cases)
// "intersection_safe" is the same as "intersection" but returns nullopt for degenerate cases
// "intersection_parameter" returns a coordinates for the first object such that a[coords] == intersection(a, b)
// "intersection_parameters" returns coordinates for both objects
// "intersection_exact" returns a variant type describing all possible intersections, including degenerate cases
// the "closest_" variants only return the closest intersection for objects where thay concept is applicable (e.g. for rays)

// Notes:
//  - intersection_exact is currently unsupported
//  - intersection_safe is currently unsupported
//  - for more elaborate ray-tracing, a future ray_cast function will exist (which also returns the intersection normal)
48
49


50
51
namespace tg
{
Philip Trettner's avatar
Philip Trettner committed
52
53
54
55
56
57
58
59
60
// ====================================== Result Structs ======================================

/// ordered list of ray intersection hits
/// behaves like a container with
///   .size()
///   operator[]
///   range-based-for
template <int MaxHits, class HitT>
struct ray_hits
61
{
62
63
    static constexpr bool is_ray_hits = true; // tag
    static constexpr int max_hits = MaxHits;
Philip Trettner's avatar
Philip Trettner committed
64
65
66
67

    template <class OtherT>
    using as_ray_hits = ray_hits<MaxHits, OtherT>;

Philip Trettner's avatar
Philip Trettner committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
    int size() const { return _size; }
    bool any() const { return _size > 0; }

    HitT const& operator[](int idx)
    {
        TG_ASSERT(0 <= idx && idx < _size);
        return _hit[idx];
    }

    HitT const* begin() const { return _hit; }
    HitT const* end() const { return _hit + _size; }

    ray_hits() = default;
    ray_hits(HitT* hits, int size) : _size(size)
    {
        for (auto i = 0; i < size; ++i)
            _hit[i] = hits[i];
    }

private:
    int _size = 0;
    HitT _hit[MaxHits];
90
91
};

Philip Trettner's avatar
Philip Trettner committed
92

Philip Trettner's avatar
Philip Trettner committed
93
94
95
96
// ====================================== Default Implementations ======================================

// returns whether two objects intersect
template <class A, class B>
97
[[nodiscard]] constexpr auto intersects(A const& a, B const& b) -> decltype(intersection(a, b).has_value())
98
{
Philip Trettner's avatar
Philip Trettner committed
99
100
    return intersection(a, b).has_value();
}
101

Philip Trettner's avatar
Philip Trettner committed
102
103
// if a value-typed intersection parameter is available and applicable, use that
template <class A, class B>
104
[[nodiscard]] constexpr auto intersection(A const& a, B const& b) -> decltype(a[intersection_parameter(a, b)])
105
{
Philip Trettner's avatar
Philip Trettner committed
106
107
    return a[intersection_parameter(a, b)];
}
108

Philip Trettner's avatar
Philip Trettner committed
109
110
// if an optional intersection parameter is available and applicable, use that
template <class A, class B>
111
[[nodiscard]] constexpr auto intersection(A const& a, B const& b) -> optional<decltype(a[intersection_parameter(a, b).value()])>
112
{
Philip Trettner's avatar
Philip Trettner committed
113
114
115
116
    if (auto t = intersection_parameter(a, b); t.has_value())
        return a[t.value()];
    return {};
}
117

Philip Trettner's avatar
Philip Trettner committed
118
119
// if a value-typed closest intersection parameter is available and applicable, use that
template <class A, class B>
120
[[nodiscard]] constexpr auto closest_intersection(A const& a, B const& b) -> decltype(a[closest_intersection_parameter(a, b)])
121
{
Philip Trettner's avatar
Philip Trettner committed
122
123
    return a[closest_intersection_parameter(a, b)];
}
124

Philip Trettner's avatar
Philip Trettner committed
125
// if an optional closest intersection parameter is available and applicable, use that
126
template <class A, class B>
127
[[nodiscard]] constexpr auto closest_intersection(A const& a, B const& b) -> optional<decltype(a[closest_intersection_parameter(a, b).value()])>
128
{
Philip Trettner's avatar
Philip Trettner committed
129
130
131
    if (auto t = closest_intersection_parameter(a, b); t.has_value())
        return a[t.value()];
    return {};
132
133
}

Philip Trettner's avatar
Philip Trettner committed
134
135
// if ray_hits intersection parameter is available, use that
template <int D, class ScalarT, class Obj>
136
[[nodiscard]] constexpr auto intersection(ray<D, ScalarT> const& r, Obj const& obj) ->
Philip Trettner's avatar
Philip Trettner committed
137
138
139
140
141
142
143
144
145
146
147
    typename decltype(intersection_parameter(r, obj))::template as_ray_hits<pos<D, ScalarT>>
{
    auto ts = intersection_parameter(r, obj);
    pos<D, ScalarT> hits[ts.max_hits];
    for (auto i = 0; i < ts.size(); ++i)
        hits[i] = r[ts[i]];
    return {hits, ts.size()};
}

// if ray_hits intersection parameter is available, use that
template <int D, class ScalarT, class Obj>
148
[[nodiscard]] constexpr auto closest_intersection_parameter(ray<D, ScalarT> const& r, Obj const& obj)
Philip Trettner's avatar
Philip Trettner committed
149
150
151
152
153
154
155
156
    -> enable_if<decltype(intersection_parameter(r, obj))::is_ray_hits, optional<ScalarT>>
{
    auto hits = intersection_parameter(r, obj);
    if (hits.any())
        return hits[0];
    return {};
}

Philip Trettner's avatar
Philip Trettner committed
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
// intersection between point and obj is same as contains
template <int D, class ScalarT, class Obj, class = void_t<decltype(contains(std::declval<pos<D, ScalarT>>(), std::declval<Obj>()))>>
constexpr optional<pos<D, ScalarT>> intersection(pos<D, ScalarT> const& p, Obj const& obj)
{
    if (contains(obj, p))
        return p;
    return {};
}

// intersection between point and obj is same as contains
template <int D, class ScalarT, class Obj, class = void_t<decltype(contains(std::declval<pos<D, ScalarT>>(), std::declval<Obj>()))>>
constexpr optional<pos<D, ScalarT>> intersection(Obj const& obj, pos<D, ScalarT> const& p)
{
    if (contains(obj, p))
        return p;
    return {};
}


Philip Trettner's avatar
Philip Trettner committed
176
177
// ====================================== Ray - Object Intersections ======================================

Philip Trettner's avatar
Philip Trettner committed
178
// ray - plane
179
template <int D, class ScalarT>
Philip Trettner's avatar
Philip Trettner committed
180
[[nodiscard]] constexpr optional<ScalarT> intersection_parameter(ray<D, ScalarT> const& r, plane<D, ScalarT> const& p)
181
{
Philip Trettner's avatar
Philip Trettner committed
182
    // if plane normal and ray direction are parallel there is no intersection
183
    auto dotND = dot(p.normal, r.dir);
184
    if (dotND == ScalarT(0))
Philip Trettner's avatar
Philip Trettner committed
185
        return {};
186

Philip Trettner's avatar
Philip Trettner committed
187
188
189
190
191
192
193
    // plane: <x, p.normal> = p.dis
    // ray: x = r.origin + t * r.dir
    // =>
    // <r.origin + t * r.dir, p.normal> = p.dis
    // t = (p.dis - <r.origin, p.normal>) / <r.dir, p.normal>

    auto t = (p.dis - dot(p.normal, vec<D, ScalarT>(r.origin))) / dotND;
194
195

    // check whether plane lies behind ray
Julian Schakib's avatar
Julian Schakib committed
196
    if (t < 0)
Philip Trettner's avatar
Philip Trettner committed
197
        return {};
198

Philip Trettner's avatar
Philip Trettner committed
199
    return t;
200
201
}

Philip Trettner's avatar
Philip Trettner committed
202
203
// returns closest intersection point(s) of ray and sphere
template <int D, class ScalarT>
204
[[nodiscard]] constexpr optional<ScalarT> closest_intersection_parameter(ray<D, ScalarT> const& r, sphere<D, ScalarT> const& s)
205
{
Philip Trettner's avatar
Philip Trettner committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
    auto t = dot(s.center - r.origin, r.dir);

    auto d_sqr = distance_sqr(r[t], s.center);
    auto r_sqr = s.radius * s.radius;
    if (d_sqr > r_sqr)
        return {};

    auto dt = sqrt(r_sqr - d_sqr);

    if (t - dt >= 0)
        return t - dt;
    if (t + dt >= 0)
        return t + dt;

    return {};
221
}
222

223
// returns intersection point(s) of ray and sphere
Philip Trettner's avatar
Philip Trettner committed
224
template <int D, class ScalarT>
225
[[nodiscard]] constexpr ray_hits<2, ScalarT> intersection_parameter(ray<D, ScalarT> const& r, sphere<D, ScalarT> const& s)
226
{
Philip Trettner's avatar
Philip Trettner committed
227
    auto t = dot(s.center - r.origin, r.dir);
228

Philip Trettner's avatar
Philip Trettner committed
229
230
231
232
233
234
235
236
237
238
    auto d_sqr = distance_sqr(r[t], s.center);
    auto r_sqr = s.radius * s.radius;
    if (d_sqr > r_sqr)
        return {};

    auto dt = sqrt(r_sqr - d_sqr);

    ScalarT hits[2];

    if (t - dt >= 0)
239
    {
Philip Trettner's avatar
Philip Trettner committed
240
241
242
        hits[0] = t - dt;
        hits[1] = t + dt;
        return {hits, 2};
243
    }
Philip Trettner's avatar
Philip Trettner committed
244
245

    if (t + dt >= 0)
246
    {
Philip Trettner's avatar
Philip Trettner committed
247
248
        hits[0] = t + dt;
        return {hits, 1};
249
250
    }

Philip Trettner's avatar
Philip Trettner committed
251
252
    return {};
}
Philip Trettner's avatar
Philip Trettner committed
253
254
255

// ray - tube
template <class ScalarT>
Philip Trettner's avatar
Philip Trettner committed
256
[[nodiscard]] constexpr ray_hits<2, ScalarT> intersection_parameter(ray<3, ScalarT> const& r, cylinder_boundary_no_caps<3, ScalarT> const& c)
Philip Trettner's avatar
Philip Trettner committed
257
{
Philip Trettner's avatar
Philip Trettner committed
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
    auto cdir = direction(c);
    auto cosA = dot(cdir, r.dir);
    auto sinA_sqr = 1 - cosA * cosA;

    if (sinA_sqr <= 0)
        return {};

    // compute closest points of the two lines
    auto origDiff = r.origin - c.axis.pos0;
    auto fRay = dot(r.dir, origDiff);
    auto fLine = dot(cdir, origDiff);
    auto tRay = (cosA * fLine - fRay) / sinA_sqr;
    auto tLine = (fLine - cosA * fRay) / sinA_sqr;

    auto closest_on_ray = r.origin + tRay * r.dir;
    auto closest_on_line = c.axis.pos0 + tLine * cdir;
    auto line_ray_dist_sqr = distance_sqr(closest_on_ray, closest_on_line);
    auto cyl_radius_sqr = c.radius * c.radius;

    if (line_ray_dist_sqr > cyl_radius_sqr)
        return {};

    // radius in 2D slice
    auto r_2D = sqrt(cyl_radius_sqr - line_ray_dist_sqr);

    // infinite tube intersection
    auto s = r_2D / sqrt(sinA_sqr);
    auto cyl_intersection_0 = closest_on_ray - s * r.dir;
    auto cyl_intersection_1 = closest_on_ray + s * r.dir;

    // project onto line segment
    auto line_length = length(c.axis);
    auto lambda_0 = dot(cyl_intersection_0 - c.axis.pos0, cdir);
    auto lambda_1 = dot(cyl_intersection_1 - c.axis.pos0, cdir);

    ScalarT hits[2];
    int hit_cnt = 0;

    if (tRay - s >= 0 && 0 <= lambda_0 && lambda_0 < line_length)
        hits[hit_cnt++] = tRay - s;
    if (tRay + s >= 0 && 0 <= lambda_1 && lambda_1 < line_length)
        hits[hit_cnt++] = tRay + s;

    return {hits, hit_cnt};
}

// ray - disk
template <class ScalarT>
306
[[nodiscard]] constexpr optional<ScalarT> intersection_parameter(ray<3, ScalarT> const& r, sphere<2, ScalarT, 3> const& d)
Philip Trettner's avatar
Philip Trettner committed
307
{
Philip Trettner's avatar
Philip Trettner committed
308
    auto const t = intersection_parameter(r, plane<3, ScalarT>(d.normal, d.center));
Philip Trettner's avatar
Philip Trettner committed
309
310
311
312
313
314
315
316
317
318
    if (!t.has_value())
        return {};

    auto const p = r[t.value()];
    if (distance_sqr(p, d.center) > d.radius * d.radius)
        return {};

    return t;
}

319
320
321
322
323
324
325
326
327
// ray - quadric (as an isosurface, not error quadric)
template <class ScalarT>
[[nodiscard]] constexpr ray_hits<2, ScalarT> intersection_parameter(ray<3, ScalarT> const& r, quadric<3, ScalarT> const& q)
{
    const auto Ad = q.A() * r.dir;
    const auto p = r.origin;

    // Substituting x in Quadric equation x^TAx + 2b^Tx + c = 0 by ray equation x = t * dir + p yields
    // d^TAd t^2 + (2p^TAd + 2bd) t + p^TAp + 2bp + c = 0
328
    const auto a = dot(r.dir, Ad);
Aaron Grabowy's avatar
Aaron Grabowy committed
329
330
    const auto b = ScalarT(2) * (dot(p, Ad) + dot(q.b(), r.dir));
    const auto c = dot(p, q.A() * vec3(p)) + ScalarT(2) * dot(q.b(), p) + q.c;
331

332
    // Solve the quadratic equation ax^2 + bx + c = 0
Aaron Grabowy's avatar
Aaron Grabowy committed
333
334
    const auto discriminant = b * b - ScalarT(4) * a * c;
    if (discriminant < ScalarT(0))
335
336
        return {}; // No solution

Aaron Grabowy's avatar
Aaron Grabowy committed
337
338
339
    const auto sqrtD = sqrt(discriminant);
    const auto t1 = (-b - sqrtD) / (ScalarT(2) * a);
    const auto t2 = (-b + sqrtD) / (ScalarT(2) * a);
340

Aaron Grabowy's avatar
Aaron Grabowy committed
341
    auto tMin = min(t1, t2);
Aaron Grabowy's avatar
Aaron Grabowy committed
342
    auto tMax = max(t1, t2);
343
344
345

    ScalarT hits[2];

Aaron Grabowy's avatar
Aaron Grabowy committed
346
    if (tMin >= ScalarT(0))
347
348
349
350
351
352
    {
        hits[0] = tMin;
        hits[1] = tMax;
        return {hits, 2};
    }

Aaron Grabowy's avatar
Aaron Grabowy committed
353
    if (tMax >= ScalarT(0))
354
355
356
357
358
359
360
361
    {
        hits[0] = tMax;
        return {hits, 1};
    }

    return {};
}

Philip Trettner's avatar
Philip Trettner committed
362
363
// ray - cylinder
template <class ScalarT>
364
[[nodiscard]] constexpr optional<ScalarT> closest_intersection_parameter(ray<3, ScalarT> const& r, cylinder<3, ScalarT> const& c)
Philip Trettner's avatar
Philip Trettner committed
365
366
{
    auto const dir = direction(c);
Philip Trettner's avatar
Philip Trettner committed
367
    auto const t_cyl = closest_intersection_parameter(r, cylinder_boundary_no_caps<3, ScalarT>(c.axis, c.radius));
368
369
    auto const t_cap0 = intersection_parameter(r, sphere<2, ScalarT, 3>(c.axis.pos0, c.radius, dir));
    auto const t_cap1 = intersection_parameter(r, sphere<2, ScalarT, 3>(c.axis.pos1, c.radius, dir));
Philip Trettner's avatar
Philip Trettner committed
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384

    optional<ScalarT> t;

    if (t_cyl.has_value())
        t = t_cyl.value();

    if (t_cap0.has_value() && (!t.has_value() || t.value() > t_cap0.value()))
        t = t_cap0;

    if (t_cap1.has_value() && (!t.has_value() || t.value() > t_cap1.value()))
        t = t_cap1;

    TG_INTERNAL_ASSERT(!t.has_value() || t.value() >= 0);

    return t;
385
386
}

387
388

// returns intersection circle of sphere and sphere (normal points from a to b)
389
// for now does not work if spheres are identical (result would be a sphere3 again)
390
template <class ScalarT>
391
[[nodiscard]] constexpr optional<sphere_boundary<2, ScalarT, 3>> intersection(sphere_boundary<3, ScalarT> const& a, sphere_boundary<3, ScalarT> const& b)
392
{
393
    auto d2 = distance_sqr(a.center, b.center);
394

395
396
    // TODO: intersection sphere
    if (a.center == b.center && a.radius == b.radius)
Philip Trettner's avatar
Philip Trettner committed
397
        return {};
398

399
    auto d = sqrt(d2);
400
401
402

    // no intersection
    if (d > a.radius + b.radius)
Philip Trettner's avatar
Philip Trettner committed
403
        return {};
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421

    // radius and centers of larger sphere (ls) and smaller sphere (ss)
    auto lsr = a.radius;
    auto ssr = b.radius;
    auto lsc = a.center;
    auto ssc = b.center;
    if (b.radius > a.radius)
    {
        // TODO: tg::swap?
        lsr = b.radius;
        ssr = a.radius;
        lsc = b.center;
        ssc = a.center;
    }

    if (d + ssr < lsr)
    {
        // Smaller sphere inside larger one and not touching it
Philip Trettner's avatar
Philip Trettner committed
422
        return {};
423
424
    }

425
    TG_INTERNAL_ASSERT(d > ScalarT(0));
426

427
428
429
430
431
432
433
434
435
436
437
    // squared radii of a and b
    auto ar2 = a.radius * a.radius;
    auto br2 = b.radius * b.radius;

    auto t = ScalarT(0.5) + (ar2 - br2) / (ScalarT(2) * d2);

    // position and radius of intersection circle
    auto ipos = a.center + t * (b.center - a.center);
    auto irad = sqrt(ar2 - t * t * d2);

    // non-empty intersection (circle)
438
    return sphere_boundary<2, ScalarT, 3>{ipos, irad, dir<3, ScalarT>((b.center - a.center) / d)};
439
440
}

441
442
443
// returns intersection points of two circles in 2D
// for now does not work if circles are identical (result would be a circle2 again)
template <class ScalarT>
Philip Trettner's avatar
Philip Trettner committed
444
[[nodiscard]] constexpr optional<pair<pos<2, ScalarT>, pos<2, ScalarT>>> intersection(sphere_boundary<2, ScalarT> const& a, sphere_boundary<2, ScalarT> const& b)
445
446
{
    if (a.center == b.center && a.radius == b.radius)
Philip Trettner's avatar
Philip Trettner committed
447
        return {}; // degenerate case
448

449
    auto d2 = distance_sqr(a.center, b.center);
450
    auto d = sqrt(d2);
451
452
453
    auto ar = a.radius;
    auto br = b.radius;
    if (ar + br < d) // no intersection
Philip Trettner's avatar
Philip Trettner committed
454
        return {};
455

456
    if (d < abs(ar - br)) // no intersection (one inside the other)
Philip Trettner's avatar
Philip Trettner committed
457
        return {};
458

459
    TG_INTERNAL_ASSERT(d > ScalarT(0));
460
461
462

    auto t = (ar * ar - br * br + d2) / (2 * d);
    auto h2 = ar * ar - t * t;
463
    TG_INTERNAL_ASSERT(h2 >= ScalarT(0));
464

465
    auto h = sqrt(h2);
466
467
468
469
470
    auto h_by_d = h / d;

    auto p_between = a.center + t / d * (b.center - a.center);

    auto a_to_b = b.center - a.center;
471
    auto a_to_b_swap = tg::vec2(-a_to_b.y, a_to_b.x);
472

Aaron Grabowy's avatar
Aaron Grabowy committed
473
    // imagining circle a on the left side of circle b...
474
475
476
    auto p_above = p_between + h_by_d * a_to_b_swap;
    auto p_below = p_between - h_by_d * a_to_b_swap;

Philip Trettner's avatar
Philip Trettner committed
477
    return pair{p_above, p_below};
478
479
}

Philip Trettner's avatar
Philip Trettner committed
480

481
template <class ScalarT>
Philip Trettner's avatar
Philip Trettner committed
482
[[nodiscard]] constexpr line<3, ScalarT> intersection(plane<3, ScalarT> const& a, plane<3, ScalarT> const& b)
483
484
485
{
    // see http://mathworld.wolfram.com/Plane-PlaneIntersection.html
    auto dir = normalize(cross(a.normal, b.normal));
486
    auto p = pos<3, ScalarT>::zero;
487

488
    if (abs(dir.z) > abs(dir.x)) // solve with p.z = 0
489
    {
490
491
        auto n0 = tg::vec<2, ScalarT>(a.normal.x, b.normal.x);
        auto n1 = tg::vec<2, ScalarT>(a.normal.y, b.normal.y);
492
        auto r = tg::vec<2, ScalarT>(a.dis, b.dis);
493
        auto p2 = inverse(mat<2, 2, ScalarT>::from_cols(n0, n1)) * r;
494
495
496
        p.x = p2.x;
        p.y = p2.y;
    }
497
    else if (abs(dir.y) > abs(dir.x)) // solve with p.y = 0
498
    {
499
500
        auto n0 = tg::vec<2, ScalarT>(a.normal.x, b.normal.x);
        auto n1 = tg::vec<2, ScalarT>(a.normal.z, b.normal.z);
501
        auto r = tg::vec<2, ScalarT>(a.dis, b.dis);
502
        auto p2 = inverse(mat<2, 2, ScalarT>::from_cols(n0, n1)) * r;
503
504
505
506
507
        p.x = p2.x;
        p.z = p2.y;
    }
    else // solve with p.x = 0
    {
508
509
        auto n0 = tg::vec<2, ScalarT>(a.normal.y, b.normal.y);
        auto n1 = tg::vec<2, ScalarT>(a.normal.z, b.normal.z);
510
        auto r = tg::vec<2, ScalarT>(a.dis, b.dis);
511
        auto p2 = inverse(mat<2, 2, ScalarT>::from_cols(n0, n1)) * r;
512
513
514
515
516
517
518
        p.y = p2.x;
        p.z = p2.y;
    }

    return {p, dir};
}

519
520
521
522
523
524
525
526
527
528
529
template <class ScalarT>
[[nodiscard]] constexpr optional<tg::pos<2, ScalarT>> intersection(segment<2, ScalarT> const& seg_0, segment<2, ScalarT> const& seg_1)
{
    /// https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
    auto const denominator
        = (seg_0.pos0.x - seg_0.pos1.x) * (seg_1.pos0.y - seg_1.pos1.y) - (seg_0.pos0.y - seg_0.pos1.y) * (seg_1.pos0.x - seg_1.pos1.x);

    // todo: might want to check == 0 with an epsilon corridor
    // todo: colinear line segments can still intersect in a point or a line segment.
    //       This might require api changes, as either a point or a line segment can be returned!
    //       Possible solution: return a segment where pos0 == pos1
530
    if (denominator == ScalarT(0))
531
532
533
534
535
536
537
538
539
540
541
542
        return {}; // colinear

    auto const numerator = (seg_0.pos0.x - seg_1.pos0.x) * (seg_1.pos0.y - seg_1.pos1.y) - (seg_0.pos0.y - seg_1.pos0.y) * (seg_1.pos0.x - seg_1.pos1.x);
    auto const t = numerator / denominator;
    if (ScalarT(0) <= t && t <= ScalarT(1))
    {
        // intersection
        return seg_0.pos0 + t * (seg_0.pos1 - seg_0.pos0);
    }
    return {};
}

543
template <int D, class ScalarT>
544
[[nodiscard]] constexpr optional<aabb<D, ScalarT>> intersection(aabb<D, ScalarT> const& a, aabb<D, ScalarT> const& b)
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
{
    for (auto i = 0; i < D; ++i)
    {
        if (a.max[i] < b.min[i])
            return {};

        if (b.max[i] < a.min[i])
            return {};
    }

    // overlap!
    aabb<D, ScalarT> res;

    for (auto i = 0; i < D; ++i)
    {
        res.min[i] = max(a.min[i], b.min[i]);
        res.max[i] = min(a.max[i], b.max[i]);
    }

    return {res};
}

567
template <class ScalarT>
Philip Trettner's avatar
Philip Trettner committed
568
[[nodiscard]] constexpr ScalarT intersection_parameter(line<3, ScalarT> const& l, plane<3, ScalarT> const& p)
569
570
571
572
573
{
    return (p.dis - dot(l.pos - pos<3, ScalarT>::zero, p.normal)) / dot(l.dir, p.normal);
}

template <class ScalarT>
Philip Trettner's avatar
Philip Trettner committed
574
[[nodiscard]] constexpr pos<3, ScalarT> intersection(plane<3, ScalarT> const& a, plane<3, ScalarT> const& b, plane<3, ScalarT> const& c)
575
576
577
578
{
    return intersection(intersection(a, b), c);
}

579
template <int D, class ScalarT>
Philip Trettner's avatar
Philip Trettner committed
580
[[nodiscard]] constexpr optional<ScalarT> intersection_parameter(segment<D, ScalarT> const& a, plane<D, ScalarT> const& p)
581
582
{
    auto denom = dot(p.normal, a.pos1 - a.pos0);
583
    if (denom == ScalarT(0))
584
585
        return {};

586
    auto t = (p.dis - dot(p.normal, a.pos0 - tg::pos<D, ScalarT>::zero)) / denom;
587
588
589
590
591
    if (t < 0 || t > 1)
        return {};
    return t;
}

592
template <class ScalarT>
593
[[nodiscard]] constexpr optional<ScalarT> intersection_parameter(ray<3, ScalarT> const& r, triangle<3, ScalarT> const& t)
594
{
595
    auto constexpr eps = 0.000001f;
596

597
598
    auto e1 = t.pos1 - t.pos0;
    auto e2 = t.pos2 - t.pos0;
599

600
    auto pvec = tg::cross(tg::vec<3, ScalarT>(r.dir), e2);
601
    auto det = dot(pvec, e1);
602

603
    if (det < eps)
604
605
        return {};

606
607
608
    auto tvec = r.origin - t.pos0;
    auto u = dot(tvec, pvec);
    if (u < 0.f || u > det)
609
610
        return {};

611
612
613
614
615
616
617
    auto qvec = cross(tvec, e1);
    auto v = dot(r.dir, qvec);
    if (v < 0.f || v + u > det)
        return {};

    auto lambda = (1.f / det) * dot(e2, qvec);
    return (lambda > 0) ? lambda : tg::optional<float>();
618
}
Philip Trettner's avatar
Philip Trettner committed
619
620

template <class ScalarT>
621
[[nodiscard]] constexpr ray_hits<2, ScalarT> intersection_parameter(ray<3, ScalarT> const& r, box<3, ScalarT> const& b)
Philip Trettner's avatar
Philip Trettner committed
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
{
    // see https://github.com/gszauer/GamePhysicsCookbook/blob/master/Code/Geometry3D.cpp

    auto const p = b.center - r.origin;

    // TODO: without normalize
    auto const X = normalize(b.half_extents[0]);
    auto const Y = normalize(b.half_extents[1]);
    auto const Z = normalize(b.half_extents[2]);

    auto f = tg::vec3(dot(X, r.dir), //
                      dot(Y, r.dir), //
                      dot(Z, r.dir));

    auto const e = tg::vec3(dot(X, p), //
                            dot(Y, p), //
                            dot(Z, p));

    auto const size = tg::vec3(length(b.half_extents[0]), //
                               length(b.half_extents[1]), //
                               length(b.half_extents[2]));

    float t[6] = {0, 0, 0, 0, 0, 0};
    for (int i = 0; i < 3; ++i)
    {
647
        if (abs(f[i]) < tg::epsilon<ScalarT> / 1000)
Philip Trettner's avatar
Philip Trettner committed
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
        {
            if (-e[i] - size[i] > 0 || -e[i] + size[i] < 0)
                return {};

            f[i] = tg::epsilon<ScalarT>; // Avoid div by 0!
        }

        t[i * 2 + 0] = (e[i] + size[i]) / f[i]; // tmin[x, y, z]
        t[i * 2 + 1] = (e[i] - size[i]) / f[i]; // tmax[x, y, z]
    }

    auto const tmin = tg::max(tg::max(tg::min(t[0], t[1]), tg::min(t[2], t[3])), tg::min(t[4], t[5]));
    auto const tmax = tg::min(tg::min(tg::max(t[0], t[1]), tg::max(t[2], t[3])), tg::max(t[4], t[5]));

    // if tmax < 0, ray is intersecting AABB
    // but entire AABB is behing it's origin
    if (tmax < 0)
        return {};

    // if tmin > tmax, ray doesn't intersect AABB
    if (tmin > tmax)
        return {};

Philip Trettner's avatar
Philip Trettner committed
671
672
673
674
675
676
677
678
679
680
681
682
683
684
    ScalarT hits[2];

    if (tmin >= 0) // two valid intersections
    {
        hits[0] = tmin;
        hits[1] = tmax;
        return {hits, 2};
    }
    else // one valid intersection
    {
        hits[0] = tmax;
        return {hits, 1};
    }
}
Philip Trettner's avatar
Philip Trettner committed
685

686
template <int D, class ScalarT>
687
[[nodiscard]] constexpr bool intersects(sphere<D, ScalarT> const& a, aabb<D, ScalarT> const& b)
Philip Trettner's avatar
Philip Trettner committed
688
{
689
690
691
    auto const b_min = b.min;
    auto const b_max = b.max;
    auto const c = a.center;
692
693
694
695
    auto const clamped_sqr = [](ScalarT v) {
        v = tg::max(ScalarT(0), v);
        return v * v;
    };
Philip Trettner's avatar
Philip Trettner committed
696

697
698
699
    auto d_min = ScalarT(0);

    if constexpr (D >= 1)
Philip Trettner's avatar
Philip Trettner committed
700
    {
701
702
        d_min += clamped_sqr(b_min.x - c.x);
        d_min += clamped_sqr(c.x - b_max.x);
Philip Trettner's avatar
Philip Trettner committed
703
704
    }

705
706
707
708
709
    if constexpr (D >= 2)
    {
        d_min += clamped_sqr(b_min.y - c.y);
        d_min += clamped_sqr(c.y - b_max.y);
    }
Philip Trettner's avatar
Philip Trettner committed
710

711
712
713
714
715
    if constexpr (D >= 3)
    {
        d_min += clamped_sqr(b_min.z - c.z);
        d_min += clamped_sqr(c.z - b_max.z);
    }
Philip Trettner's avatar
Philip Trettner committed
716

717
718
719
720
721
    if constexpr (D >= 4)
    {
        d_min += clamped_sqr(b_min.w - c.w);
        d_min += clamped_sqr(c.w - b_max.w);
    }
Philip Trettner's avatar
Philip Trettner committed
722

723
    return d_min <= a.radius * a.radius;
Philip Trettner's avatar
Philip Trettner committed
724
}
725
template <int D, class ScalarT>
726
[[nodiscard]] constexpr bool intersects(aabb<D, ScalarT> const& a, sphere<D, ScalarT> const& b)
727
728
729
730
{
    return intersects(b, a);
}

Philip Trettner's avatar
Philip Trettner committed
731
732
733
734
735
736
737
738
template <int D, class ScalarT>
[[nodiscard]] constexpr optional<segment<D, ScalarT>> intersection(segment<D, ScalarT> const& a, sphere<D, ScalarT> const& b)
{
    static_assert(always_false<ScalarT>, "not implemented");
    (void)a;
    (void)b;
    return {}; // TODO
}
Philip Trettner's avatar
merge    
Philip Trettner committed
739

Philip Trettner's avatar
Philip Trettner committed
740
741
742
743
744
745
template <int D, class ScalarT>
[[nodiscard]] constexpr optional<segment<D, ScalarT>> intersection(sphere<D, ScalarT> const& b, segment<D, ScalarT> const& a)
{
    return intersection(b, a);
}

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
template <class ScalarT>
[[nodiscard]] constexpr bool intersects(triangle<2, ScalarT> const& a, aabb<2, ScalarT> const& b)
{
    auto p0 = a.pos0;
    auto p1 = a.pos1;
    auto p2 = a.pos2;

    auto bb_t = aabb_of(p0, p1, p2);
    if (!intersects(bb_t, b))
        return false;

    if (contains(b, p0) || contains(b, p1) || contains(b, p2))
        return true;

    pos<2, ScalarT> aabb_pts[] = {
        {b.min.x, b.min.y}, //
        {b.min.x, b.max.y}, //
        {b.max.x, b.min.y}, //
        {b.max.x, b.max.y}, //
    };

    auto const is_separate = [&](pos<2, ScalarT> pa, vec<2, ScalarT> n, pos<2, ScalarT> pb) {
        auto da = dot(n, pa);
        auto db = dot(n, pb);

        // TODO: faster
        auto a_min = min(da, db);
        auto a_max = max(da, db);

        auto b_min = dot(n, aabb_pts[0]);
        auto b_max = b_min;
        for (auto i = 1; i < 4; ++i)
        {
            auto d = dot(n, aabb_pts[i]);
            b_min = min(b_min, d);
            b_max = max(b_max, d);
        }

        if (b_max < a_min || b_min > a_max)
            return true;

        return false;
    };

    if (is_separate(p0, perpendicular(p1 - p0), p2))
        return false;
    if (is_separate(p1, perpendicular(p2 - p1), p0))
        return false;
    if (is_separate(p2, perpendicular(p0 - p2), p1))
        return false;

    return true;
}
template <class ScalarT>
[[nodiscard]] constexpr bool intersects(aabb<2, ScalarT> const& a, triangle<2, ScalarT> const& b)
{
    return intersects(b, a);
}

805
} // namespace tg