VisuTwin Canvas
C++ 3D Engine — Metal Backend
Loading...
Searching...
No Matches
boundingSphere.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 "boundingSphere.h"
7
8#include <cmath>
9
10namespace visutwin::canvas
11{
12 BoundingSphere::BoundingSphere() : _center(0.0f), _radius(0.5f)
13 {
14 }
15
16 BoundingSphere::BoundingSphere(const Vector3& center, const float radius) : _center(center), _radius(radius)
17 {
18 }
19
21 {
22 _center = src._center;
23 _radius = src._radius;
24 return *this;
25 }
26
28 {
29 return BoundingSphere(_center, _radius);
30 }
31
32 bool BoundingSphere::containsPoint(const Vector3& point) const
33 {
34 const Vector3 delta = point - _center;
35 return delta.lengthSquared() < _radius * _radius;
36 }
37
38 bool BoundingSphere::intersectsRay(const Ray& ray, Vector3* point) const
39 {
40 const Vector3 m = ray.origin() - _center;
41 const Vector3 rayDirection = ray.direction().normalized();
42 const float b = m.dot(rayDirection);
43 const float c = m.dot(m) - _radius * _radius;
44
45 if (c > 0.0f && b > 0.0f) {
46 return false;
47 }
48
49 const float discr = b * b - c;
50 if (discr < 0.0f) {
51 return false;
52 }
53
54 const float t = std::abs(-b - std::sqrt(discr));
55 if (point) {
56 *point = ray.origin() + rayDirection * t;
57 }
58 return true;
59 }
60
62 {
63 const Vector3 delta = sphere._center - _center;
64 const float totalRadius = sphere._radius + _radius;
65 return delta.lengthSquared() <= totalRadius * totalRadius;
66 }
67}
68
const Vector3 & center() const
bool intersectsRay(const Ray &ray, Vector3 *point=nullptr) const
bool containsPoint(const Vector3 &point) const
bool intersectsBoundingSphere(const BoundingSphere &sphere) const
BoundingSphere & copy(const BoundingSphere &src)
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
3D vector for positions, directions, and normals with multi-backend SIMD acceleration.
Definition vector3.h:29
Vector3 normalized() const
float dot(const Vector3 &other) const
float lengthSquared() const
Definition vector3.h:233