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
//! The kiss3d window.
use std::cell::RefCell;
use std::path::Path;
use std::rc::Rc;
use std::sync::mpsc::{self, Receiver};
use std::sync::Arc;
use crate::color::{Color, BLACK};
use crate::context::Context;
use crate::event::{Key, Modifiers, WindowEvent};
use crate::renderer::{PointRenderer2d, PointRenderer3d, PolylineRenderer2d, PolylineRenderer3d};
use crate::resource::{
FramebufferManager, MaterialManager2d, MeshManager2d, RenderTarget, Texture, TextureManager,
};
use crate::text::TextRenderer;
use crate::window::canvas::CanvasSetup;
use crate::window::Canvas;
use glamx::UVec2;
use image::{GenericImage, Pixel};
use winit::dpi::LogicalSize;
use winit::window::WindowAttributes;
#[cfg(feature = "egui")]
pub(super) use super::egui_integration::EguiContext;
#[cfg(feature = "recording")]
pub(super) use super::recording::RecordingState;
use super::window_cache::WindowCache;
pub(super) static DEFAULT_WIDTH: u32 = 800u32;
pub(super) static DEFAULT_HEIGHT: u32 = 600u32;
/// Structure representing a window and a 3D scene.
///
/// This is the main interface with the 3d engine.
pub struct Window {
pub(super) events: Rc<Receiver<WindowEvent>>,
pub(super) unhandled_events: Rc<RefCell<Vec<WindowEvent>>>,
pub(super) ambient_intensity: f32,
pub(super) background: Color,
pub(super) polyline_renderer_2d: PolylineRenderer2d,
pub(super) point_renderer_2d: PointRenderer2d,
pub(super) point_renderer: PointRenderer3d,
pub(super) polyline_renderer: PolylineRenderer3d,
pub(super) text_renderer: TextRenderer,
pub(super) framebuffer_manager: FramebufferManager,
pub(super) post_process_render_target: RenderTarget,
/// Offscreen render target used when the window is hidden, so `snap` and
/// recording work without a presentable surface. Created on first use.
pub(super) offscreen_output_target: Option<RenderTarget>,
/// Whether the window is hidden. Hidden windows render offscreen.
pub(super) hidden: bool,
pub(super) should_close: bool,
/// `true` until the first surface texture has been successfully acquired.
/// While set, frame acquisition retries (pumping window events) instead of
/// skipping, so a freshly created window reliably renders its first frame.
pub(super) first_frame: bool,
pub(super) close_key: Option<Key>,
pub(super) close_modifiers: Option<Modifiers>,
#[cfg(feature = "egui")]
pub(super) egui_context: EguiContext,
pub(super) canvas: Canvas,
#[cfg(feature = "recording")]
pub(super) recording: Option<RecordingState>,
}
impl Window {
/// Indicates whether this window should be closed.
#[inline]
pub fn should_close(&self) -> bool {
self.should_close
}
/// The window width.
#[inline]
pub fn width(&self) -> u32 {
self.canvas.size().0
}
/// The window height.
#[inline]
pub fn height(&self) -> u32 {
self.canvas.size().1
}
/// The size of the window.
#[inline]
pub fn size(&self) -> UVec2 {
let (w, h) = self.canvas.size();
UVec2::new(w, h)
}
/// Gets a reference to the underlying canvas.
///
/// This provides access to low-level rendering features like:
/// - Getting the current surface texture for custom rendering
/// - Getting the depth texture view
/// - Presenting frames manually
#[inline]
pub fn canvas(&self) -> &Canvas {
&self.canvas
}
/// Gets a mutable reference to the underlying canvas.
#[inline]
pub fn canvas_mut(&mut self) -> &mut Canvas {
&mut self.canvas
}
/// Sets the window title.
///
/// # Arguments
/// * `title` - The new title for the window
///
/// # Example
/// ```no_run
/// # use kiss3d::window::Window;
/// # #[kiss3d::main]
/// # async fn main() {
/// let mut window = Window::new("Initial Title").await;
/// window.set_title("New Title");
/// # }
/// ```
pub fn set_title(&mut self, title: &str) {
self.canvas.set_title(title)
}
/// Set the window icon. On wasm this does nothing.
///
/// ```no_run
/// # use kiss3d::window::Window;
/// # #[kiss3d::main]
/// # async fn main() {
/// # let mut window = Window::new("Example").await;
/// window.set_icon(image::open("foo.ico").unwrap());
/// # }
/// ```
pub fn set_icon(&mut self, icon: impl GenericImage<Pixel = impl Pixel<Subpixel = u8>>) {
self.canvas.set_icon(icon)
}
/// Sets the cursor grabbing behaviour.
///
/// If cursor grabbing is enabled, the cursor is prevented from leaving the window.
///
/// # Arguments
/// * `grab` - `true` to enable cursor grabbing, `false` to disable it
///
/// # Platform-specific
/// Does nothing on web platforms.
pub fn set_cursor_grab(&self, grab: bool) {
self.canvas.set_cursor_grab(grab);
}
/// Sets the cursor position in window coordinates.
///
/// # Arguments
/// * `x` - The x-coordinate in pixels from the left edge of the window
/// * `y` - The y-coordinate in pixels from the top edge of the window
#[inline]
pub fn set_cursor_position(&self, x: f64, y: f64) {
self.canvas.set_cursor_position(x, y);
}
/// Controls the cursor visibility.
///
/// # Arguments
/// * `hide` - `true` to hide the cursor, `false` to show it
#[inline]
pub fn hide_cursor(&self, hide: bool) {
self.canvas.hide_cursor(hide);
}
/// Closes the window.
///
/// After calling this method, [`render()`](Self::render) will return `false` on the next frame,
/// allowing the render loop to exit gracefully.
#[inline]
pub fn close(&mut self) {
self.should_close = true;
}
/// Hides the window without closing it.
///
/// Use [`show()`](Self::show) to make it visible again.
/// The window continues to exist and can be shown again later.
#[inline]
pub fn hide(&mut self) {
self.hidden = true;
self.canvas.hide()
}
/// Makes the window visible.
///
/// Use [`hide()`](Self::hide) to hide it again.
#[inline]
pub fn show(&mut self) {
self.hidden = false;
self.canvas.show()
}
/// Sets the background color for the window.
///
/// # Arguments
/// * `r` - Red component (0.0 to 1.0)
/// * `g` - Green component (0.0 to 1.0)
/// * `b` - Blue component (0.0 to 1.0)
///
/// # Example
/// ```no_run
/// # use kiss3d::window::Window;
/// # #[kiss3d::main]
/// # async fn main() {
/// use kiss3d::color::DARK_BLUE;
/// let mut window = Window::new("Example").await;
/// window.set_background_color(DARK_BLUE);
/// # }
/// ```
#[inline]
pub fn set_background_color(&mut self, color: Color) {
self.background = color;
}
/// Loads a texture from a file and returns a reference to it.
///
/// The texture is managed by the global texture manager and will be reused
/// if loaded again with the same name.
///
/// # Arguments
/// * `path` - Path to the texture file
/// * `name` - A unique name to identify this texture
///
/// # Returns
/// A reference-counted texture that can be applied to scene objects
pub fn add_texture(&mut self, path: &Path, name: &str) -> Arc<Texture> {
TextureManager::get_global_manager(|tm| tm.add(path, name))
}
/// Returns the DPI scale factor of the screen.
///
/// This is the ratio between physical pixels and logical pixels.
/// On high-DPI displays (like Retina displays), this will be greater than 1.0.
///
/// # Returns
/// The scale factor (e.g., 1.0 for standard displays, 2.0 for Retina displays)
pub fn scale_factor(&self) -> f64 {
self.canvas.scale_factor()
}
/// Sets the ambient light intensity for the scene.
///
/// # Example
/// ```no_run
/// # use kiss3d::window::Window;
/// # use kiss3d::light::Light;
/// # use glamx::Vec3;
/// # #[kiss3d::main]
/// # async fn main() {
/// # let mut window = Window::new("Example").await;
/// // Set global ambient lighting intensity
/// window.set_ambient(0.3);
/// # }
/// ```
///
/// Note: Individual lights should be added to the scene tree using
/// `SceneNode3d::add_point_light()`, `add_directional_light()`, or `add_spot_light()`.
pub fn set_ambient(&mut self, ambient: f32) {
self.ambient_intensity = ambient;
}
/// Returns the current ambient lighting intensity.
pub fn ambient(&self) -> f32 {
self.ambient_intensity
}
/// Rebinds the key to close the window.
/// Set to None to disable.
pub fn rebind_close_key(&mut self, new_close_key: Option<Key>) {
self.close_key = new_close_key;
}
/// Rebinds the modifiers to close the window.
/// Set to None make it work with any modifiers.
pub fn rebind_close_modifiers(&mut self, new_close_modifiers: Option<Modifiers>) {
self.close_modifiers = new_close_modifiers;
}
/// Returns the current key to close the window.
pub fn close_key(&self) -> Option<Key> {
self.close_key
}
/// Returns the current modifiers to close the window.
pub fn close_modifiers(&self) -> Option<Modifiers> {
self.close_modifiers
}
/// Creates a new hidden window.
///
/// The window is created but not displayed. Use [`show()`](Self::show) to make it visible.
/// The default size is 800x600 pixels.
///
/// While hidden, the window renders off-screen instead of to its surface,
/// so [`snap`](Self::snap), [`snap_image`](Self::snap_image) and recording
/// work without ever displaying anything — this is how kiss3d does
/// offscreen rendering.
///
/// # Arguments
/// * `title` - The window title
///
/// # Returns
/// A new `Window` instance
pub async fn new_hidden(title: &str) -> Window {
Window::do_new(title, true, DEFAULT_WIDTH, DEFAULT_HEIGHT, None).await
}
/// Creates a new hidden window with custom dimensions.
///
/// The window is created but not displayed. Use [`show()`](Self::show) to make it visible.
///
/// While hidden, the window renders off-screen instead of to its surface,
/// so [`snap`](Self::snap), [`snap_image`](Self::snap_image) and recording
/// work without ever displaying anything — this is how kiss3d does
/// offscreen rendering.
///
/// # Arguments
/// * `title` - The window title
/// * `width` - The window width in pixels
/// * `height` - The window height in pixels
///
/// # Returns
/// A new `Window` instance
pub async fn new_hidden_with_size(title: &str, width: u32, height: u32) -> Window {
Window::do_new(title, true, width, height, None).await
}
/// Creates a new visible window with default settings.
///
/// The window is created and immediately visible with a default size of 800x600 pixels.
/// Use this in combination with the `#[kiss3d::main]` macro for cross-platform rendering.
///
/// # Arguments
/// * `title` - The window title
///
/// # Returns
/// A new `Window` instance
///
/// # Example
/// ```no_run
/// use kiss3d::prelude::*;
///
/// #[kiss3d::main]
/// async fn main() {
/// let mut window = Window::new("My Application").await;
/// let mut camera = OrbitCamera3d::default();
/// let mut scene = SceneNode3d::empty();
///
/// while window.render_3d(&mut scene, &mut camera).await {
/// // Your render loop code here
/// }
/// }
/// ```
pub async fn new(title: &str) -> Window {
Window::do_new(title, false, DEFAULT_WIDTH, DEFAULT_HEIGHT, None).await
}
/// Creates a new window with custom dimensions.
///
/// # Arguments
/// * `title` - The window title
/// * `width` - The window width in pixels
/// * `height` - The window height in pixels
///
/// # Returns
/// A new `Window` instance
pub async fn new_with_size(title: &str, width: u32, height: u32) -> Window {
Window::do_new(title, false, width, height, None).await
}
/// Creates a new window with custom setup options.
///
/// This allows fine-grained control over window creation, including VSync and anti-aliasing settings.
///
/// # Arguments
/// * `title` - The window title
/// * `width` - The window width in pixels
/// * `height` - The window height in pixels
/// * `setup` - A `CanvasSetup` struct containing the window configuration
///
/// # Returns
/// A new `Window` instance
pub async fn new_with_setup(
title: &str,
width: u32,
height: u32,
setup: CanvasSetup,
) -> Window {
Window::do_new(title, false, width, height, Some(setup)).await
}
/// Creates a new window with custom attributes.
///
/// This allows fine-grained control over window creation.
///
/// # Arguments
/// * `window_attrs` - The window title
///
/// # Returns
/// A new `Window` instance
pub async fn new_with_window_attributes(window_attrs: WindowAttributes) -> Window {
Window::do_new_with_window_attributes(window_attrs, None).await
}
// TODO: make this pub?
async fn do_new(
title: &str,
hide: bool,
width: u32,
height: u32,
setup: Option<CanvasSetup>,
) -> Window {
let window_attrs = WindowAttributes::default()
.with_title(title)
.with_inner_size(LogicalSize::new(width as f64, height as f64))
.with_visible(!hide);
Self::do_new_with_window_attributes(window_attrs, setup).await
}
async fn do_new_with_window_attributes(
window_attrs: WindowAttributes,
setup: Option<CanvasSetup>,
) -> Window {
let (event_send, event_receive) = mpsc::channel();
let hide = !window_attrs.visible;
let canvas = Canvas::open(window_attrs, setup, event_send).await;
let (width, height) = canvas.size();
// Track window count for proper cleanup
Context::increment_window_count();
WindowCache::populate();
let framebuffer_manager = FramebufferManager::new();
let mut usr_window = Window {
should_close: false,
first_frame: true,
close_key: Some(Key::Escape),
close_modifiers: None,
canvas,
events: Rc::new(event_receive),
unhandled_events: Rc::new(RefCell::new(Vec::new())),
ambient_intensity: 0.2,
background: BLACK,
polyline_renderer_2d: PolylineRenderer2d::new(),
point_renderer_2d: PointRenderer2d::new(),
point_renderer: PointRenderer3d::new(),
polyline_renderer: PolylineRenderer3d::new(),
text_renderer: TextRenderer::new(),
#[cfg(feature = "egui")]
egui_context: EguiContext::new(),
post_process_render_target: framebuffer_manager.new_render_target(width, height, true),
offscreen_output_target: None,
hidden: hide,
framebuffer_manager,
#[cfg(feature = "recording")]
recording: None,
};
if hide {
usr_window.canvas.hide()
}
usr_window
}
/// Creates a headless window: a render target backed by no actual window,
/// for off-screen rendering. Powers [`OffscreenSurface`](crate::window::OffscreenSurface).
#[cfg(not(target_arch = "wasm32"))]
pub(super) async fn do_new_headless(
width: u32,
height: u32,
setup: Option<CanvasSetup>,
) -> Window {
let (event_send, event_receive) = mpsc::channel();
let canvas = Canvas::open_headless(width, height, setup, event_send).await;
let (width, height) = canvas.size();
Context::increment_window_count();
WindowCache::populate();
let framebuffer_manager = FramebufferManager::new();
Window {
should_close: false,
first_frame: true,
close_key: None,
close_modifiers: None,
canvas,
events: Rc::new(event_receive),
unhandled_events: Rc::new(RefCell::new(Vec::new())),
ambient_intensity: 0.2,
background: BLACK,
polyline_renderer_2d: PolylineRenderer2d::new(),
point_renderer_2d: PointRenderer2d::new(),
point_renderer: PointRenderer3d::new(),
polyline_renderer: PolylineRenderer3d::new(),
text_renderer: TextRenderer::new(),
#[cfg(feature = "egui")]
egui_context: EguiContext::new(),
post_process_render_target: framebuffer_manager.new_render_target(width, height, true),
offscreen_output_target: None,
// A headless window has no surface; always render off-screen.
hidden: true,
framebuffer_manager,
#[cfg(feature = "recording")]
recording: None,
}
}
}
impl Drop for Window {
fn drop(&mut self) {
// Only clean up GPU resources when the last window is dropped.
// This prevents TLS access order issues with wgpu internals that can cause
// panics during thread cleanup.
let is_last_window = Context::decrement_window_count();
if is_last_window {
// The order matters: clear caches first (which hold references to GPU resources),
// then clear the Context (which holds the wgpu Device/Queue/Instance).
// Clear 3D resource managers
WindowCache::reset();
// Clear 2D resource managers
MeshManager2d::reset_global_manager();
MaterialManager2d::reset_global_manager();
// Finally, clear the wgpu context itself
Context::reset();
}
}
}