-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathlib.rs
More file actions
848 lines (795 loc) · 30.4 KB
/
lib.rs
File metadata and controls
848 lines (795 loc) · 30.4 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
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
#![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 convert;
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>>,
/// The current alpha mode that the surface is configured with.
alpha_mode: AlphaMode,
_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 {
alpha_mode: AlphaMode::default(),
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()
}
/// The current alpha mode of the surface.
#[doc(alias = "transparency")]
pub fn alpha_mode(&self) -> AlphaMode {
self.alpha_mode
}
/// Set the size of the buffer.
///
/// This is a convenience method for reconfiguring when only the size changes, it is equivalent
/// to:
/// ```ignore
/// surface.configure(width, height, surface.alpha_mode());
/// ````
pub fn resize(&mut self, width: NonZeroU32, height: NonZeroU32) -> Result<(), SoftBufferError> {
self.configure(width, height, self.alpha_mode())
}
/// Reconfigure the surface's properties.
///
/// This sets the size and alpha mode 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.
//
// TODO(madsmtm): What are the exact semantics of configuring? Should it always re-create the
// buffers, or should that only be done in `next_buffer` if properties changed?
pub fn configure(
&mut self,
width: NonZeroU32,
height: NonZeroU32,
alpha_mode: AlphaMode,
) -> Result<(), SoftBufferError> {
if u32::MAX / 4 < width.get() {
// Stride would be too large.
return Err(SoftBufferError::SizeOutOfRange { width, height });
}
if !self.supports_alpha_mode(alpha_mode) {
return Err(SoftBufferError::UnsupportedAlphaMode { alpha_mode });
}
self.surface_impl.configure(width, height, alpha_mode)?;
self.alpha_mode = alpha_mode;
Ok(())
}
/// Query if the given alpha mode is supported.
///
/// See [`AlphaMode`] for documentation on what this will (currently) return on each platform.
#[inline]
pub fn supports_alpha_mode(&self, alpha_mode: AlphaMode) -> bool {
// TODO: Once we get pixel formats, replace this with something like:
// fn supported_pixel_formats(&self, alpha_mode: AlphaMode) -> &[PixelFormat];
//
// And return an empty list from that if the alpha mode isn't supported.
self.surface_impl.supports_alpha_mode(alpha_mode)
}
/// 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()
}
/// A [`Buffer`] that the next frame should be rendered into.
///
/// The size must be set with [`Surface::resize`] or [`Surface::configure`] first.
///
/// The 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 alpha_mode = self.alpha_mode();
let mut buffer_impl = self.surface_impl.next_buffer(alpha_mode)?;
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,
alpha_mode,
_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>,
alpha_mode: AlphaMode,
_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()
}
/// The alpha mode that the buffer uses.
pub fn alpha_mode(&self) -> AlphaMode {
self.alpha_mode
}
/// `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(mut self, damage: &[Rect]) -> Result<(), SoftBufferError> {
// Verify that pixels are set as opaque if the alpha mode requires it.
if cfg!(debug_assertions) && self.alpha_mode == AlphaMode::Opaque {
// Only check inside `width`, pixels outside are allowed to be anything.
let width = self.width().get() as usize;
for (y, row) in self.pixel_rows().enumerate() {
for (x, pixel) in row.iter().take(width).enumerate() {
let msg = concat!(
"This is required by `AlphaMode::Opaque` for cross-platform support, ",
"either write `0xff` to the alpha channel on all pixels, or use ",
"`AlphaMode::Ignored`."
);
assert_eq!(pixel.a, 0xff, "pixel at ({x}, {y}) was not opaque\n{msg}");
}
}
}
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::{AlphaMode, 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 surface: softbuffer::Surface<
/// # std::sync::Arc<dyn raw_window_handle::HasDisplayHandle>,
/// # std::sync::Arc<dyn raw_window_handle::HasWindowHandle>,
/// # > = todo!();
/// # let width = std::num::NonZero::new(1).unwrap();
/// # let height = std::num::NonZero::new(1).unwrap();
///
/// // At surface creation:
/// if surface.supports_alpha_mode(AlphaMode::Ignored) {
/// // Try to use `AlphaMode::Ignored` if possible.
/// surface.configure(width, height, AlphaMode::Ignored);
/// } else {
/// // Fall back to `AlphaMode::Opaque` if not.
/// surface.configure(width, height, AlphaMode::Opaque);
/// }
///
/// // Each draw:
/// let buffer = surface.next_buffer().unwrap();
///
/// let width = buffer.width().get();
/// let height = buffer.height().get();
///
/// if PixelFormat::Rgba.is_default()
/// && buffer.byte_stride().get() == width * 4
/// && buffer.alpha_mode() == AlphaMode::Ignored
/// {
/// // Use zero-copy implementation when possible.
///
/// // 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 RGBA.
/// // - The `stride == width * 4`.
/// // - The alpha channel is ignored (A -> X).
/// //
/// // So we can correctly render in the user's expected simplified RGBX format.
/// render(pixels, width, height);
/// } else {
/// // Fall back to slower implementation when zero-copy is not supported.
/// //
/// // Depending on what performance testing says, if the pixel format is the only
/// // incompatibility, you might also want a branch that renders and swizzles the `R` and
/// // `B` channels after user rendering.
///
/// // 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))
})
}
/// Convert the alpha mode of the buffer in place.
///
/// # Examples
///
/// Write to the buffer as-if it was [`AlphaMode::Ignored`], and convert afterwards if
/// necessary.
///
/// ```no_run
/// # let buffer: Buffer<'_> = unimplemented!();
///
/// surface.supports_alpha_mode(AlphaMode::Ignored) {
/// surface.set_alpha_mode(AlphaMode::Ignored);
/// } else {
/// surface.set_alpha_mode(AlphaMode::Opaque);
/// }
///
/// for row in buffer.pixel_rows() {
/// for pixel in row {
/// // Write red pixels with an arbitrary alpha value.
/// pixel = Pixel::new_rgba(0xff, 0x00, 0x00, 0x7f);
/// }
/// }
///
/// buffer.make_pixels_opaque();
///
/// // Alpha value is ignored, either by compositor () or by us above.
/// buffer.present();
/// ```
#[inline]
pub fn make_pixels_opaque(&mut self) {
if self.alpha_mode == AlphaMode::Ignored {
// Alpha mode is ignored, no need to change the pixels
return;
}
for row in self.pixel_rows() {
for pixel in row {
// TODO: SIMD-optimize this somehow? Or maybe autovectorization is good enough.
pixel.a = 0xff;
}
}
}
/// Multiply pixel color components by the alpha component.
#[inline]
pub fn premultiply_pixels(&mut self) {
for row in self.pixel_rows() {
for pixel in row {
// TODO: SIMD-optimize this somehow? Or maybe autovectorization is good enough.
let a = pixel.a;
pixel.r = convert::premultiply(pixel.r, a);
pixel.g = convert::premultiply(pixel.g, a);
pixel.b = convert::premultiply(pixel.b, a);
}
}
}
/// Divide pixel color components by the alpha component.
#[inline]
pub fn unpremultiply_pixels(&mut self) {
for row in self.pixel_rows() {
for pixel in row {
// TODO: SIMD-optimize this somehow? Or maybe autovectorization is good enough.
let a = pixel.a;
pixel.r = convert::unpremultiply(pixel.r, a);
pixel.g = convert::unpremultiply(pixel.g, a);
pixel.b = convert::unpremultiply(pixel.b, a);
}
}
}
}
/// Specifies how the alpha channel of the surface should be handled by the compositor.
///
/// See [the WhatWG spec][whatwg-premultiplied] for a good description of the difference between
/// premultiplied and postmultiplied alpha.
///
/// Query [`Surface::supports_alpha_mode`] to figure out supported modes for the current platform /
/// surface.
///
/// [whatwg-premultiplied]: https://html.spec.whatwg.org/multipage/canvas.html#premultiplied-alpha-and-the-2d-rendering-context
#[doc(alias = "Transparency")]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
pub enum AlphaMode {
/// The alpha channel must be completely opaque (`1.0` or `0xff`).
///
/// If it isn't, the alpha channel may be ignored, or the contents may be drawn transparent,
/// depending on the platform. Softbuffer contains consistency checks for this internally, so
/// using this mode with a transparent alpha channel may panic with `cfg!(debug_assertions)`
/// enabled.
///
/// **This is the default**, and is supported on all platforms.
//
// NOTE: We use a separate enum value here instead of just making a platform-specific default,
// because even though we'll want to effectively use a `*multiplied` internally on some
// platforms, we'll still want to hint to the compositor that the surface is opaque.
//
// See also <https://github.com/rust-windowing/softbuffer/issues/338>.
#[default]
Opaque,
/// The alpha channel is ignored, and the contents are treated as opaque.
///
/// ## Platform Dependent Behavior
///
/// - Android, macOS/iOS, DRM/KMS, Orbital, Wayland, Windows, X11: Supported.
/// - Web: Cannot be supported in a zero-copy manner.
Ignored,
/// The non-alpha channels are expected to already have been multiplied by the alpha channel.
///
/// ## Platform Dependent Behavior
///
/// - Wayland and DRM/KMS: Supported.
/// - macOS/iOS: Supported, but currently doesn't work with additive values (maybe only as the
/// root layer?). Will be fixed by <https://github.com/rust-windowing/softbuffer/pull/329>.
/// - Web: Not yet supported (TODO `ImageBitmap`).
/// - Android, Orbital, Windows and X11: Not supported (yet unknown if they can be, feel
/// free to open an issue about it).
#[doc(alias = "Associated")]
Premultiplied,
/// The non-alpha channels are not expected to already be multiplied by the alpha channel;
/// instead, the compositor will multiply the non-alpha channels by the alpha channel during
/// compositing.
///
/// Also known as "straight alpha".
///
/// ## Platform Dependent Behavior
///
/// - Web and macOS/iOS: Supported.
/// - Android, DRM/KMS, Orbital, Wayland, Windows, X11: Not supported (yet unknown if they can
/// be, feel free to open an issue about it).
#[doc(alias = "Straight")]
#[doc(alias = "Unassociated")]
#[doc(alias = "Unpremultiplied")]
Postmultiplied,
// Intentionally exhaustive, there are probably no other alpha modes that make sense.
}
/// Convenience helpers.
impl AlphaMode {
/// Check if this is [`AlphaMode::Opaque`].
pub fn is_opaque(self) -> bool {
matches!(self, Self::Opaque)
}
/// Check if this is [`AlphaMode::Ignored`].
pub fn is_ignored(self) -> bool {
matches!(self, Self::Ignored)
}
/// Check if this is [`AlphaMode::Premultiplied`].
pub fn is_premultiplied(self) -> bool {
matches!(self, Self::Premultiplied)
}
/// Check if this is [`AlphaMode::Postmultiplied`].
pub fn is_postmultiplied(self) -> bool {
matches!(self, Self::Postmultiplied)
}
}
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() {}
}