CMSC23740 Common Code Library
Support code for CS23740 programming projects
Loading...
Searching...
No Matches
window.hpp
Go to the documentation of this file.
1
7
8/*
9 * COPYRIGHT (c) 2026 John Reppy (https://cs.uchicago.edu/~jhr)
10 * All rights reserved.
11 */
12
13#ifndef _CS237_WINDOW_HPP_
14#define _CS237_WINDOW_HPP_
15
16#ifndef _CS237_HPP_
17#error "cs237/window.hpp should not be included directly"
18#endif
19
20#include <optional>
21
22namespace cs237 {
23
24#ifdef CS237_MAX_FRAMES_IN_FLIGHT
25# define MAX_FRAMES CS237_MAX_FRAMES_IN_FLIGHT
26#else
27# define MAX_FRAMES 2
28#endif
29
33constexpr int kMaxFrames = MAX_FRAMES;
34
36//
38 int wid;
39 int ht;
40 std::string title;
41 bool resizable;
42 bool depth;
43 bool stencil;
44
52 CreateWindowInfo (int w, int h, std::string const &t, bool r, bool d, bool s)
53 : wid(w), ht(h), title(t), resizable(r), depth(d), stencil(s)
54 { }
55
59 CreateWindowInfo (int w, int h)
60 : wid(w), ht(h), title(""), resizable(false), depth(false), stencil(false)
61 { }
62
64 bool needsDepthBuf () const { return this->depth || this->stencil; }
65};
66
68//
69class Window {
70public:
71
73 virtual ~Window ();
74
78 void initialize ();
79
81 Application *app () { return this->_app; }
82
84 vk::Device device () const { return this->_app->_device; }
85
87 vk::Queue graphicsQ () const { return this->_app->_queues.graphics; }
88
90 vk::Queue presentationQ () const { return this->_app->_queues.present; }
91
93 vk::Queue computeQ () const { return this->_app->_queues.compute; }
94
97 void refresh ()
98 {
99 if (this->_isVis) {
100 this->draw();
101 }
102 }
103
105 void hide ()
106 {
107 glfwHideWindow (this->_win);
108 this->_isVis = false;
109 }
110
112 void show ()
113 {
114 glfwShowWindow (this->_win);
115 this->_isVis = true;
116 }
117
120 virtual void draw () = 0;
121
129 virtual void reshape (int wid, int ht);
130
132 virtual void iconify (bool iconified);
133
136 {
137 return glfwWindowShouldClose (this->_win);
138 }
139
143 virtual void key (int key, int scancode, int action, int mods);
144 virtual void cursorPos (double xpos, double ypos);
145 virtual void cursorEnter (bool entered);
146 virtual void mouseButton (int button, int action, int mods);
147 virtual void scroll (double xoffset, double yoffset);
148 //}
149
152 void enableKeyEvent (bool enable);
153 void setCursorMode (int mode);
154 void enableCursorPosEvent (bool enable);
155 void enableCursorEnterEvent (bool enable);
156 void enableMouseButtonEvent (bool enable);
157 void enableScrollEvent (bool enable);
158 //}
159
160protected:
167 struct FrameData {
169 vk::CommandBuffer cmdBuf;
171 vk::Semaphore imageAvail;
173 vk::Semaphore finished;
175 vk::Fence inFlight;
177 uint32_t index;
180
185 //
187
188 FrameData () = delete;
189 FrameData (FrameData &) = delete;
190 FrameData (FrameData const &) = delete;
191 FrameData (FrameData &&) = delete;
192
194 //
195 virtual ~FrameData ();
196
199 {
200 auto sts = this->win->device().waitForFences(this->inFlight, VK_TRUE, UINT64_MAX);
201 if (sts != vk::Result::eSuccess) {
202 ERROR("Synchronization error");
203 }
204 }
205
208 {
209 this->win->device().resetFences(this->inFlight);
210 }
211
214
217 vk::Result present ()
218 {
219 vk::PresentInfoKHR presentInfo(
220 this->finished,
221 this->win->_swap.chain,
222 this->index,
223 nullptr);
224
225 return this->win->presentationQ().presentKHR(presentInfo);
226 }
227
228 }; // struct FrameData
229
232 vk::SurfaceCapabilitiesKHR capabilities;
233 std::vector<vk::SurfaceFormatKHR> formats;
234 std::vector<vk::PresentModeKHR> presentModes;
235
237 vk::SurfaceFormatKHR chooseSurfaceFormat ();
240 vk::PresentModeKHR choosePresentMode ();
243 vk::Extent2D chooseExtent (GLFWwindow *win);
244 };
245
248 bool depth;
249 bool stencil;
250 vk::Format format;
251 vk::Image image;
252 vk::DeviceMemory imageMem;
253 vk::ImageView view;
254 };
255
257 struct SwapChain {
258 vk::Device device;
259 vk::SwapchainKHR chain;
260 vk::Format imageFormat;
261 vk::Extent2D extent;
265 // the following vectors hold the state for each of the buffers in the
266 // swap chain.
267 std::vector<vk::Image> images;
268 std::vector<vk::ImageView> views;
269 std::optional<DepthStencilBuffer> dsBuf;
270
271 SwapChain (vk::Device dev)
272 : device(dev), dsBuf(std::nullopt)
273 { }
274
276 int size () const { return this->images.size(); }
277
279 bool hasDepthBuffer () const
280 {
281 return this->dsBuf.has_value() && this->dsBuf->depth;
282 }
283
285 bool hasStencilBuffer () const
286 {
287 return this->dsBuf.has_value() && this->dsBuf->stencil;
288 }
289
292 std::optional<vk::ImageView> depthImageView ()
293 {
294 if (this->dsBuf.has_value()) {
295 return dsBuf->view;
296 } else {
297 // no depth buffer
298 return std::optional<vk::ImageView>();
299 }
300 }
301
305 void genRenderBarrier (vk::CommandBuffer &cmdBuf, FrameData *frame);
306
310 void genPresentBarrier (vk::CommandBuffer &cmdBuf, FrameData *frame);
311
313 void cleanup ();
314 };
315
317 GLFWwindow *_win;
318 int _wid, _ht;
319 bool _isVis;
325 // Vulkan state for rendering
326 vk::SurfaceKHR _surf;
328 std::vector<FrameData *> _frames;
329 uint32_t _curFrameIdx;
331
336
339 virtual void _init ();
340
343
348 void _createSwapChain (bool depth, bool stencil);
349
354
360
362 FrameData *_currentFrame () { return this->_frames[this->_curFrameIdx]; }
363
366 {
367 if (this->_curFrameIdx == 0) {
368 return this->_frames[this->_frames.size() - 1];
369 } else {
370 return this->_frames[this->_curFrameIdx - 1];
371 }
372 }
373
376 {
377 return this->_frames[(this->_curFrameIdx + 1) % this->_frames.size()];
378 }
379
382 {
383 this->_curFrameIdx = (this->_curFrameIdx + 1) % this->_frames.size();
384 }
385
390 vk::Result _acquireNextImage ();
391
397 std::vector<vk::AttachmentDescription> &descs,
398 std::vector<vk::AttachmentReference> &refs);
399
403 uint32_t _graphicsQIdx () const { return this->_app->_qIdxs.graphics; }
404
408 uint32_t _presentationQIdx () const { return this->_app->_qIdxs.present; }
409
413 uint32_t _computeQIdx () const { return this->_app->_qIdxs.compute; }
414
420 vk::Viewport _getViewport (bool oglView = false)
421 {
422 if (oglView) {
423 // to get the OpenGL-style viewport, we set the origin at Y = height
424 // and use a negative height
425 return vk::Viewport(
426 0.0f,
427 float(this->_swap.extent.width),
428 float(this->_swap.extent.width),
429 -float(this->_swap.extent.height),
430 0.0f, /* min depth */
431 1.0f);
432 } else {
433 return vk::Viewport(
434 0.0f, 0.0f,
435 float(this->_swap.extent.width),
436 float(this->_swap.extent.height),
437 0.0f, /* min depth */
438 1.0f); /* max depth */
439 }
440 }
441
444 vk::Rect2D _getScissorsRect ()
445 {
446 return vk::Rect2D(
447 {0, 0},
448 {this->_swap.extent.width, this->_swap.extent.height});
449 }
450
461 void _setViewportCmd (vk::CommandBuffer cmdBuf, bool oglView = false)
462 {
463 if (oglView) {
464 /* NOTE: we negate the height and set the Y origin to ht because Vulkan's
465 * viewport coordinates are from top-left down, instead of from
466 * bottom-left up. See
467 * https://www.saschawillems.de/blog/2019/03/29/flipping-the-vulkan-viewport
468 */
469 this->_setViewportCmd(cmdBuf,
470 0, this->_swap.extent.height,
471 this->_swap.extent.width, -(int32_t)this->_swap.extent.height);
472 } else {
473 this->_setViewportCmd(cmdBuf,
474 0, 0,
475 this->_swap.extent.width, this->_swap.extent.height);
476 }
477 }
478
489 void _setViewportCmd (vk::CommandBuffer cmdBuf,
490 int32_t x, int32_t y,
491 int32_t wid, int32_t ht);
492
497 vk::DeviceMemory _allocImageMemory (vk::Image img, vk::MemoryPropertyFlags props)
498 {
499 return this->_app->_allocImageMemory (img, props);
500 }
501
508 vk::ImageView _createImageView (
509 vk::Image img, vk::Format fmt, vk::ImageAspectFlags aspectFlags)
510 {
511 return this->_app->_createImageView (img, fmt, aspectFlags);
512 }
513
520 vk::Image img,
521 vk::Format fmt,
522 vk::ImageLayout oldLayout,
523 vk::ImageLayout newLayout)
524 {
525 this->_app->_transitionImageLayout(img, fmt, oldLayout, newLayout);
526 }
527
528public:
529
531 int width () const { return this->_swap.extent.width; }
532
534 int height () const { return this->_swap.extent.height; }
535
536};
537
538} // namespace cs237
539
540#endif // !_CS237_WINDOW_HPP_
the base class for applications
Definition application.hpp:25
vk::Device _device
the logical device that we are using to render
Definition application.hpp:433
Queues< uint32_t > _qIdxs
the queue family indices
Definition application.hpp:434
void _transitionImageLayout(vk::Image img, vk::Format fmt, vk::ImageLayout oldLayout, vk::ImageLayout newLayout)
A helper function for changing the layout of an image.
vk::ImageView _createImageView(vk::Image img, vk::Format fmt, vk::ImageAspectFlags aspectFlags)
A helper function for creating a Vulkan image view object for an image.
Queues< vk::Queue > _queues
the device queues that we are using
Definition application.hpp:435
vk::DeviceMemory _allocImageMemory(vk::Image img, vk::MemoryPropertyFlags props)
A helper function for allocating and binding device memory for an image.
SwapChain _swap
buffer-swapping information
Definition window.hpp:327
virtual void cursorPos(double xpos, double ypos)
void enableKeyEvent(bool enable)
void _transitionImageLayout(vk::Image img, vk::Format fmt, vk::ImageLayout oldLayout, vk::ImageLayout newLayout)
A helper function for changing the layout of an image.
Definition window.hpp:519
vk::Queue presentationQ() const
the presentation queue
Definition window.hpp:90
void enableScrollEvent(bool enable)
virtual FrameData * _allocFrameData(Window *w)
vk::Device device() const
return the logical device for this window
Definition window.hpp:84
FrameData * _currentFrame()
get a pointer to the current per-frame rendering state
Definition window.hpp:362
std::vector< FrameData * > _frames
the per-frame rendering state
Definition window.hpp:328
bool _keyEnabled
true when the Key callback is enabled
Definition window.hpp:320
uint32_t _curFrameIdx
Definition window.hpp:329
vk::Rect2D _getScissorsRect()
get the scissors rectangle for this window
Definition window.hpp:444
virtual void key(int key, int scancode, int action, int mods)
virtual void mouseButton(int button, int action, int mods)
vk::SurfaceKHR _surf
the Vulkan surface to render to
Definition window.hpp:326
void _setViewportCmd(vk::CommandBuffer cmdBuf, bool oglView=false)
add a command to set the viewport and scissor to the whole window
Definition window.hpp:461
bool _isVis
true when the window is visible
Definition window.hpp:319
vk::DeviceMemory _allocImageMemory(vk::Image img, vk::MemoryPropertyFlags props)
A helper function for allocating and binding device memory for an image.
Definition window.hpp:497
void show()
Show the window (a no-op if it is already visible).
Definition window.hpp:112
vk::Queue graphicsQ() const
the graphics queue
Definition window.hpp:87
void enableCursorEnterEvent(bool enable)
vk::ImageView _createImageView(vk::Image img, vk::Format fmt, vk::ImageAspectFlags aspectFlags)
A helper function for creating a Vulkan image view object for an image.
Definition window.hpp:508
void _recreateSwapChain()
Recreate the swap chain for this window; this redefines the _swap instance variable and is used when ...
Window(Application *app, CreateWindowInfo const &info)
the Window base-class constructor
FrameData * _nextFrame()
get a pointer to the next per-frame rendering state
Definition window.hpp:375
virtual void _init()
void enableCursorPosEvent(bool enable)
uint32_t _computeQIdx() const
the compute queue index
Definition window.hpp:413
int _ht
window dimensions
Definition window.hpp:318
void _advanceFrame()
advance the current frame
Definition window.hpp:381
bool _scrollEnabled
true when the Scroll callback is enabled
Definition window.hpp:324
bool _cursorEnterEnabled
true when the CursorEnter callback is enabled
Definition window.hpp:322
void setCursorMode(int mode)
bool windowShouldClose()
get the value of the "close" flag for the window
Definition window.hpp:135
virtual void cursorEnter(bool entered)
GLFWwindow * _win
the underlying window
Definition window.hpp:317
SwapChainDetails _getSwapChainDetails()
Get the swap-chain details for a physical device.
bool _mouseButtonEnabled
true when the MouseButton callback is enabled
Definition window.hpp:323
int width() const
the width of the window
Definition window.hpp:531
virtual ~Window()
destructor: it destroys the underlying GLFW window
Application * _app
the owning application
Definition window.hpp:316
bool _cursorPosEnabled
true when the CursorPos callback is enabled
Definition window.hpp:321
vk::Viewport _getViewport(bool oglView=false)
get the natural viewport for the window
Definition window.hpp:420
uint32_t _presentationQIdx() const
the presentation queue
Definition window.hpp:408
Application * app()
return the application pointer
Definition window.hpp:81
void _createSwapChain(bool depth, bool stencil)
Create the swap chain for this window; this initializes the _swap instance variable.
virtual void iconify(bool iconified)
method invoked on Iconify events.
vk::Queue computeQ() const
the compute queue
Definition window.hpp:93
void enableMouseButtonEvent(bool enable)
uint32_t _graphicsQIdx() const
the graphics queue-family index
Definition window.hpp:403
FrameData * _prevFrame()
get a pointer to the previous per-frame rendering state
Definition window.hpp:365
void refresh()
Definition window.hpp:97
void initialize()
virtual void scroll(double xoffset, double yoffset)
void _initAttachments(std::vector< vk::AttachmentDescription > &descs, std::vector< vk::AttachmentReference > &refs)
initialize the attachment descriptors and references for the color and optional depth/stencil-buffer
vk::Result _acquireNextImage()
void hide()
Hide the window.
Definition window.hpp:105
virtual void reshape(int wid, int ht)
int height() const
the height of the window
Definition window.hpp:534
virtual void draw()=0
void _setViewportCmd(vk::CommandBuffer cmdBuf, int32_t x, int32_t y, int32_t wid, int32_t ht)
add a viewport command to the command buffer; this also sets the scissor rectangle.
int _wid
Definition window.hpp:318
#define ERROR(msg)
Definition cs237.hpp:65
Definition aabb.hpp:22
constexpr int kMaxFrames
Definition window.hpp:33
T compute
the queue family that supports compute
Definition application.hpp:409
T present
the queue family that supports presentation
Definition application.hpp:408
T graphics
the queue family that supports graphics
Definition application.hpp:407
structure containing parameters for creating windows
Definition window.hpp:37
std::string title
window title
Definition window.hpp:40
int ht
the window height
Definition window.hpp:39
bool depth
do we need depth-buffer support?
Definition window.hpp:42
bool resizable
should the window support resizing
Definition window.hpp:41
bool needsDepthBuf() const
do we need a depth/stencil buffer for the window?
Definition window.hpp:64
CreateWindowInfo(int w, int h)
Definition window.hpp:59
CreateWindowInfo(int w, int h, std::string const &t, bool r, bool d, bool s)
Definition window.hpp:52
int wid
the window width
Definition window.hpp:38
bool stencil
do we need stencil-buffer support?
Definition window.hpp:43
information about the optional depth/stencil buffers for the window
Definition window.hpp:247
vk::ImageView view
image view for depth/image-buffer
Definition window.hpp:253
vk::Image image
depth/image-buffer image
Definition window.hpp:251
bool stencil
true if stencil-buffer is supported
Definition window.hpp:249
vk::Format format
the depth/image-buffer format
Definition window.hpp:250
vk::DeviceMemory imageMem
device memory for depth/image-buffer
Definition window.hpp:252
bool depth
true if depth-buffer is supported
Definition window.hpp:248
A container for the per-frame rendering state.
Definition window.hpp:167
vk::Semaphore imageAvail
Definition window.hpp:171
uint32_t index
Definition window.hpp:177
FrameData(FrameData &)=delete
void waitForFence()
wait for this frame's `inFlight' fence
Definition window.hpp:198
vk::Semaphore finished
Definition window.hpp:173
vk::Fence inFlight
Definition window.hpp:175
Window * win
the owning window
Definition window.hpp:168
vk::CommandBuffer cmdBuf
Definition window.hpp:169
vk::Result present()
present this frame
Definition window.hpp:217
void submitDrawingCommands()
submit drawing commands for this frame using the main command buffer
FrameData(FrameData const &)=delete
FrameData(FrameData &&)=delete
void resetFence()
reset this frame's inFlight fence
Definition window.hpp:207
virtual ~FrameData()
Destructor.
information about swap-chain support
Definition window.hpp:231
vk::SurfaceCapabilitiesKHR capabilities
Definition window.hpp:232
vk::PresentModeKHR choosePresentMode()
choose a presentation mode from the available modes; we prefer "mailbox" (aka triple buffering)
std::vector< vk::SurfaceFormatKHR > formats
Definition window.hpp:233
std::vector< vk::PresentModeKHR > presentModes
Definition window.hpp:234
vk::Extent2D chooseExtent(GLFWwindow *win)
get the extent of the window subject to the limits of the Vulkan device
vk::SurfaceFormatKHR chooseSurfaceFormat()
choose a surface format from the available formats
the collected information about the swap-chain for a window
Definition window.hpp:257
std::vector< vk::ImageView > views
image views for the swap buffers
Definition window.hpp:268
std::vector< vk::Image > images
images for the swap buffers
Definition window.hpp:267
std::optional< vk::ImageView > depthImageView()
get the image view for the depth buffer
Definition window.hpp:292
int size() const
return the number of buffers in the swap chain
Definition window.hpp:276
bool hasStencilBuffer() const
does the swap-chain support a stencil buffer?
Definition window.hpp:285
std::optional< DepthStencilBuffer > dsBuf
optional depth/stencil-buffer
Definition window.hpp:269
SwapChain(vk::Device dev)
Definition window.hpp:271
bool hasDepthBuffer() const
does the swap-chain support a depth buffer?
Definition window.hpp:279
vk::SwapchainKHR chain
the swap chain object
Definition window.hpp:259
void cleanup()
destroy the Vulkan state for the swap chain
vk::Extent2D extent
size of swap buffer images
Definition window.hpp:261
void genPresentBarrier(vk::CommandBuffer &cmdBuf, FrameData *frame)
generate a barrier command into the given command buffer that will synchronize presentation access an...
vk::Format imageFormat
pixel format of image buffers
Definition window.hpp:260
int numAttachments
Definition window.hpp:262
vk::Device device
the owning logical device
Definition window.hpp:258
void genRenderBarrier(vk::CommandBuffer &cmdBuf, FrameData *frame)
generate a barrier command into the given command buffer that will synchronize rendering access and c...
#define MAX_FRAMES
Definition window.hpp:27