Easy3D 3.0.0
Loading...
Searching...
No Matches
Tutorial_306_ImageViewer

A minimal 2D image viewer built on the Easy3D Viewer, with zoom, fit, and file loading.

Overview

This tutorial turns the 3D Viewer into a simple image viewer: it displays a photograph in screen space (no 3D camera involved), supports mouse-wheel zoom, 'f' to fit the image to the window, Ctrl+O to open another image, and drag-and-drop of image files. It demonstrates that the Viewer's overlay mechanism can render flat 2D content on both the OpenGL and Vulkan backends. All the logic lives in the TutorialImageViewer class (shown after this file); main() only picks the initial image and starts the viewer.

The technique

An image is displayed by texture-mapping it onto a screen-space quad: four vertices whose positions are framebuffer pixel coordinates and whose UVs cover the full [0,1] image square. An orthographic "screen-space projection" maps pixel coordinates directly to clip space, so the quad appears exactly where we place it, independent of any 3D camera. Zooming simply rescales the quad; "fit to screen" chooses the largest scale that keeps the whole image inside the window (the minimum of the width and height ratios, preserving aspect ratio). The quad is rebuilt only when something changes (new image, zoom, resize) — a "dirty" flag avoids redundant geometry-snapshot updates every frame. This is the same textured-quad idea as Tutorial_305_Texture, but driven in pixel coordinates instead of world coordinates.

Easy3D API

Running it

The window opens showing data/fountain/images/0000.jpg fitted to the window. Scroll the mouse wheel to zoom in/out, press 'f' to fit the image again, press Ctrl+O to open a different image via a file dialog, or drag an image file onto the window. If the initial image cannot be loaded, the constructor throws and the program terminates with an error.

1
27#include "viewer.h"
28#include <easy3d/util/resource.h>
29#include <easy3d/util/initializer.h>
30
83using namespace easy3d;
84
85int main(int argc, char **argv) {
86 // Bootstrap Easy3D (logging, resource directory, ...). Must come first.
87 initialize();
88
89 // the image file.
90 const std::string image_file = resource::directory() + "/data/fountain/images/0000.jpg";
91
92 // The custom viewer loads the image in its constructor (throwing on failure) and fits
93 // it to the window, so nothing else needs to be set up here.
94 TutorialImageViewer viewer(EXAMPLE_TITLE, image_file);
95 // Enter the interactive loop (returns when the window is closed).
96 return viewer.run();
97}
Definition collider.cpp:182

The header file of the viewer class:

1
27#ifndef EASY3D_TUTORIAL_IMAGE_VIEWER_H
28#define EASY3D_TUTORIAL_IMAGE_VIEWER_H
29
30#include <easy3d/viewer/viewer.h>
31
41class TutorialImageViewer : public easy3d::Viewer {
42public:
43 // Loads the initial image (throws std::runtime_error on failure) and fits it to the window.
44 TutorialImageViewer(const std::string &title, const std::string &image_file);
45 ~TutorialImageViewer() override;
46
47protected:
48 // Handles 'f' (fit to screen) and Ctrl+O (open file dialog); other keys go to Viewer.
49 bool key_press_event(int key, int modifiers) override;
50 // Mouse wheel zooms by scaling the displayed image size multiplicatively.
51 bool mouse_scroll_event(int x, int y, int dx, int dy) override;
52 // Recomputes scale_ so the whole image fits inside the current window.
53 void fit_screen();
54 // Drag-and-drop: load the first dropped file as the new image.
55 bool drop_event(const std::vector<std::string> &files) override;
56 // Window size changed: the centered quad must be recomputed on the next frame.
57 void post_resize(int width, int height) override;
58 // Rebuilds the screen-space textured quad whenever the dirty_ flag is set.
59 void pre_draw() override;
60
61private:
62 // Decodes the file into an RGBA graphics::Image; returns false on failure.
63 bool load_image(const std::string &file);
64 std::shared_ptr<const easy3d::graphics::Image> image_;
65 float scale_ = 1;
66 bool dirty_ = true;
67};
68
69#endif // EASY3D_TUTORIAL_IMAGE_VIEWER_H
The default viewer implementation for both OpenGL and Vulkan backends.
Definition viewer.h:143
void fit_screen(const Model *model=nullptr) override
Moves the camera so that the entire scene or the active model is centered on the screen at a proper s...
Definition viewer.cpp:1400

The source file of the viewer class:

1
27#include "viewer.h"
28#include <easy3d/fileio/image_io.h>
29#include <easy3d/util/dialog.h>
30#include <easy3d/util/resource.h>
31#include <algorithm>
32#include <cmath>
33#include <stdexcept>
34
35using namespace easy3d;
36
37// The implementation is reproduced on the example page via \include in main.cpp, so we hide
38// it from Doxygen's separate symbol documentation to avoid documenting it twice.
39// \cond
40
41TutorialImageViewer::TutorialImageViewer(const std::string &title, const std::string &file) : Viewer(title) {
42 // This is a 2D image viewer, so suppress the default 3D-navigation manual text and show
43 // only the image-specific shortcuts in the HUD.
44 manual_ = "";
45 hint_ =
46 "Ctrl + o: open an image\n"
47 "Mouse wheel: zoom in/out\n"
48 "f: reset the view";
49 // Load the initial image; failing here is fatal, so report it as an exception.
50 if (!load_image(file))
51 throw std::runtime_error("could not load image: " + file);
52 // Start with the whole image visible, scaled to fit the window.
53 fit_screen();
54}
55
56TutorialImageViewer::~TutorialImageViewer() = default;
57
58// Keyboard shortcuts. Returning true marks the key as handled; unrecognized keys are
59// forwarded to the base Viewer.
60bool TutorialImageViewer::key_press_event(int key, int modifiers) {
61 if (key == KEY_F) {
62 // 'f': reset zoom/position so the entire image fits the window again.
63 fit_screen();
64 return true;
65 }
66 if (key == KEY_O && (modifiers & MODIF_CTRL)) {
67 // Ctrl+O: pick another image with a native file dialog (filtered to common formats).
68 const auto file =
69 dialog::open("Please choose an image file", resource::directory() + "/data/",
70 {"Image Files (*.png *.jpg *.bmp *.ppm *.tga)", "*.png *.jpg *.bmp *.ppm *.tga"});
71 if (!file.empty() && load_image(file)) {
72 fit_screen();
73 return true;
74 }
75 return false;
76 }
77 return Viewer::key_press_event(key, modifiers);
78}
79
80// Wheel zoom: each scroll step multiplies the scale by 1.1 (up) or divides it (down), giving
81// smooth exponential zoom. The scale is clamped to a sane range to avoid degenerate sizes.
82bool TutorialImageViewer::mouse_scroll_event(int, int, int, int dy) {
83 const float next = scale_ * std::pow(1.1f, float(dy));
84 scale_ = std::max(1e-6f, std::min(1e6f, next));
85 // The quad must be rebuilt with the new size, and a repaint must be scheduled.
86 dirty_ = true;
87 update();
88 return true;
89}
90
91// Drag-and-drop support: take the first dropped file and display it if it is a valid image.
92bool TutorialImageViewer::drop_event(const std::vector<std::string> &files) {
93 if (files.empty() || !load_image(files.front()))
94 return false;
95 fit_screen();
96 return true;
97}
98
99// The window was resized: the image stays centered only if the quad is recomputed.
100void TutorialImageViewer::post_resize(int, int) {
101 dirty_ = true;
102}
103
104// Called before each frame. Rebuilds the screen-space quad only when something changed
105// (dirty_), so idle frames cost nothing beyond the base Viewer's own pre_draw() work.
106void TutorialImageViewer::pre_draw() {
107 Viewer::pre_draw();
108 if (!dirty_)
109 return;
110 // Displayed size in framebuffer pixels = image size times the current zoom scale.
111 const float w = image_->width() * scale_;
112 const float h = image_->height() * scale_;
113 // Center the quad in the window (pixel coordinates, origin at the top-left).
114 int fw = 0, fh = 0;
115 framebuffer_size(fw, fh);
116 const float x = static_cast<float>(fw - w) * 0.5f;
117 const float y = static_cast<float>(fh - h) * 0.5f;
118 // Four corners of the quad; UVs (0,0)-(1,1) map the entire image onto it.
119 std::vector<graphics::Vertex> vertices(4);
120 vertices[0].position = vec3(x, y, 0);
121 vertices[0].texcoord = vec2(0, 0);
122 vertices[1].position = vec3(x + w, y, 0);
123 vertices[1].texcoord = vec2(1, 0);
124 vertices[2].position = vec3(x + w, y + h, 0);
125 vertices[2].texcoord = vec2(1, 1);
126 vertices[3].position = vec3(x, y + h, 0);
127 vertices[3].texcoord = vec2(0, 1);
128 // Package the quad as an overlay draw command: two triangles (0,1,2) and (0,2,3),
129 // textured with the image, projected with the pixel-to-clip-space matrix so positions
130 // are interpreted directly as framebuffer pixels (no 3D camera involved).
131 graphics::DrawCommand overlay;
132 overlay.geometry = std::make_shared<graphics::Geometry>(vertices, std::vector<uint32_t>{0, 1, 2, 0, 2, 3});
133 overlay.texture = image_;
134 overlay.model_view_projection = graphics::screen_space_projection(fw, fh);
135 set_overlays({overlay});
136 dirty_ = false;
137}
138
139// Choose the largest scale at which the whole image still fits the window: the minimum of
140// the horizontal and vertical fit ratios preserves the aspect ratio (letterboxing as needed).
141void TutorialImageViewer::fit_screen() {
142 int fw = 0, fh = 0;
143 framebuffer_size(fw, fh);
144 scale_ = std::min(float(fw) / image_->width(), float(fh) / image_->height());
145 dirty_ = true;
146 update();
147}
148
149// Decode an image file into a CPU-side graphics::Image. Returns false if decoding fails.
150bool TutorialImageViewer::load_image(const std::string &file) {
151 int w = 0, h = 0, channels = 0;
152 std::vector<unsigned char> rgba;
153 // Force 4 channels (RGBA) regardless of the file's native format; 'false' keeps the
154 // top row first (no vertical flip), matching the screen-space UV convention used above.
155 if (!ImageIO::load(file, rgba, w, h, channels, 4, false))
156 return false;
157 // Linear filtering interpolates between texels, so zoomed images look smooth instead of
158 // blocky (nearest-neighbor would show individual pixels).
159 graphics::Sampler sampler;
160 sampler.filter = graphics::TextureFilter::linear;
161 auto image = std::make_shared<graphics::Image>(w, h, std::move(rgba), sampler);
162 image_ = std::move(image);
163 // A new image requires rebuilding the overlay quad.
164 dirty_ = true;
165 return true;
166}
167
168// \endcond
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
std::shared_ptr< const Image > texture
Optional texture; null selects white.
Definition render_device.h:221
Texture addressing and filtering configuration.
Definition render_device.h:165
TextureFilter filter
Interpolation used when sampling between texels.
Definition render_device.h:169
See also
Viewer, Tutorial_305_Texture