Easy3D 3.0.0
Loading...
Searching...
No Matches
Tutorial_403_PointSelection

Selecting a subset of a point cloud by sketching a rectangle or a lasso with the mouse.

Overview

This tutorial implements region selection on a point cloud: while holding Shift, the user drags out a rectangle (key 'R') or a free-form lasso (key 'L'), and every point projecting inside the region becomes selected (colored red). Dragging with the right button instead deselects. Where Tutorial_401/402 pick a single element under the cursor, this tutorial selects many elements at once — the standard "marquee/lasso" interaction of 3D editors.

The technique

Region selection asks a different question than picking: not "what is the nearest element at this pixel?" but "which elements project inside this 2D region?". Note that this is a through-selection: points hidden behind other points are still selected, because selection is defined by projection, not by visibility. Testing every point against the polygon on the CPU would be O(n) per gesture with a serial point-in-polygon test; instead Easy3D evaluates all points on the GPU in parallel (a vertex-shader/compute pass): each point is transformed by the model-view-projection matrix, tested against the region and the clipping planes, and the answer is packed into a bitmask — one bit per point, 32 points per 32-bit word — so only a compact result is read back. The request carries the current selection as an input bitmask so a deselect gesture can clear bits, and the returned words become the new selection. While the gesture is in progress, the sketched region is drawn as a screen-space overlay: the lasso interior is triangulated with the Tessellator (a polygon may be concave or self-overlapping, so a simple fan would not do) and the outline is built from thin quads.

Easy3D API

Running it

Hold Shift and drag with the left button to select points, or with the right button to deselect. Press 'L' for lasso mode (default), 'R' for rectangle mode, and Escape to cancel an ongoing gesture. Selected points turn red.

1
27#include "viewer.h"
28#include <easy3d/core/model.h>
29#include <easy3d/renderer/drawable_points.h>
30#include <easy3d/renderer/renderer.h>
31#include <easy3d/util/resource.h>
32#include <easy3d/util/initializer.h>
33
89using namespace easy3d;
90
91int main(int argc, char **argv) {
92 // Bootstrap Easy3D (logging, resource directory, ...). Must come first.
93 initialize();
94
95 // A point cloud stored in Easy3D's binary format.
96 const std::string file = resource::directory() + "/data/polyhedron.bin";
97
98 // Our custom viewer: a Viewer subclass that turns Shift+drag into region selection.
99 TutorialPointSelection viewer(EXAMPLE_TITLE);
100
101 // Load the cloud; the second argument (true) centers and scales it to fit the scene.
102 auto model = viewer.add_model(file, true);
103 if (!model) {
104 std::cerr << "failed to load model. Please make sure the file exists and format is correct" << std::endl;
105 return EXIT_FAILURE;
106 }
107
108 // "vertices" is the standard points drawable of a point cloud. Enlarging the points
109 // makes the selection feedback (red points) easier to see.
110 auto drawable = model->renderer()->get_points_drawable("vertices");
111 // drawable->set_impostor_type(PointsDrawable::SPHERE);
112 drawable->set_point_size(3.0f);
113
114 // Enter the interactive loop (returns when the window is closed).
115 return viewer.run();
116}
Definition collider.cpp:182

The header file of the viewer class:

1
27#ifndef EASY3D_TUTORIAL_POINT_SELECTION_H
28#define EASY3D_TUTORIAL_POINT_SELECTION_H
29
30#include <easy3d/viewer/viewer.h>
31
32// Forward declaration only: the header just needs the PointCloud name, so we avoid pulling
33// its full definition into every includer.
34namespace easy3d {
35 class PointCloud;
36}
37
48class TutorialPointSelection : public easy3d::Viewer {
49public:
50 // Installs the usage manual and the on-screen hint.
51 explicit TutorialPointSelection(const std::string &title = "PointSelection");
52
53protected:
54 // Starts a selection gesture on Shift + left/right press over the current point cloud.
55 bool mouse_press_event(int x, int y, int button, int modifiers) override;
56 // On release, runs the GPU region selection and applies the resulting colors.
57 bool mouse_release_event(int x, int y, int button, int modifiers) override;
58 // Extends the sketched region while the gesture is active.
59 bool mouse_drag_event(int x, int y, int dx, int dy, int button, int modifiers) override;
60 // 'L'/'R' switch lasso/rectangle mode; Escape cancels an ongoing gesture.
61 bool key_press_event(int key, int modifiers) override;
62 // Losing window focus aborts the gesture (the mouse may be released elsewhere).
63 bool focus_event(bool focused) override;
64 // A resize invalidates the framebuffer-pixel polygon, so abort the gesture.
65 void post_resize(int width, int height) override;
66 // Builds/refreshes the overlay visualizing the region being sketched.
67 void pre_draw() override;
68
69private:
70 // Appends the cursor position to the region (or recomputes the rectangle corners).
71 void extend(int x, int y);
72 // Resets all gesture state and clears the overlay.
73 void cancel();
74 // Gesture state: active_ = a gesture is in progress; rectangle_ = rectangle mode ('R')
75 // vs. lasso mode ('L', default); dirty_ = the region changed and the overlay must be rebuilt.
76 bool active_ = false, rectangle_ = false, dirty_ = true;
77 int button_ = -1;
78 // The sketched region in framebuffer pixels (top-left origin), sent to the GPU query.
79 std::vector<easy3d::vec2> polygon_;
80 // Non-owning handle to the cloud being selected; weak so a deleted model cannot dangle.
81 std::weak_ptr<easy3d::Model> target_;
82 // Cached overlay geometry: the translucent interior fill and the opaque outline.
83 std::shared_ptr<const easy3d::graphics::Geometry> fill_, edge_;
84};
85
86#endif // EASY3D_TUTORIAL_POINT_SELECTION_H
The default viewer implementation for both OpenGL and Vulkan backends.
Definition viewer.h:143

The source file of the viewer class:

1
27#include "viewer.h"
28
29#include <easy3d/core/point_cloud.h>
30#include <easy3d/renderer/camera.h>
31#include <easy3d/renderer/renderer.h>
32#include <easy3d/renderer/drawable_points.h>
33#include <easy3d/algo/tessellator.h>
34#include <algorithm>
35#include <limits>
36
37using namespace easy3d;
38
39// \cond
40TutorialPointSelection::TutorialPointSelection(const std::string &title) : Viewer(title) {
41 // manual_ is the full help text (shown on demand); hint_ is the short HUD reminder.
42 manual_ =
43 "-------------- Point selection usage --------------\n"
44 "Shift + left/right drag: select/deselect points\n"
45 "L: lasso mode; R: rectangle mode; Escape: cancel\n"
46 "---------------------------------------------------\n";
47 hint_ =
48 "Pressing Shift, drag the mouse to select (left) or deselect (right) points\n"
49 "\tL: lasso mode (default)\n"
50 "\tR: rectangle mode";
51}
52
53// Shift + left/right press starts a selection gesture — but only if the current model is a
54// point cloud (region selection is defined on points here). Other presses go to the base
55// Viewer so camera navigation still works.
56bool TutorialPointSelection::mouse_press_event(int x, int y, int button, int modifiers) {
57 if ((modifiers & MODIF_SHIFT) && (button == BUTTON_LEFT || button == BUTTON_RIGHT)) {
58 cancel();
59 for (const auto &model : models())
60 if (model.get() == current_model() && dynamic_cast<easy3d::PointCloud *>(model.get())) {
61 target_ = model;
62 active_ = true;
63 button_ = button; // remember: left = select, right = deselect
64 // The region is stored in framebuffer pixels (top-left origin) because that
65 // is what the GPU selection query expects. Mouse events arrive in logical
66 // screen units, which differ by the DPI scaling factor on HiDPI displays.
67 int fw = 0, fh = 0;
68 framebuffer_size(fw, fh);
69 polygon_.push_back(easy3d::vec2(float(x) * fw / camera()->screen_width(),
70 float(y) * fh / camera()->screen_height()));
71 break;
72 }
73 return true;
74 }
75 return Viewer::mouse_press_event(x, y, button, modifiers);
76}
77
78// While the gesture is active, dragging extends the region instead of moving the camera.
79bool TutorialPointSelection::mouse_drag_event(int x, int y, int dx, int dy, int button, int modifiers) {
80 if (active_) {
81 extend(x, y);
82 return true;
83 }
84 return Viewer::mouse_drag_event(x, y, dx, dy, button, modifiers);
85}
86
87// Releasing the starting button finishes the gesture: run the GPU region-selection query
88// and apply the result as per-point colors.
89bool TutorialPointSelection::mouse_release_event(int x, int y, int button, int modifiers) {
90 if (!active_)
91 return Viewer::mouse_release_event(x, y, button, modifiers);
92 // Ignore releases of other buttons (e.g. a stray middle click during the gesture).
93 if (button != button_)
94 return true;
95 extend(x, y);
96 // The target is held weakly: verify the model still exists and is still in the scene.
97 const auto model = target_.lock();
98 if (model && std::find(models().begin(), models().end(), model) != models().end()) {
99 auto *cloud = dynamic_cast<easy3d::PointCloud *>(model.get());
100 auto drawable = cloud->renderer()->get_points_drawable("vertices");
101 // Only select what the user can actually see rendered.
102 if (drawable && cloud->renderer()->is_visible() && drawable->is_visible()) {
103 // Assemble the GPU selection request.
105 int fw = 0, fh = 0;
106 framebuffer_size(fw, fh);
107 request.width = fw;
108 request.height = fh;
109 request.polygon = polygon_;
110 // point_resource() is the immutable position snapshot shared by rendering and
111 // selection, so the query tests exactly the points that are drawn.
112 request.points = point_resource(drawable);
113 // The result is a bitmask: one bit per point, 32 points per 32-bit word.
114 request.words.resize((size_t(request.points->source_count()) + 31) / 32, 0);
115 // Seed the input mask with the current selection so a deselect gesture clears
116 // the right bits (and previously selected points outside the region survive).
117 auto selected = cloud->vertex_property<bool>("v:select");
118 for (auto v : cloud->vertices())
119 if (selected[v])
120 request.words[v.idx() >> 5] |= 1u << (v.idx() & 31);
121 // Points must be projected exactly as they are rendered: camera MVP combined
122 // with the drawable's own manipulation transform.
123 const auto transform = drawable->manipulated_matrix();
124 request.model_view_projection = camera()->model_view_projection_matrix() * transform;
125 // Clipping planes are given in world space; the query tests points in model
126 // space, so convert each plane p by transpose(T): dot(p, T*q) == dot(T^T*p, q).
127 for (const auto &plane : clipping_planes())
128 request.local_clipping_planes.push_back(transpose(transform) * plane);
129 request.deselect = button_ == BUTTON_RIGHT;
130 // The GPU projects every point in parallel, tests it against the region, and
131 // returns the updated bitmask. This is a through-selection: occluded points
132 // inside the region are selected too.
133 const auto words = select_points(request);
134 // Unpack the result: selected points turn red, the others keep the drawable color.
135 auto colors = cloud->vertex_property<easy3d::vec3>("v:color");
136 for (auto v : cloud->vertices()) {
137 selected[v] = (words[v.idx() >> 5] & (1u << (v.idx() & 31))) != 0;
138 colors[v] = selected[v] ? easy3d::vec3(1, 0, 0) : drawable->color().xyz();
139 }
140 // Tell the drawable to source colors from the per-vertex property and update its snapshot.
141 drawable->set_coloring(easy3d::State::COLOR_PROPERTY, easy3d::State::VERTEX, "v:color");
142 drawable->update_color_buffer(colors.vector());
143 }
144 }
145 cancel();
146 return true;
147}
148
149// Mode switching and cancellation. Unhandled keys go to the base Viewer.
150bool TutorialPointSelection::key_press_event(int key, int modifiers) {
151 if (key == KEY_ESCAPE && active_) {
152 cancel();
153 return true;
154 }
155 if (modifiers == 0 && (key == KEY_R || key == KEY_L)) {
156 cancel();
157 rectangle_ = key == KEY_R;
158 return true;
159 }
160 return Viewer::key_press_event(key, modifiers);
161}
162
163// If the window loses focus mid-gesture, the button release may arrive elsewhere; abort so
164// the gesture does not get stuck. Returning false leaves focus handling to the base class.
165bool TutorialPointSelection::focus_event(bool focused) {
166 if (!focused)
167 cancel();
168 return false;
169}
170
171// The polygon is stored in framebuffer pixels, which change meaning after a resize.
172void TutorialPointSelection::post_resize(int, int) {
173 cancel();
174}
175
176// Draws the region being sketched as a screen-space overlay: a translucent red fill plus an
177// opaque red outline. The geometry is cached and only rebuilt when the region changes.
178void TutorialPointSelection::pre_draw() {
179 Viewer::pre_draw();
180 // No overlay when idle or when the region is still degenerate (fewer than 3 corners).
181 if (!active_ || polygon_.size() < 3) {
182 set_overlays({});
183 return;
184 }
185 if (dirty_) {
186 // Triangulate the (possibly concave) lasso interior. A simple triangle fan would
187 // fail for concave polygons, so we use the Tessellator, which handles arbitrary
188 // simple polygons. The normal (0,0,1) fixes the contour orientation in screen space.
190 tess.begin_polygon(easy3d::vec3(0, 0, 1));
191 tess.begin_contour();
192 for (const auto &p : polygon_)
193 tess.add_vertex(easy3d::vec3(p, 0));
194 tess.end_contour();
195 tess.end_polygon();
196 // Flatten the tessellated triangles into a plain vertex list for the overlay.
197 std::vector<easy3d::graphics::Vertex> fill, edge;
198 for (const auto &triangle : tess.elements())
199 for (auto index : triangle) {
200 const auto *p = tess.vertices()[index]->data();
202 v.position = easy3d::vec3(float(p[0]), float(p[1]), 0);
203 fill.push_back(v);
204 }
205 // Build the outline as 1.5-pixel screen-space quads (two triangles per segment).
206 for (size_t i = 0, j = polygon_.size() - 1; i < polygon_.size(); j = i++) {
207 const auto a = polygon_[j], b = polygon_[i], d = b - a;
208 if (d.length2() < 1e-6f)
209 continue; // skip zero-length segments (duplicate cursor samples)
210 // Perpendicular offset of half the line width (0.75 px on each side).
211 const auto n = easy3d::vec2(-d.y, d.x) * (.75f / d.length());
212 const easy3d::vec2 corners[] = {a - n, b - n, b + n, a + n};
213 for (unsigned k : {0u, 1u, 2u, 0u, 2u, 3u}) {
215 v.position = easy3d::vec3(corners[k], 0);
216 edge.push_back(v);
217 }
218 }
219 fill_ = fill.empty() ? nullptr : std::make_shared<easy3d::graphics::Geometry>(std::move(fill));
220 edge_ = edge.empty() ? nullptr : std::make_shared<easy3d::graphics::Geometry>(std::move(edge));
221 dirty_ = false;
222 }
223 // Submit the overlay draw commands. screen_space_projection() maps framebuffer-pixel
224 // coordinates directly to the screen, so the geometry stays glued to the cursor region.
225 int fw = 0, fh = 0;
226 framebuffer_size(fw, fh);
227 std::vector<easy3d::graphics::DrawCommand> overlays;
228 for (unsigned i = 0; i < 2; ++i) {
230 draw.geometry = i ? edge_ : fill_;
231 if (!draw.geometry)
232 continue;
233 draw.model_view_projection = easy3d::graphics::screen_space_projection(fw, fh);
234 // Translucent fill (alpha 0.2) so the points underneath stay visible; solid outline.
235 draw.color = easy3d::vec4(1, 0, 0, i ? 1 : .2f);
236 overlays.push_back(draw);
237 }
238 set_overlays(std::move(overlays));
239}
240
241// Adds the current cursor position to the region. In rectangle mode the region is always the
242// axis-aligned box spanned by the first click and the current position; in lasso mode every
243// sufficiently distant sample becomes a new polygon corner.
244void TutorialPointSelection::extend(int x, int y) {
245 // Convert logical screen units to framebuffer pixels (HiDPI scaling), as in mouse_press.
246 int fw = 0, fh = 0;
247 framebuffer_size(fw, fh);
248 const easy3d::vec2 p{float(x) * fw / camera()->screen_width(),
249 float(y) * fh / camera()->screen_height()};
250 if (rectangle_) {
251 // Four corners: start, current, and the two mixed-coordinate corners.
252 const auto first = polygon_.front();
253 polygon_ = {first, {first.x, p.y}, p, {p.x, first.y}};
254 } else if ((p - polygon_.back()).length2() >= 1)
255 // Lasso: append only if the cursor moved at least ~1 pixel, to limit polygon size.
256 polygon_.push_back(p);
257 dirty_ = true;
258 update();
259}
260
261// Aborts the gesture and drops all cached overlay geometry.
262void TutorialPointSelection::cancel() {
263 active_ = false;
264 polygon_.clear();
265 target_.reset();
266 fill_.reset();
267 edge_.reset();
268 dirty_ = true;
269 update();
270}
271
272// \endcond
A data structure for point clouds.
Definition point_cloud.h:46
@ COLOR_PROPERTY
Using a color property.
Definition state.h:59
@ VERTEX
Property defined on vertices.
Definition state.h:69
Tessellator subdivides concave planar polygons, polygons with holes, or polygons with intersecting ed...
Definition tessellator.h:55
void begin_polygon(const vec3 &normal)
Begin the tessellation of a complex polygon.
Definition tessellator.cpp:145
void end_polygon()
Finish tessellating the current polygon and append its elements to the result.
Definition tessellator.cpp:233
void begin_contour()
Begin a contour of the current polygon.
Definition tessellator.cpp:158
const std::vector< Vertex * > & vertices() const
Get the unique vertices accumulated since the last reset().
Definition tessellator.cpp:238
void end_contour()
Finish the current contour.
Definition tessellator.cpp:228
Mat< M, N, T > transpose(const Mat< N, M, T > &m)
Transposes a matrix.
Definition mat.h:1126
Vec< 3, float > vec3
A 3D point/vector of float type.
Definition types.h:44
Vec< 4, float > vec4
A 4D point/vector of float type.
Definition types.h:46
Vec< 2, float > vec2
A 2D point/vector of float type.
Definition types.h:42
Complete backend-independent description of a draw operation.
Definition render_device.h:219
std::shared_ptr< const Geometry > geometry
Geometry snapshot to draw.
Definition render_device.h:220
mat4 model_view_projection
Model-to-clip transform in Easy3D/OpenGL convention.
Definition render_device.h:224
vec4 color
Uniform RGBA multiplier.
Definition render_device.h:226
Inputs for selection of point centers inside a screen polygon.
Definition render_device.h:500
mat4 model_view_projection
Transform from point-local coordinates to OpenGL clip coordinates.
Definition render_device.h:508
std::vector< std::uint32_t > words
Selection bitset, one bit per source slot.
Definition render_device.h:506
bool deselect
Clear bits inside the polygon instead of setting them.
Definition render_device.h:514
std::shared_ptr< const PointData > points
Immutable point positions and source-slot mapping.
Definition render_device.h:502
std::uint32_t height
Framebuffer height in pixels.
Definition render_device.h:512
std::vector< vec2 > polygon
Polygon in top-left framebuffer pixel coordinates.
Definition render_device.h:504
std::uint32_t width
Framebuffer width in pixels.
Definition render_device.h:510
Per-vertex data consumed by a draw command.
Definition render_device.h:91
vec3 position
Position in geometry-local coordinates.
Definition render_device.h:93
See also
Viewer, PointCloud, PointsDrawable, Tessellator, Tutorial_401_ModelPicker