Easy3D 3.0.0
Loading...
Searching...
No Matches
Tutorial_406_CollisionDetection

Real-time collision detection between two meshes, with intersecting faces highlighted.

Overview

This tutorial loads two meshes (a bunny and a mannequin), animates the bunny, and continuously reports which faces of the two meshes intersect, painting them red. Pausing the animation lets the user drag the bunny around (as in Tutorial_404_ObjectManipulation) and watch the contact regions update in real time. Unlike the other 4xx tutorials, all scene setup happens in the viewer's constructor, so main() only creates the viewer and runs it.

The technique

Testing every face of one mesh against every face of the other is O(n*m) — far too slow for interactive rates on large meshes. The standard solution is a bounding volume hierarchy (BVH): each mesh is preprocessed once into a tree of axis-aligned bounding boxes (AABBs), with the actual triangles at the leaves. A collision query then walks both trees simultaneously, discarding whole branches whose boxes do not overlap, and only performs exact triangle-triangle intersection tests on the few leaf pairs that survive. Easy3D's Collider wraps the Opcode library (Pierre Terdiman), which achieves real-time performance even for large meshes. Crucially, the trees are built in each mesh's local space and the current transformation matrices are passed to every detect() call — so moving or rotating a mesh never requires rebuilding the trees. The demo visualizes the result by storing a per-face color property: all faces start in the mesh's base color, and every reported intersecting face pair is painted red.

Easy3D API

Running it

On start, an animation rotates the bunny and highlights intersecting faces in red. Press 'space' (or F2) to pause/resume. While paused, Alt + left-drag rotates the bunny and Alt + right-drag translates it; collisions are recomputed during every drag.

1
27#include "viewer.h"
28#include <easy3d/util/initializer.h>
29
83using namespace easy3d;
84
85int main(int argc, char **argv) {
86 // initialize Easy3D.
87 initialize();
88
89 TutorialCollisionDetection viewer(EXAMPLE_TITLE);
90
91 // run the viewer
92 return viewer.run();
93}
Definition collider.cpp:182

The header file of the viewer class:

1
27#ifndef EASY3D_TUTORIAL_COLLISION_DETECTION_H
28#define EASY3D_TUTORIAL_COLLISION_DETECTION_H
29
30#include <easy3d/viewer/viewer.h>
31#include <chrono>
32
33// This class demonstrates how to detect intersecting faces of two meshes.
34
35namespace easy3d {
36 class Model;
37 class SurfaceMesh;
38 class Collider;
39} // namespace easy3d
40
42class TutorialCollisionDetection : public easy3d::Viewer {
43public:
44 explicit TutorialCollisionDetection(const std::string &title);
45 void clear_scene() override;
46 bool delete_model(easy3d::Model *model) override;
47 ~TutorialCollisionDetection() override;
48
49protected:
50 // Rebuild the collision trees for the two currently attached triangle meshes.
51 void initialize_collision();
52 bool mouse_press_event(int x, int y, int button, int modifiers) override;
53 bool mouse_release_event(int x, int y, int button, int modifiers) override;
54 bool focus_event(bool focused) override;
55 void post_resize(int width, int height) override;
56 bool mouse_drag_event(int x, int y, int dx, int dy, int button, int modifiers) override;
57 bool key_press_event(int key, int modifiers) override;
58
59 void detect();
60
61private:
62 bool collision_models_valid() const;
63 void end_model_drag();
64 void retire_collision();
65 void advance();
66 std::unique_ptr<easy3d::Collider> collider_;
67 std::weak_ptr<easy3d::SurfaceMesh> collision_models_[2];
68 std::weak_ptr<easy3d::SurfaceMesh> drag_model_;
69 std::chrono::steady_clock::time_point next_tick_;
70 float angle_ = 0;
71
72 easy3d::vec3 model0_color_;
73 easy3d::vec3 model1_color_;
74};
75
76#endif // EASY3D_TUTORIAL_COLLISION_DETECTION_H
Base class for spatial models with optional rendering and manipulation state.
Definition model.h:53
The default viewer implementation for both OpenGL and Vulkan backends.
Definition viewer.h:143
bool delete_model(Model *model) override
Delete a model. The memory of the model will be released and its existing drawables will also be dele...
Definition viewer.cpp:1344
void clear_scene() override
Delete all visual contents of the viewer (all models and drawables).
Definition viewer.cpp:1381

The source file of the viewer class:

1
27#include "viewer.h"
28#include <algorithm>
29#include <stdexcept>
30
31#include <easy3d/renderer/drawable_triangles.h>
32#include <easy3d/renderer/manipulator.h>
33#include <easy3d/renderer/manipulated_frame.h>
34#include <easy3d/renderer/renderer.h>
35#include <easy3d/util/resource.h>
36#include <easy3d/algo/collider.h>
37
38using namespace easy3d;
39
40// \cond
41
42TutorialCollisionDetection::TutorialCollisionDetection(const std::string &title)
43 : Viewer(title), model0_color_(.8f, 1, .8f), model1_color_(.8f, .8f, 1) {
44 manual_ =
45 "--------------------- Collision Viewer usage ----------------------\n"
46 "On start, you will see an animation with highlighted intersecting \n"
47 "faces. Press 'space' to pause/resume the animation. \n"
48 "When the animation is paused, you can manipulate the bunny model \n"
49 "(using your mouse) to perform real-time collection detection: \n"
50 " - Alt + left button: rotate bunny model \n"
51 " - Alt + right button: translate bunny model \n"
52 "------------------------------------------------------------------ \n";
53 hint_ =
54 "Press 'space' to pause/resume animation\n"
55 "When paused:\n"
56 " - Alt + left button: rotate bunny model\n"
57 " - Alt + right button: translate bunny model";
58 add_model(resource::directory() + "/data/bunny.ply");
59 add_model(resource::directory() + "/data/mannequin.ply");
60 animation_func_ = [this](Viewer *) {
61 advance();
62 return true;
63 };
64 initialize_collision();
65}
66TutorialCollisionDetection::~TutorialCollisionDetection() {
67 set_animation(false);
68 animation_func_ = {};
69 end_model_drag();
70 collider_.reset();
71}
72bool TutorialCollisionDetection::collision_models_valid() const {
73 if (!collider_ || models().size() != 2)
74 return false;
75 for (unsigned i = 0; i < 2; ++i) {
76 const auto model = collision_models_[i].lock();
77 if (!model || !model->renderer() || !model->manipulator() ||
78 std::find(models().begin(), models().end(), model) == models().end())
79 return false;
80 }
81 return true;
82}
83void TutorialCollisionDetection::initialize_collision() {
84 retire_collision();
85 if (models().size() != 2)
86 throw std::invalid_argument("collision example requires two triangle meshes");
87 auto first = std::dynamic_pointer_cast<SurfaceMesh>(models()[0]);
88 auto second = std::dynamic_pointer_cast<SurfaceMesh>(models()[1]);
89 if (!first || !second || first->n_faces() == 0 || second->n_faces() == 0 || !first->is_triangle_mesh() ||
90 !second->is_triangle_mesh())
91 throw std::invalid_argument("collision example requires two nonempty triangle meshes");
92 for (const auto &mesh : {first, second})
93 if (!mesh->manipulator())
94 mesh->set_manipulator(std::make_shared<Manipulator>(mesh.get()));
95 first->add_face_property<vec3>("face_color", model0_color_);
96 second->add_face_property<vec3>("face_color", model1_color_);
97 for (const auto &mesh : {first, second})
98 mesh->renderer()->get_triangles_drawable("faces")->set_coloring(State::COLOR_PROPERTY, State::FACE,
99 "face_color");
100 collider_.reset(new Collider(first.get(), second.get()));
101 collision_models_[0] = first;
102 collision_models_[1] = second;
103 angle_ = 0;
104 detect();
105 next_tick_ = std::chrono::steady_clock::now() + std::chrono::milliseconds(50);
106 set_animation(true);
107}
108void TutorialCollisionDetection::end_model_drag() {
109 if (auto model = drag_model_.lock())
110 if (model->manipulator())
111 model->manipulator()->frame()->action_end();
112 drag_model_.reset();
113}
114void TutorialCollisionDetection::retire_collision() {
115 set_animation(false);
116 end_model_drag();
117 // Retired pairs must not leave red contacts on a remaining/retained mesh.
118 for (unsigned i = 0; i < 2; ++i)
119 if (const auto mesh = collision_models_[i].lock()) {
120 auto colors = mesh->get_face_property<vec3>("face_color");
121 if (colors) {
122 colors.vector().assign(mesh->n_faces(), i == 0 ? model0_color_ : model1_color_);
123 if (mesh->renderer())
124 mesh->renderer()->update();
125 }
126 }
127 collider_.reset();
128 collision_models_[0].reset();
129 collision_models_[1].reset();
130}
131void TutorialCollisionDetection::advance() {
132 if (!collision_models_valid()) {
133 retire_collision();
134 return;
135 }
136 const auto now = std::chrono::steady_clock::now();
137 if (now < next_tick_)
138 return;
139 next_tick_ = now + std::chrono::milliseconds(50); // no catch-up burst after a pause/minimize
140 const auto mesh = collision_models_[0].lock();
141 angle_ += .0001f;
142 const auto pose = mat4::rotation(vec3(0, 0, 1), angle_) * mesh->manipulator()->frame()->matrix();
143 mesh->manipulator()->frame()->set_from_matrix(pose);
144 detect();
145}
146void TutorialCollisionDetection::detect() {
147 if (!collision_models_valid()) {
148 retire_collision();
149 return;
150 }
151 const auto first = collision_models_[0].lock();
152 const auto second = collision_models_[1].lock();
153 const auto pairs = collider_->detect(first->manipulator()->matrix(), second->manipulator()->matrix());
154 auto colors0 = first->get_face_property<vec3>("face_color");
155 auto colors1 = second->get_face_property<vec3>("face_color");
156 colors0.vector().assign(first->n_faces(), model0_color_);
157 colors1.vector().assign(second->n_faces(), model1_color_);
158 for (const auto &pair : pairs) {
159 colors0[pair.first] = vec3(1, 0, 0);
160 colors1[pair.second] = vec3(1, 0, 0);
161 }
162 first->renderer()->update();
163 second->renderer()->update();
164 update();
165}
166bool TutorialCollisionDetection::key_press_event(int key, int modifiers) {
167 if ((key == KEY_SPACE || key == KEY_F2) && modifiers == 0) {
168 end_model_drag();
169 if (is_animating())
170 set_animation(false);
171 else if (collision_models_valid()) {
172 next_tick_ = std::chrono::steady_clock::now() + std::chrono::milliseconds(50);
173 set_animation(true);
174 }
175 return true;
176 }
177 return Viewer::key_press_event(key, modifiers);
178}
179bool TutorialCollisionDetection::mouse_press_event(int x, int y, int button, int modifiers) {
180 end_model_drag();
181 if (modifiers == MODIF_ALT && !is_animating() && collision_models_valid() &&
182 (button == BUTTON_LEFT || button == BUTTON_RIGHT)) {
183 const auto mesh = collision_models_[0].lock();
184 mesh->manipulator()->frame()->action_start();
185 drag_model_ = mesh;
186 return true;
187 }
188 return Viewer::mouse_press_event(x, y, button, modifiers);
189}
190bool TutorialCollisionDetection::mouse_drag_event(int x, int y, int dx, int dy, int button, int modifiers) {
191 const auto mesh = drag_model_.lock();
192 if (modifiers == MODIF_ALT && !is_animating() && collision_models_valid() && mesh) {
193 if (button == BUTTON_LEFT)
194 mesh->manipulator()->frame()->action_rotate(x, y, dx, dy, camera(), ManipulatedFrame::NONE);
195 else if (button == BUTTON_RIGHT)
196 mesh->manipulator()->frame()->action_translate(x, y, dx, dy, camera(), ManipulatedFrame::NONE);
197 else
198 return false;
199 detect();
200 return true;
201 }
202 return Viewer::mouse_drag_event(x, y, dx, dy, button, modifiers);
203}
204bool TutorialCollisionDetection::mouse_release_event(int x, int y, int button, int modifiers) {
205 end_model_drag();
206 return Viewer::mouse_release_event(x, y, button, modifiers);
207}
208bool TutorialCollisionDetection::focus_event(bool focused) {
209 if (!focused)
210 end_model_drag();
211 return false;
212}
213void TutorialCollisionDetection::post_resize(int, int) {
214 end_model_drag();
215}
216bool TutorialCollisionDetection::delete_model(Model *model) {
217 if (collision_models_[0].lock().get() == model || collision_models_[1].lock().get() == model) {
218 retire_collision();
219 }
220 return Viewer::delete_model(model);
221}
222void TutorialCollisionDetection::clear_scene() {
223 retire_collision();
224 Viewer::clear_scene();
225}
226
227// \endcond
Efficient collision detection.
Definition collider.h:51
See also
Collider, SurfaceMesh, Manipulator, Tutorial_404_ObjectManipulation