-
Notifications
You must be signed in to change notification settings - Fork 1
/
print.html
688 lines (589 loc) · 34.4 KB
/
print.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js light">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>Femtovg Book</title>
<meta name="robots" content="noindex" />
<!-- Custom HTML head -->
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff" />
<link rel="icon" href="favicon.svg">
<link rel="shortcut icon" href="favicon.png">
<link rel="stylesheet" href="css/variables.css">
<link rel="stylesheet" href="css/general.css">
<link rel="stylesheet" href="css/chrome.css">
<link rel="stylesheet" href="css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="highlight.css">
<link rel="stylesheet" href="tomorrow-night.css">
<link rel="stylesheet" href="ayu-highlight.css">
<!-- Custom theme stylesheets -->
</head>
<body>
<!-- Provide site root to javascript -->
<script type="text/javascript">
var path_to_root = "";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script type="text/javascript">
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script type="text/javascript">
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('no-js')
html.classList.remove('light')
html.classList.add(theme);
html.classList.add('js');
</script>
<!-- Hide / unhide sidebar before it is displayed -->
<script type="text/javascript">
var html = document.querySelector('html');
var sidebar = 'hidden';
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
}
html.classList.remove('sidebar-visible');
html.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item expanded affix "><a href="index.html">Introduction</a></li><li class="chapter-item expanded "><a href="1_getting_started/0_intro.html"><strong aria-hidden="true">1.</strong> Getting Started</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="1_getting_started/1_setting_up.html"><strong aria-hidden="true">1.1.</strong> Setting Up</a></li><li class="chapter-item expanded "><a href="1_getting_started/2_rendering.html"><strong aria-hidden="true">1.2.</strong> Rendering</a></li><li class="chapter-item expanded "><a href="1_getting_started/3_event_loop.html"><strong aria-hidden="true">1.3.</strong> The Event Loop</a></li></ol></li></ol>
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
</nav>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky bordered">
<div class="left-buttons">
<button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</button>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">Femtovg Book</h1>
<div class="right-buttons">
<a href="print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script type="text/javascript">
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<main>
<h1 id="introduction-to-femtovg"><a class="header" href="#introduction-to-femtovg">Introduction to Femtovg</a></h1>
<p>Femtovg is a 2D graphics library written in Rust. This means you can draw shapes and stuff with it!</p>
<p>For a quick demo, clone the repository and run the <a href="https://github.com/femtovg/femtovg/blob/master/examples/demo.rs">demo example</a> (you'll need to have <a href="https://www.rust-lang.org/learn/get-started">Rust installed</a>):</p>
<pre><code class="language-commandline">git clone https://github.com/femtovg/femtovg.git
cd femtovg
cargo run --example demo
</code></pre>
<p><img src="demo.png" alt="Femtovg demo: various animated vector graphics and text" /></p>
<p>You can run other examples too. Try <code>cargo run --example text</code> or <code>cargo run --example breakout</code>!</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="getting-started"><a class="header" href="#getting-started">Getting Started</a></h1>
<p>Let's start with a simple program – we'll create a window and paint a simple shape on it!</p>
<p>If you don't have one already, make a new crate named <code>hello_femtovg</code>:</p>
<pre><code class="language-commandline">cargo new hello_femtovg
</code></pre>
<blockquote>
<p>Unless you have much big brain, it is highly recommended that you <a href="https://doc.rust-lang.org/book/ch00-00-introduction.html">learn Rust</a> first, then come back here.</p>
</blockquote>
<div style="break-before: page; page-break-before: always;"></div><h1 id="setting-up"><a class="header" href="#setting-up">Setting Up</a></h1>
<p>Femtovg uses OpenGL to talk to the GPU. We'll need to give Femtovg an <a href="https://www.khronos.org/opengl/wiki/OpenGL_Context">OpenGL context</a> – an object that stores a bunch of stuff needed to draw things. Then, we can create a Canvas to draw things on!</p>
<h2 id="creating-an-opengl-context"><a class="header" href="#creating-an-opengl-context">Creating an OpenGL Context</a></h2>
<blockquote>
<p>If you're new to graphics, maybe this part will feel a bit overwhelming. Don't worry, we'll wrap all the weird code in a function and never worry about it again.</p>
</blockquote>
<p>So, how do we get this OpenGL context? We'll use the winit library to create a window and the <code>glutin</code> library to create an OpenGL context for rendering to that window:</p>
<pre><code class="language-toml">[dependencies]
winit = "0.28.6"
glutin = "0.30.10"
</code></pre>
<p>The first thing we need to do is create an Event Loop – we'll only really use it later, but we can't even create a window without it!</p>
<pre><code class="language-rust ignore">use winit::event_loop::EventLoop;
fn main() {
let event_loop = EventLoop::new();
}
</code></pre>
<p>Let's configure a window. We can specify many settings here, but let's just set the size and title:</p>
<pre><code class="language-rust ignore">use winit::window::WindowBuilder;
use winit::dpi::PhysicalSize;
let window_builder = WindowBuilder::new()
.with_inner_size(PhysicalSize::new(1000., 600.))
.with_title("Femtovg");
</code></pre>
<p>Next we specify a configuration for that window. Usually windows may have many different properties. Think transparency, OpenGL support, bit depth. The following lines find one that is suitable for rendering:</p>
<pre><code class="language-rust ignore">use glutin_winit::DisplayBuilder;
use glutin::{
config::ConfigTemplateBuilder,
context::ContextAttributesBuilder,
context::PossiblyCurrentContext,
display::GetGlDisplay,
prelude::*,
};
let template = ConfigTemplateBuilder::new().with_alpha_size(8);
let display_builder = DisplayBuilder::new().with_window_builder(Some(window_builder));
let (window, gl_config) = display_builder
.build(event_loop, template, |mut configs| configs.next().unwrap())
.unwrap();
let window = window.unwrap();
let gl_display = gl_config.display();
let context_attributes = ContextAttributesBuilder::new().build(Some(window.raw_window_handle()));
let mut not_current_gl_context =
Some(unsafe { gl_display.create_context(&gl_config, &context_attributes).unwrap() });
</code></pre>
<p>Now, we can create a surface for rendering and make our OpenGL context current on that surface:</p>
<pre><code class="language-rust ignore">use surface::{SurfaceAttributesBuilder, WindowSurface},
let attrs = SurfaceAttributesBuilder::<WindowSurface>::new().build(
window.raw_window_handle(),
NonZeroU32::new(1000).unwrap(),
NonZeroU32::new(600).unwrap(),
);
let surface = unsafe { gl_config.display().create_window_surface(&gl_config, &attrs).unwrap() };
not_current_gl_context.take().unwrap().make_current(&surface).unwrap()
</code></pre>
<blockquote>
<p>In order for any OpenGL commands to work, a context must be current; all OpenGL commands affect the state of whichever context is current (<em>from <a href="https://www.khronos.org/opengl/wiki/OpenGL_Context">OpenGL wiki</a></em>)</p>
</blockquote>
<p>We'll need the <code>event_loop</code> and <code>current_context</code> for the next step, but as promised, we can hide everything else in a function. Here's the code we have so far:</p>
<pre><code class="language-rust ignore">use std::num::NonZeroU32;
use glutin_winit::DisplayBuilder;
use raw_window_handle::HasRawWindowHandle;
use winit::dpi::PhysicalSize;
use winit::event_loop::EventLoop;
use winit::window::WindowBuilder;
use glutin::{
config::ConfigTemplateBuilder,
context::ContextAttributesBuilder,
context::PossiblyCurrentContext,
display::GetGlDisplay,
prelude::*,
surface::{SurfaceAttributesBuilder, WindowSurface},
};
fn main() {
let event_loop = EventLoop::new().unwrap();
let _context = create_window(&event_loop);
}
fn create_window(event_loop: &EventLoop<()>) -> PossiblyCurrentContext {
let window_builder = WindowBuilder::new()
.with_inner_size(PhysicalSize::new(1000., 600.))
.with_title("Femtovg");
let template = ConfigTemplateBuilder::new().with_alpha_size(8);
let display_builder = DisplayBuilder::new().with_window_builder(Some(window_builder));
let (window, gl_config) = display_builder
.build(event_loop, template, |mut configs| configs.next().unwrap())
.unwrap();
let window = window.unwrap();
let gl_display = gl_config.display();
let context_attributes = ContextAttributesBuilder::new().build(Some(window.raw_window_handle()));
let mut not_current_gl_context =
Some(unsafe { gl_display.create_context(&gl_config, &context_attributes).unwrap() });
let attrs = SurfaceAttributesBuilder::<WindowSurface>::new().build(
window.raw_window_handle(),
NonZeroU32::new(1000).unwrap(),
NonZeroU32::new(600).unwrap(),
);
let surface = unsafe { gl_config.display().create_window_surface(&gl_config, &attrs).unwrap() };
not_current_gl_context.take().unwrap().make_current(&surface).unwrap()
}
</code></pre>
<p>It compiles, runs, and immediately exits successfully.</p>
<h2 id="creating-a-canvas"><a class="header" href="#creating-a-canvas">Creating a Canvas</a></h2>
<p>We have an OpenGL context and display now – the Femtovg renderer can use it as output for rendering things. Let's create a renderer from the display we have:</p>
<pre><code class="language-rust ignore">let renderer = unsafe { OpenGl::new_from_function_cstr(|s| gl_display.get_proc_address(s).cast()) }
.expect("Cannot create renderer");
</code></pre>
<p>The renderer is responsible for drawing things, but we can't draw on it directly – instead, we need to create a Canvas object:</p>
<pre><code class="language-rust ignore">let mut canvas = Canvas::new(renderer).expect("Cannot create canvas");
</code></pre>
<p>Finally, we have what we need to proceed to the next section – <code>canvas</code> has methods like <code>fill_path</code> and <code>fill_text</code> that actually draw stuff.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="rendering"><a class="header" href="#rendering">Rendering</a></h1>
<p>Now that we have a <code>canvas</code>, we can start drawing things! To keep things organized, let's create a <code>render</code> function that will do all the rendering:</p>
<pre><code class="language-rust ignore">fn main() {
let (context, gl_display, window, surface) = ...;
// [...]
let mut canvas = ..;
render(&context, &surface, &window, &mut canvas);
}
fn render<T: Renderer>(
context: &PossiblyCurrentContext,
surface: &Surface<WindowSurface>,
window: &Window,
canvas: &mut Canvas<T>,
) {}
</code></pre>
<p>In <code>render</code>, first let's make sure that the canvas has the right size – it should match the dimensions and DPI of the window:</p>
<pre><code class="language-rust ignore">let size = window.inner_size();
canvas.set_size(size.width, size.height, window.scale_factor() as f32);
</code></pre>
<p>Next, let's do some actual drawing. As an example, we'll fill a smol red rectangle:</p>
<pre><code class="language-rust ignore">canvas.clear_rect(30, 30, 30, 30, Color::rgbf(1., 0., 0.));
</code></pre>
<blockquote>
<p><a href="https://docs.rs/femtovg/latest/femtovg/struct.Canvas.html#method.clear_rect"><code>clear_rect</code></a> fills a rectangle. The first 2 parameters specify its position, and the next 2 specify the dimensions of the rectangle.</p>
<p><a href="https://docs.rs/femtovg/latest/femtovg/struct.Color.html#method.rgbf"><code>Color::rgbf</code></a> is one of the functions that lets you create a Color. The three parameters correspond to the Red, Green and Blue values in the range 0..1.</p>
</blockquote>
<p>Even if you consider your minimalist abstract masterpiece complete, there's actually some more code we need to write. We have to call <a href="https://docs.rs/femtovg/latest/femtovg/struct.Canvas.html#method.flush"><code>canvas.flush()</code></a> to tell the renderer to execute all drawing commands. Then, we must call <a href="https://docs.rs/glutin/0.30.10/glutin/surface/enum.Surface.html#method.swap_buffers"><code>swap_buffers</code></a> to display what we've rendered: </p>
<pre><code class="language-rust ignore">canvas.flush();
surface.swap_buffers(context).expect("Could not swap buffers");
</code></pre>
<p>The <code>render</code> function is finished, but if you run your program, you won't get to look at it for very long – as soon as <code>render</code> completes, the program exits. To fix this, let's freeze the program with an infinite <code>loop {}</code>.</p>
<p>Our program now looks like this:</p>
<pre><code class="language-rust ignore">use std::num::NonZeroU32;
use femtovg::renderer::OpenGl;
use femtovg::{Canvas, Color};
use glutin::surface::Surface;
use glutin::{context::PossiblyCurrentContext, display::Display};
use glutin_winit::DisplayBuilder;
use raw_window_handle::HasRawWindowHandle;
use winit::event_loop::EventLoop;
use winit::window::WindowBuilder;
use winit::{dpi::PhysicalSize, window::Window};
use glutin::{
config::ConfigTemplateBuilder,
context::ContextAttributesBuilder,
display::GetGlDisplay,
prelude::*,
surface::{SurfaceAttributesBuilder, WindowSurface},
};
fn main() {
let event_loop = EventLoop::new().unwrap();
let (context, gl_display, window, surface) = create_window(&event_loop);
let renderer = unsafe { OpenGl::new_from_function_cstr(|s| gl_display.get_proc_address(s).cast()) }
.expect("Cannot create renderer");
let mut canvas = Canvas::new(renderer).expect("Cannot create canvas");
canvas.set_size(1000, 600, window.scale_factor() as f32);
render(&context, &surface, &window, &mut canvas);
loop {}
}
fn create_window(event_loop: &EventLoop<()>) -> (PossiblyCurrentContext, Display, Window, Surface<WindowSurface>) {
let window_builder = WindowBuilder::new()
.with_inner_size(PhysicalSize::new(1000., 600.))
.with_title("Femtovg");
let template = ConfigTemplateBuilder::new().with_alpha_size(8);
let display_builder = DisplayBuilder::new().with_window_builder(Some(window_builder));
let (window, gl_config) = display_builder
.build(event_loop, template, |mut configs| configs.next().unwrap())
.unwrap();
let window = window.unwrap();
let gl_display = gl_config.display();
let context_attributes = ContextAttributesBuilder::new().build(Some(window.raw_window_handle()));
let mut not_current_gl_context =
Some(unsafe { gl_display.create_context(&gl_config, &context_attributes).unwrap() });
let attrs = SurfaceAttributesBuilder::<WindowSurface>::new().build(
window.raw_window_handle(),
NonZeroU32::new(1000).unwrap(),
NonZeroU32::new(600).unwrap(),
);
let surface = unsafe { gl_config.display().create_window_surface(&gl_config, &attrs).unwrap() };
(
not_current_gl_context.take().unwrap().make_current(&surface).unwrap(),
gl_display,
window,
surface,
)
}
fn render(
context: &PossiblyCurrentContext,
surface: &Surface<WindowSurface>,
window: &Window,
canvas: &mut Canvas<OpenGl>,
) {
// Make sure the canvas has the right size:
let size = window.inner_size();
canvas.set_size(size.width, size.height, window.scale_factor() as f32);
// Make smol red rectangle
canvas.clear_rect(30, 30, 30, 30, Color::rgbf(1., 0., 0.));
// Tell renderer to execute all drawing commands
canvas.flush();
// Display what we've just rendered
surface.swap_buffers(context).expect("Could not swap buffers");
}
</code></pre>
<p>And when we run it, we see the red square we rendered:</p>
<p><img src="1_getting_started/2_app.png" alt="Window titled Femtovg containing a small red square on a black background" /></p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="the-event-loop"><a class="header" href="#the-event-loop">The Event Loop</a></h1>
<p>So far, our app isn't really "doing" anything – in fact, it won't even respond if we try to close it with the "x" button. To handle input from the user, we must use the event loop.</p>
<p>Let's edit <code>main</code> to handle events instead of doing nothing with <code>loop {}</code>:</p>
<pre><code class="language-rust ignore">fn main() {
let event_loop = EventLoop::new();
let (context, gl_display, window, surface) = create_window(&event_loop);
let renderer = unsafe { OpenGl::new_from_function_cstr(|s| gl_display.get_proc_address(s).cast()) }
.expect("Cannot create renderer");
let mut canvas = Canvas::new(renderer).expect("Cannot create canvas");
render(&context, &surface, &window, &mut canvas);
event_loop.run(|event, _target, control_flow| match event {
Event::WindowEvent { window_id, event } => {
println!("{:?}", event)
}
_ => {}
})
}
</code></pre>
<p><a href="https://docs.rs/winit/0.28.6/winit/event_loop/struct.EventLoop.html#method.run"><code>event_loop.run</code></a> will call the provided closure for each new event, until the program exits.</p>
<p><a href="https://docs.rs/winit/0.28.6/winit/event/enum.Event.html"><code>Event</code></a> is the first parameter of the closure, and the one we are most interested in. It is an enum with a few branches for different types of events. In the example above, we only capture and print <code>WindowEvent</code>s, and ignore the rest.</p>
<p>Each <code>Event::WindowEvent</code> contains:</p>
<ul>
<li>A <a href="https://docs.rs/winit/0.28.6/winit/window/struct.WindowId.html"><code>WindowId</code></a> – but since we only have 1 window in this example, the ID will always match with our window's ID.</li>
<li>A <a href="https://docs.rs/winit/0.28.6/winit/event/enum.WindowEvent.html"><code>WindowEvent</code></a> enum, which contains information about the window event.</li>
</ul>
<blockquote>
<p>Note: <code>Event::WindowEvent</code> is a branch of the <code>Event</code> enum, which contains another enum, <code>WindowEvent</code>, of the same name! It can get confusing, but Rust namespaces distinguish between the two – one is <code>glutin::event::Event::WindowEvent</code> and the other is <code>glutin::event::WindowEvent</code>.</p>
</blockquote>
<p>You can run the example to see the different types of <code>WindowEvent</code>s being printed as you interact with the window! You might see something like:</p>
<pre><code>CursorMoved { device_id: DeviceId(X(DeviceId(2))), position: PhysicalPosition { x: 931.1624145507813, y: 270.08074951171875 }, modifiers: (empty) }
AxisMotion { device_id: DeviceId(X(DeviceId(2))), axis: 0, value: 969.1624302163254 }
AxisMotion { device_id: DeviceId(X(DeviceId(2))), axis: 1, value: 372.08075569337234 }
CursorMoved { device_id: DeviceId(X(DeviceId(2))), position: PhysicalPosition { x: 981.8682861328125, y: 257.404296875 }, modifiers: (empty) }
AxisMotion { device_id: DeviceId(X(DeviceId(2))), axis: 0, value: 1019.8683132424485 }
AxisMotion { device_id: DeviceId(X(DeviceId(2))), axis: 1, value: 359.4042849368416 }
CursorLeft { device_id: DeviceId(X(DeviceId(2))) }
KeyboardInput { device_id: DeviceId(X(DeviceId(3))), input: KeyboardInput { scancode: 113, state: Released, virtual_keycode: None, modifiers: (empty) }, is_synthetic: true }
ModifiersChanged((empty))
Focused(false)
</code></pre>
<h2 id="exiting-on-close"><a class="header" href="#exiting-on-close">Exiting on Close</a></h2>
<p>Clicking on the window's close button also creates a <code>WindowEvent</code>. We'll capture this event to exit the application when the user requests it:</p>
<pre><code class="language-rust ignore">event_loop.run(move |event, _target, control_flow| match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
_ => {}
},
_ => {}
})
</code></pre>
<p>Try running it! Thr program should exit when you click the close button.</p>
<blockquote>
<p>The third parameter of the closure is of type <a href="https://docs.rs/glutin/latest/glutin/event_loop/enum.ControlFlow.html"><code>ControlFlow</code></a>. You can set it to <code>ControlFlow::Exit</code> to request the application to quit.</p>
</blockquote>
<h2 id="tracking-mouse-movement"><a class="header" href="#tracking-mouse-movement">Tracking Mouse Movement</a></h2>
<p>Using the <code>CursorMoved</code> event, we can track the mouse position. Let's create a variable for storing the latest position we know, and updating it whenever we get a <code>CursorMoved</code> event:</p>
<pre><code class="language-rust ignore">let mut mouse_position = PhysicalPosition::new(0., 0.);
event_loop.run(move |event, _target, control_flow| match event {
Event::WindowEvent { window_id, event } => match event {
WindowEvent::CursorMoved { position, .. } => {
mouse_position = position;
}
// ...
},
_ => {}
})
</code></pre>
<h2 id="re-rendering"><a class="header" href="#re-rendering">Re-rendering</a></h2>
<p>So far, our code only renders the window once – after that, there's no rendering, only event handling. But suppose we wanted the red square to follow the mouse. How can we re-render the square in the new position?</p>
<p>We'll need to re-render every time the mouse position changes. The correct way to do this is to <a href="https://docs.rs/glutin/latest/glutin/window/struct.Window.html#method.request_redraw"><code>request_redraw</code></a>, so that the platform knows we want to draw some new stuff. Then, we'll receive a <code>Event::RedrawRequested</code> event, and that's when we can render a new frame:</p>
<pre><code class="language-rust ignore">let mut mouse_position = PhysicalPosition::new(0., 0.);
event_loop.run(move |event, _target, control_flow| match event {
Event::WindowEvent { window_id, event } => match event {
WindowEvent::CursorMoved { position, .. } => {
mouse_position = position;
window.request_redraw();
}
// ...
},
Event::RedrawRequested(_) => {
render(&context, &surface, &window, &mut canvas, mouse_position);
}
_ => {}
})
</code></pre>
<p>Finally, we should update our <code>render</code> function to take the mouse position into account – we can just use those coordinates for the square position:</p>
<pre><code class="language-rust ignore">fn render<T: Renderer>(
context: &PossiblyCurrentContext,
surface: &Surface<WindowSurface>,
window: &Window,
canvas: &mut Canvas<T>,
square_position: PhysicalPosition<f64>,
) {
//...
canvas.clear_rect(
square_position.x as u32,
square_position.y as u32,
30,
30,
Color::rgbf(1., 0., 0.),
);
//...
}
</code></pre>
<p>Our code runs! There's just one small problem...</p>
<p><img src="1_getting_started/3_red_paint.png" alt="Screenshot of a window: a trail of blocky red paint on a black background, with the cursor at the end of it" /></p>
<p>What happened? Since there's no code to "erase" the old square, all the squares pile up on each other, creating a red mess. To fix this, we should clear the entire window before rendering anything new.</p>
<pre><code class="language-rust ignore">canvas.clear_rect(0, 0, size.width, size.height, Color::black());
</code></pre>
<p>Now, if you run the code, the red square will happily follow the cursor wherever it goes.</p>
<p><img src="1_getting_started/3_final.png" alt="Screenshot of a window: red square at the cursor position on a black background" /></p>
<p>To recap, here's the code we've written:</p>
<pre><code class="language-rust ignore">use std::num::NonZeroU32;
use femtovg::renderer::OpenGl;
use femtovg::{Canvas, Color};
use glutin::surface::Surface;
use glutin::{context::PossiblyCurrentContext, display::Display};
use glutin_winit::DisplayBuilder;
use raw_window_handle::HasRawWindowHandle;
use winit::dpi::PhysicalPosition;
use winit::event::{Event, WindowEvent};
use winit::event_loop::EventLoop;
use winit::window::WindowBuilder;
use winit::{dpi::PhysicalSize, window::Window};
use glutin::{
config::ConfigTemplateBuilder,
context::ContextAttributesBuilder,
display::GetGlDisplay,
prelude::*,
surface::{SurfaceAttributesBuilder, WindowSurface},
};
fn main() {
let event_loop = EventLoop::new().unwrap();
let (context, gl_display, window, surface) = create_window(&event_loop);
let renderer = unsafe { OpenGl::new_from_function_cstr(|s| gl_display.get_proc_address(s).cast()) }
.expect("Cannot create renderer");
let mut canvas = Canvas::new(renderer).expect("Cannot create canvas");
canvas.set_size(1000, 600, window.scale_factor() as f32);
let mut mouse_position = PhysicalPosition::new(0., 0.);
event_loop
.run(move |event, target| match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::CursorMoved { position, .. } => {
mouse_position = position;
window.request_redraw();
}
WindowEvent::CloseRequested => target.exit(),
WindowEvent::RedrawRequested { .. } => {
render(&context, &surface, &window, &mut canvas, mouse_position);
}
_ => {}
},
_ => {}
})
.unwrap();
}
fn create_window(event_loop: &EventLoop<()>) -> (PossiblyCurrentContext, Display, Window, Surface<WindowSurface>) {
let window_builder = WindowBuilder::new()
.with_inner_size(PhysicalSize::new(1000., 600.))
.with_title("Femtovg");
let template = ConfigTemplateBuilder::new().with_alpha_size(8);
let display_builder = DisplayBuilder::new().with_window_builder(Some(window_builder));
let (window, gl_config) = display_builder
.build(event_loop, template, |mut configs| configs.next().unwrap())
.unwrap();
let window = window.unwrap();
let gl_display = gl_config.display();
let context_attributes = ContextAttributesBuilder::new().build(Some(window.raw_window_handle()));
let mut not_current_gl_context =
Some(unsafe { gl_display.create_context(&gl_config, &context_attributes).unwrap() });
let attrs = SurfaceAttributesBuilder::<WindowSurface>::new().build(
window.raw_window_handle(),
NonZeroU32::new(1000).unwrap(),
NonZeroU32::new(600).unwrap(),
);
let surface = unsafe { gl_config.display().create_window_surface(&gl_config, &attrs).unwrap() };
(
not_current_gl_context.take().unwrap().make_current(&surface).unwrap(),
gl_display,
window,
surface,
)
}
fn render(
context: &PossiblyCurrentContext,
surface: &Surface<WindowSurface>,
window: &Window,
canvas: &mut Canvas<OpenGl>,
square_position: PhysicalPosition<f64>,
) {
// Make sure the canvas has the right size:
let size = window.inner_size();
canvas.set_size(size.width, size.height, window.scale_factor() as f32);
canvas.clear_rect(0, 0, size.width, size.height, Color::black());
// Make smol red rectangle
canvas.clear_rect(
square_position.x as u32,
square_position.y as u32,
30,
30,
Color::rgbf(1., 0., 0.),
);
// Tell renderer to execute all drawing commands
canvas.flush();
// Display what we've just rendered
surface.swap_buffers(context).expect("Could not swap buffers");
}
</code></pre>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
</nav>
</div>
<script type="text/javascript">
window.playground_copyable = true;
</script>
<script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
<script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
<script src="searcher.js" type="text/javascript" charset="utf-8"></script>
<script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
<script src="highlight.js" type="text/javascript" charset="utf-8"></script>
<script src="book.js" type="text/javascript" charset="utf-8"></script>
<!-- Custom JS scripts -->
<script type="text/javascript">
window.addEventListener('load', function() {
window.setTimeout(window.print, 100);
});
</script>
</body>
</html>