-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathlib.rs
More file actions
583 lines (546 loc) · 20.3 KB
/
lib.rs
File metadata and controls
583 lines (546 loc) · 20.3 KB
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
#![doc = include_str!("../README.md")]
#![allow(clippy::needless_doctest_main)]
#![deny(unsafe_op_in_unsafe_fn)]
#![warn(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
extern crate core;
mod backend_dispatch;
mod backend_interface;
mod backends;
mod error;
mod format;
mod pixel;
mod util;
use std::cell::Cell;
use std::marker::PhantomData;
use std::num::NonZeroU32;
use std::sync::Arc;
use raw_window_handle::{HasDisplayHandle, HasWindowHandle, RawDisplayHandle, RawWindowHandle};
use self::backend_dispatch::*;
use self::backend_interface::*;
use self::error::InitError;
pub use self::error::SoftBufferError;
pub use self::format::PixelFormat;
pub use self::pixel::Pixel;
/// An instance of this struct contains the platform-specific data that must be managed in order to
/// write to a window on that platform.
#[derive(Clone, Debug)]
pub struct Context<D> {
/// The inner static dispatch object.
context_impl: ContextDispatch<D>,
/// This is Send+Sync IFF D is Send+Sync.
_marker: PhantomData<Arc<D>>,
}
impl<D: HasDisplayHandle> Context<D> {
/// Creates a new instance of this struct, using the provided display.
pub fn new(display: D) -> Result<Self, SoftBufferError> {
match ContextDispatch::new(display) {
Ok(context_impl) => Ok(Self {
context_impl,
_marker: PhantomData,
}),
Err(InitError::Unsupported(display)) => {
let raw = display.display_handle()?.as_raw();
Err(SoftBufferError::UnsupportedDisplayPlatform {
human_readable_display_platform_name: display_handle_type_name(&raw),
display_handle: raw,
})
}
Err(InitError::Failure(f)) => Err(f),
}
}
}
/// A rectangular region of the buffer coordinate space.
#[derive(Clone, Copy, Debug)]
pub struct Rect {
/// x coordinate of top left corner
pub x: u32,
/// y coordinate of top left corner
pub y: u32,
/// width
pub width: NonZeroU32,
/// height
pub height: NonZeroU32,
}
/// A surface for drawing to a window with software buffers.
#[derive(Debug)]
pub struct Surface<D, W> {
/// This is boxed so that `Surface` is the same size on every platform.
surface_impl: Box<SurfaceDispatch<D, W>>,
_marker: PhantomData<Cell<()>>,
}
impl<D: HasDisplayHandle, W: HasWindowHandle> Surface<D, W> {
/// Creates a new surface for the context for the provided window.
///
/// # Platform Dependent Behavior
///
/// - Web: If the handle is a [`WebOffscreenCanvasWindowHandle`], this will error if another
/// context than "2d" was already created for the canvas. If the handle is a
/// [`WebCanvasWindowHandle`], this will additionally error if the canvas was already
/// controlled by an `OffscreenCanvas`.
///
/// [`WebCanvasWindowHandle`]: raw_window_handle::WebCanvasWindowHandle
/// [`WebOffscreenCanvasWindowHandle`]: raw_window_handle::WebCanvasWindowHandle
pub fn new(context: &Context<D>, window: W) -> Result<Self, SoftBufferError> {
match SurfaceDispatch::new(window, &context.context_impl) {
Ok(surface_dispatch) => Ok(Self {
surface_impl: Box::new(surface_dispatch),
_marker: PhantomData,
}),
Err(InitError::Unsupported(window)) => {
let raw = window.window_handle()?.as_raw();
Err(SoftBufferError::UnsupportedWindowPlatform {
human_readable_window_platform_name: window_handle_type_name(&raw),
human_readable_display_platform_name: context.context_impl.variant_name(),
window_handle: raw,
})
}
Err(InitError::Failure(f)) => Err(f),
}
}
/// Get a reference to the underlying window handle.
pub fn window(&self) -> &W {
self.surface_impl.window()
}
/// Set the size of the buffer that will be returned by [`Surface::next_buffer()`].
///
/// If the size of the buffer does not match the size of the window, the buffer is drawn
/// in the upper-left corner of the window. It is recommended in most production use cases
/// to have the buffer fill the entire window. Use your windowing library to find the size
/// of the window.
pub fn resize(&mut self, width: NonZeroU32, height: NonZeroU32) -> Result<(), SoftBufferError> {
if u32::MAX / 4 < width.get() {
// Stride would be too large.
return Err(SoftBufferError::SizeOutOfRange { width, height });
}
self.surface_impl.resize(width, height)?;
Ok(())
}
/// Copies the window contents into a buffer.
///
/// ## Platform Dependent Behavior
///
/// - On X11, the window must be visible.
/// - On AppKit, UIKit, Redox and Wayland, this function is unimplemented.
/// - On Web, this will fail if the content was supplied by
/// a different origin depending on the sites CORS rules.
pub fn fetch(&mut self) -> Result<Vec<Pixel>, SoftBufferError> {
self.surface_impl.fetch()
}
/// Return a [`Buffer`] that the next frame should be rendered into. The size must
/// be set with [`Surface::resize`] first. The initial contents of the buffer may be zeroed, or
/// may contain a previous frame. Call [`Buffer::age`] to determine this.
///
/// ## Platform Dependent Behavior
///
/// - On DRM/KMS, there is no reliable and sound way to wait for the page flip to happen from within
/// `softbuffer`. Therefore it is the responsibility of the user to wait for the page flip before
/// sending another frame.
pub fn next_buffer(&mut self) -> Result<Buffer<'_>, SoftBufferError> {
let mut buffer_impl = self.surface_impl.next_buffer()?;
debug_assert_eq!(
buffer_impl.byte_stride().get() % 4,
0,
"stride must be a multiple of 4"
);
debug_assert_eq!(
buffer_impl.height().get() as usize * buffer_impl.byte_stride().get() as usize,
buffer_impl.pixels_mut().len() * 4,
"buffer must be sized correctly"
);
debug_assert!(
buffer_impl.width().get() * 4 <= buffer_impl.byte_stride().get(),
"width * 4 must be less than or equal to stride"
);
Ok(Buffer {
buffer_impl,
_marker: PhantomData,
})
}
/// Rename to [`Surface::next_buffer()`].
#[deprecated = "renamed to `next_buffer()`"]
pub fn buffer_mut(&mut self) -> Result<Buffer<'_>, SoftBufferError> {
self.next_buffer()
}
}
impl<D: HasDisplayHandle, W: HasWindowHandle> AsRef<W> for Surface<D, W> {
#[inline]
fn as_ref(&self) -> &W {
self.window()
}
}
impl<D: HasDisplayHandle, W: HasWindowHandle> HasWindowHandle for Surface<D, W> {
#[inline]
fn window_handle(
&self,
) -> Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
self.window().window_handle()
}
}
/// A buffer that can be written to by the CPU and presented to the window.
///
/// The buffer's contents is a [slice] of [`Pixel`]s, which depending on the backend may be a
/// mapping into shared memory accessible to the display server, so presentation doesn't require any
/// (client-side) copying.
///
/// This trusts the display server not to mutate the buffer, which could otherwise be unsound.
///
/// # Data representation
///
/// The buffer data is laid out in row-major order (split into horizontal lines), with origin in the
/// top-left corner. There is one [`Pixel`] (4 bytes) in the buffer for each pixel in the area to
/// draw.
///
/// # Reading buffer data
///
/// Reading from buffer data may perform very poorly, as the underlying storage of zero-copy
/// buffers, where implemented, may set options optimized for CPU writes, that allows them to bypass
/// certain caches and avoid cache pollution.
///
/// As such, when rendering, you should always set the pixel in its entirety:
///
/// ```
/// # use softbuffer::Pixel;
/// # let pixel = &mut Pixel::default();
/// # let (red, green, blue) = (0x11, 0x22, 0x33);
/// *pixel = Pixel::new_rgb(red, green, blue);
/// ```
///
/// Instead of e.g. something like:
///
/// ```
/// # use softbuffer::Pixel;
/// # let pixel = &mut Pixel::default();
/// # let (red, green, blue) = (0x11, 0x22, 0x33);
/// // DISCOURAGED!
/// *pixel = Pixel::default(); // Clear
/// pixel.r |= red;
/// pixel.g |= green;
/// pixel.b |= blue;
/// ```
///
/// To discourage reading from the buffer, `&self -> &[u8]` methods are intentionally not provided.
///
/// # Platform dependent behavior
///
/// No-copy presentation is currently supported on:
/// - Wayland
/// - X, when XShm is available
/// - Win32
/// - Orbital, when buffer size matches window size
///
/// Currently [`Buffer::present`] must block copying image data on:
/// - Web
/// - AppKit
/// - UIKit
///
/// Buffer copies an channel swizzling happen on:
/// - Android
#[derive(Debug)]
pub struct Buffer<'surface> {
buffer_impl: BufferDispatch<'surface>,
_marker: PhantomData<Cell<()>>,
}
impl Buffer<'_> {
/// The number of bytes wide each row in the buffer is.
///
/// On some platforms, the buffer is slightly larger than `width * height * 4`, usually for
/// performance reasons to align each row such that they are never split across cache lines.
///
/// In your code, prefer to use [`Buffer::pixel_rows`] (which handles this correctly), or
/// failing that, make sure to chunk rows by the stride instead of the width.
///
/// This is guaranteed to be `>= width * 4`, and is guaranteed to be a multiple of 4.
#[doc(alias = "pitch")] // SDL and Direct3D
#[doc(alias = "bytes_per_row")] // WebGPU
#[doc(alias = "row_stride")]
#[doc(alias = "stride")]
pub fn byte_stride(&self) -> NonZeroU32 {
self.buffer_impl.byte_stride()
}
/// The amount of pixels wide the buffer is.
pub fn width(&self) -> NonZeroU32 {
self.buffer_impl.width()
}
/// The amount of pixels tall the buffer is.
pub fn height(&self) -> NonZeroU32 {
self.buffer_impl.height()
}
/// `age` is the number of frames ago this buffer was last presented. So if the value is
/// `1`, it is the same as the last frame, and if it is `2`, it is the same as the frame
/// before that (for backends using double buffering). If the value is `0`, it is a new
/// buffer that has unspecified contents.
///
/// This can be used to update only a portion of the buffer.
pub fn age(&self) -> u8 {
self.buffer_impl.age()
}
/// Presents buffer to the window.
///
/// # Platform dependent behavior
///
/// ## Wayland
///
/// On Wayland, calling this function may send requests to the underlying `wl_surface`. The
/// graphics context may issue `wl_surface.attach`, `wl_surface.damage`, `wl_surface.damage_buffer`
/// and `wl_surface.commit` requests when presenting the buffer.
///
/// If the caller wishes to synchronize other surface/window changes, such requests must be sent to the
/// Wayland compositor before calling this function.
#[inline]
pub fn present(self) -> Result<(), SoftBufferError> {
// Damage the entire buffer.
self.present_with_damage(&[Rect {
x: 0,
y: 0,
width: NonZeroU32::MAX,
height: NonZeroU32::MAX,
}])
}
/// Presents buffer to the window, with damage regions.
///
/// Damage regions that fall outside the surface are ignored.
///
/// # Platform dependent behavior
///
/// Supported on:
/// - Wayland
/// - X, when XShm is available
/// - Win32
/// - Web
///
/// Otherwise this is equivalent to [`Self::present`].
pub fn present_with_damage(self, damage: &[Rect]) -> Result<(), SoftBufferError> {
self.buffer_impl.present_with_damage(damage)
}
}
/// Helper methods for writing to the buffer as RGBA pixel data.
impl Buffer<'_> {
/// Get a mutable reference to the buffer's pixels.
///
/// The size of the returned slice is `buffer.byte_stride() * buffer.height() / 4`.
///
/// # Examples
///
/// Clear the buffer with red.
///
/// ```no_run
/// # use softbuffer::{Buffer, Pixel};
/// # let buffer: Buffer<'_> = unimplemented!();
/// buffer.pixels().fill(Pixel::new_rgb(0xff, 0x00, 0x00));
/// ```
///
/// Render to a slice of `[u8; 4]`s. This might be useful for library authors that want to
/// provide a simple API that provides RGBX rendering.
///
/// ```no_run
/// use softbuffer::{Pixel, PixelFormat};
///
/// // Assume the user controls the following rendering function:
/// fn render(pixels: &mut [[u8; 4]], width: u32, height: u32) {
/// pixels.fill([0xff, 0xff, 0x00, 0x00]); // Yellow in RGBX
/// }
///
/// // Then we'd convert pixel data as follows:
///
/// # let buffer: softbuffer::Buffer<'_> = todo!();
/// # #[cfg(false)]
/// let buffer = surface.next_buffer();
///
/// let width = buffer.width().get();
/// let height = buffer.height().get();
///
/// // Use fast, zero-copy implementation when possible, and fall back to slower version when not.
/// if PixelFormat::Rgbx.is_default() && buffer.byte_stride().get() == width * 4 {
/// // SAFETY: `Pixel` can be reinterpreted as `[u8; 4]`.
/// let pixels = unsafe { std::mem::transmute::<&mut [Pixel], &mut [[u8; 4]]>(buffer.pixels()) };
/// // CORRECTNESS: We just checked that the format is RGBX, and that `stride == width * 4`.
/// render(pixels, width, height);
/// } else {
/// // Render into temporary buffer.
/// let mut temporary = vec![[0; 4]; width as usize * height as usize];
/// render(&mut temporary, width, height);
///
/// // And copy from temporary buffer to actual pixel data.
/// for (tmp_row, actual_row) in temporary.chunks(width as usize).zip(buffer.pixel_rows()) {
/// for (tmp, actual) in tmp_row.iter().zip(actual_row) {
/// *actual = Pixel::new_rgb(tmp[0], tmp[1], tmp[2]);
/// }
/// }
/// }
///
/// buffer.present();
/// ```
pub fn pixels(&mut self) -> &mut [Pixel] {
self.buffer_impl.pixels_mut()
}
/// Iterate over each row of pixels.
///
/// Each slice returned from the iterator has a length of `buffer.byte_stride() / 4`.
///
/// # Examples
///
/// Fill each row with alternating black and white.
///
/// ```no_run
/// # use softbuffer::{Buffer, Pixel};
/// # let buffer: Buffer<'_> = unimplemented!();
/// for (y, row) in buffer.pixel_rows().enumerate() {
/// if y % 2 == 0 {
/// row.fill(Pixel::new_rgb(0xff, 0xff, 0xff));
/// } else {
/// row.fill(Pixel::new_rgb(0x00, 0x00, 0x00));
/// }
/// }
/// ```
///
/// Fill a red rectangle while skipping over regions that don't need to be modified.
///
/// ```no_run
/// # use softbuffer::{Buffer, Pixel};
/// # let buffer: Buffer<'_> = unimplemented!();
/// let x = 100;
/// let y = 200;
/// let width = 10;
/// let height = 20;
///
/// for row in buffer.pixel_rows().skip(y).take(height) {
/// for pixel in row.iter_mut().skip(x).take(width) {
/// *pixel = Pixel::new_rgb(0xff, 0x00, 0x00);
/// }
/// }
/// ```
///
/// Iterate over each pixel (similar to what the [`pixels_iter`] method does).
///
/// [`pixels_iter`]: Self::pixels_iter
///
/// ```no_run
/// # use softbuffer::{Buffer, Pixel};
/// # let buffer: Buffer<'_> = unimplemented!();
/// for (y, row) in buffer.pixel_rows().enumerate() {
/// for (x, pixel) in row.iter_mut().enumerate() {
/// *pixel = Pixel::new_rgb((x % 0xff) as u8, (y % 0xff) as u8, 0x00);
/// }
/// }
/// ```
#[inline]
pub fn pixel_rows(
&mut self,
) -> impl DoubleEndedIterator<Item = &mut [Pixel]> + ExactSizeIterator {
let pixel_stride = self.byte_stride().get() as usize / 4;
let pixels = self.pixels();
assert_eq!(pixels.len() % pixel_stride, 0, "must be multiple of stride");
// NOTE: This won't panic because `pixel_stride` came from `NonZeroU32`
pixels.chunks_mut(pixel_stride)
}
/// Iterate over each pixel in the data.
///
/// The returned iterator contains the `x` and `y` coordinates and a mutable reference to the
/// pixel at that position.
///
/// # Examples
///
/// Draw a red rectangle with a margin of 10 pixels, and fill the background with blue.
///
/// ```no_run
/// # use softbuffer::{Buffer, Pixel};
/// # let buffer: Buffer<'_> = unimplemented!();
/// let width = buffer.width().get();
/// let height = buffer.height().get();
/// let left = 10;
/// let top = 10;
/// let right = width.saturating_sub(10);
/// let bottom = height.saturating_sub(10);
///
/// for (x, y, pixel) in buffer.pixels_iter() {
/// if (left..=right).contains(&x) && (top..=bottom).contains(&y) {
/// // Inside rectangle.
/// *pixel = Pixel::new_rgb(0xff, 0x00, 0x00);
/// } else {
/// // Outside rectangle.
/// *pixel = Pixel::new_rgb(0x00, 0x00, 0xff);
/// };
/// }
/// ```
///
/// Iterate over the pixel data in reverse, and draw a red rectangle in the top-left corner.
///
/// ```no_run
/// # use softbuffer::{Buffer, Pixel};
/// # let buffer: Buffer<'_> = unimplemented!();
/// // Only reverses iteration order, x and y are still relative to the top-left corner.
/// for (x, y, pixel) in buffer.pixels_iter().rev() {
/// if x <= 100 && y <= 100 {
/// *pixel = Pixel::new_rgb(0xff, 0x00, 0x00);
/// }
/// }
/// ```
#[inline]
pub fn pixels_iter(&mut self) -> impl DoubleEndedIterator<Item = (u32, u32, &mut Pixel)> {
self.pixel_rows().enumerate().flat_map(|(y, pixels)| {
pixels
.iter_mut()
.enumerate()
.map(move |(x, pixel)| (x as u32, y as u32, pixel))
})
}
}
fn window_handle_type_name(handle: &RawWindowHandle) -> &'static str {
match handle {
RawWindowHandle::Xlib(_) => "Xlib",
RawWindowHandle::Win32(_) => "Win32",
RawWindowHandle::WinRt(_) => "WinRt",
RawWindowHandle::Web(_) => "Web",
RawWindowHandle::Wayland(_) => "Wayland",
RawWindowHandle::AndroidNdk(_) => "AndroidNdk",
RawWindowHandle::AppKit(_) => "AppKit",
RawWindowHandle::Orbital(_) => "Orbital",
RawWindowHandle::UiKit(_) => "UiKit",
RawWindowHandle::Xcb(_) => "XCB",
RawWindowHandle::Drm(_) => "DRM",
RawWindowHandle::Gbm(_) => "GBM",
RawWindowHandle::Haiku(_) => "Haiku",
_ => "Unknown Name", //don't completely fail to compile if there is a new raw window handle type that's added at some point
}
}
fn display_handle_type_name(handle: &RawDisplayHandle) -> &'static str {
match handle {
RawDisplayHandle::Xlib(_) => "Xlib",
RawDisplayHandle::Web(_) => "Web",
RawDisplayHandle::Wayland(_) => "Wayland",
RawDisplayHandle::AppKit(_) => "AppKit",
RawDisplayHandle::Orbital(_) => "Orbital",
RawDisplayHandle::UiKit(_) => "UiKit",
RawDisplayHandle::Xcb(_) => "XCB",
RawDisplayHandle::Drm(_) => "DRM",
RawDisplayHandle::Gbm(_) => "GBM",
RawDisplayHandle::Haiku(_) => "Haiku",
RawDisplayHandle::Windows(_) => "Windows",
RawDisplayHandle::Android(_) => "Android",
_ => "Unknown Name", //don't completely fail to compile if there is a new raw window handle type that's added at some point
}
}
#[cfg(not(target_family = "wasm"))]
fn __assert_send() {
fn is_send<T: Send>() {}
fn is_sync<T: Sync>() {}
is_send::<Context<()>>();
is_sync::<Context<()>>();
is_send::<Surface<(), ()>>();
is_send::<Buffer<'static>>();
/// ```compile_fail
/// use softbuffer::Surface;
///
/// fn __is_sync<T: Sync>() {}
/// __is_sync::<Surface<(), ()>>();
/// ```
fn __surface_not_sync() {}
/// ```compile_fail
/// use softbuffer::Buffer;
///
/// fn __is_sync<T: Sync>() {}
/// __is_sync::<Buffer<'static>>();
/// ```
fn __buffer_not_sync() {}
}