VisuTwin Canvas
C++ 3D Engine — Metal Backend
Loading...
Searching...
No Matches
tri.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2025-2026 Arnis Lektauers
3//
4// Created by Arnis Lektauers on 13.02.2026.
5//
6#include "tri.h"
7
8#include <sstream>
9
10namespace visutwin::canvas
11{
12 namespace
13 {
14 constexpr float kEpsilon = 1e-6f;
15 }
16
17 Tri::Tri() : _v0(0.0f), _v1(0.0f), _v2(0.0f)
18 {
19 }
20
21 Tri::Tri(const Vector3& v0, const Vector3& v1, const Vector3& v2) : _v0(v0), _v1(v1), _v2(v2)
22 {
23 }
24
25 Tri& Tri::set(const Vector3& v0, const Vector3& v1, const Vector3& v2)
26 {
27 _v0 = v0;
28 _v1 = v1;
29 _v2 = v2;
30 return *this;
31 }
32
33 bool Tri::intersectsRay(const Ray& ray, Vector3* point) const
34 {
35 const Vector3 e1 = _v1 - _v0;
36 const Vector3 e2 = _v2 - _v0;
37 const Vector3 h = ray.direction().cross(e2);
38 const float a = e1.dot(h);
39 if (a > -kEpsilon && a < kEpsilon) {
40 return false;
41 }
42
43 const float f = 1.0f / a;
44 const Vector3 s = ray.origin() - _v0;
45 const float u = f * s.dot(h);
46 if (u < 0.0f || u > 1.0f) {
47 return false;
48 }
49
50 const Vector3 q = s.cross(e1);
51 const float v = f * ray.direction().dot(q);
52 if (v < 0.0f || u + v > 1.0f) {
53 return false;
54 }
55
56 const float t = f * e2.dot(q);
57 if (t > kEpsilon) {
58 if (point) {
59 *point = ray.origin() + ray.direction() * t;
60 }
61 return true;
62 }
63 return false;
64 }
65
66 std::string Tri::toString() const
67 {
68 std::ostringstream stream;
69 stream << "[[" << _v0.getX() << ", " << _v0.getY() << ", " << _v0.getZ()
70 << "], [" << _v1.getX() << ", " << _v1.getY() << ", " << _v1.getZ()
71 << "], [" << _v2.getX() << ", " << _v2.getY() << ", " << _v2.getZ() << "]]";
72 return stream.str();
73 }
74}
75
Infinite ray defined by origin and direction for raycasting and picking.
Definition ray.h:14
const Vector3 & origin() const
Definition ray.h:19
const Vector3 & direction() const
Definition ray.h:21
bool intersectsRay(const Ray &ray, Vector3 *point=nullptr) const
Definition tri.cpp:33
const Vector3 & v2() const
Definition tri.h:22
std::string toString() const
Definition tri.cpp:66
const Vector3 & v0() const
Definition tri.h:18
Tri & set(const Vector3 &v0, const Vector3 &v1, const Vector3 &v2)
Definition tri.cpp:25
const Vector3 & v1() const
Definition tri.h:20
3D vector for positions, directions, and normals with multi-backend SIMD acceleration.
Definition vector3.h:29
Vector3 cross(const Vector3 &other) const
float dot(const Vector3 &other) const