🆕 Draw the guest's cursor where the guest moves it on its own
Issue #135: with the mouse passed through to the guest (QEMU's usb-host), the window drew the guest's glyph at the host's pointer, which never moves, while the guest's cursor moved elsewhere. At each cursor doorbell the window now reads the guest's cursor position through its sink, via the display's core, which the callback's block holds. A change of position with no pointer event of the window's in the second before means something else moves the cursor: a passed-through mouse, or the guest placing its own. The window then draws the guest's cursor into its image at that position, and the host's cursor is invisible over the image. The window's next pointer event gives the cursor back to the host's pointer. A doorbell that moves nothing (a show, a hide, a glyph change) changes nothing. The lead is timed on the platform's clock. There is no option: the window decides from what the guest does. The glyph is a second draw in the display's own render pass, after the frame's and before its endEncoding (DisplayCore::encode_current_frame_with and an OverlayDraw), so the target is stored once, with no pass that loads it again. The host's encode_current_frame is unchanged and draws no overlay. - The draw uses the display's own quad buffers over a viewport that is the glyph's rectangle, clipped to the image by a scissor. - The pipeline is the display's overlay pipeline, kept in its cache and made of its functions (DisplayPipelineCache::overlay_for). Colour attachment 0 blends premultiplied (RenderPipelineDesc::blend_over, on Metal and Vulkan). - The glyph's texture holds it premultiplied, so a scaled glyph's filtered edges keep their colour. - The runtime hands a viewport to Vulkan as it is, so a glyph whose viewport would reach past the least bounds Vulkan sets every device ([-8192, 8191], 4096 wide) is not drawn: only one at the far edge of a window over 8000 pixels across. Nothing the guest reads moves for it: the pass makes no buffer, and on the Vulkan platform the glyph's texture is the platform's own (VulkanDevice::new_own_texture: no resource ID, no range of Metal's space). The pipeline and the texture are made before the display encodes the frame, outside the time a guest's present waits on. The position is read without dying while the guest display is paused (DisplayCore::guest_cursor_position). Tests: the lead and the doorbell's read; the placement, the clip and the viewport bounds; the overlay draw's place in the display's pass; pixels on Metal and on the Vulkan platform through SinkDisplay::encode, at 1:1, scaled, letterboxed and clipped; the own texture's ID and address; the blending pipeline value on both platforms. features.md gains the entry, with a manual walk owed.
This commit is contained in:
1 parent
12adb1fb46
commit
094a50318a
40 files changed
+1923
-129
No files matched your search
@@ -741,6 +741,11 @@ impl<P: Platform> DisplayCore<P> {
|
||||
self.render_pipeline_cache.as_ref().map(|c| &c.mtl_device)
|
||||
}
|
||||
|
||||
/// The platform the display draws on.
|
||||
pub fn platform(&self) -> &Arc<P> {
|
||||
&self.platform
|
||||
}
|
||||
|
||||
/// Detaches from the port, unreserves the serial number, cancels the newFrame source and
|
||||
/// releases the queue; each once, at the display's end. The guest display pointer stays.
|
||||
pub fn unplug(&self) {
|
||||
@@ -889,6 +894,23 @@ impl<P: Platform> DisplayCore<P> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest display's cursor position, for the display's own window: `None` without a guest
|
||||
/// display, and while it is paused, where [`DisplayCore::cursor_position`] dies. The guest
|
||||
/// display pointer's lock is let go before the read, so the guest display, where this holds
|
||||
/// its last reference, ends outside it.
|
||||
pub fn guest_cursor_position(&self) -> Option<DisplayCoord> {
|
||||
let guest_display = self.guest_display.lock().as_ref().and_then(Weak::upgrade);
|
||||
guest_display.and_then(|n| n.cursor_position_unless_paused())
|
||||
}
|
||||
|
||||
/// The pipeline the display's own window draws over a frame of the display in a target of
|
||||
/// `format` with ([`DisplayPipelineCache::overlay_for`]), in the display's pass
|
||||
/// ([`DisplayCore::encode_current_frame_with`]): asked before the encode, which makes none.
|
||||
/// `None` without the render state, and where the platform refuses it.
|
||||
pub fn overlay_pipeline(&self, format: u64) -> Option<P::RenderPipeline> {
|
||||
self.render_pipeline_cache.as_ref()?.overlay_for(format)
|
||||
}
|
||||
|
||||
/// Sets the protection options (logged when they change) and hands them to the guest display,
|
||||
/// under the guest display pointer's lock.
|
||||
pub fn set_protection_options(&self, protection_options: u64) {
|
||||
|
||||
@@ -368,4 +368,18 @@ impl<P: Platform> GuestDisplay<P> {
|
||||
y: position.wrapping_shr(16).low_u16(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest's cursor position, read as [`GuestDisplay::cursor_position`] reads it, or
|
||||
/// `None` while paused, where that read dies: for the display's own window, which draws the
|
||||
/// cursor there and never ends the process.
|
||||
pub fn cursor_position_unless_paused(&self) -> Option<DisplayCoord> {
|
||||
if self.unlocked.paused.load(Ordering::SeqCst) {
|
||||
return None;
|
||||
}
|
||||
let position = self.raw_page().load(sp::CURSOR_POSITION);
|
||||
Some(DisplayCoord {
|
||||
x: position.low_u16(),
|
||||
y: position.wrapping_shr(16).low_u16(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1565,6 +1565,21 @@ fn cursor_position_unpacks_the_word() {
|
||||
assert_eq!(r.err(), Some(DeathKind::PageWhilePaused.site()));
|
||||
}
|
||||
|
||||
/// The window's read of the cursor position is the host's while running, and none while paused,
|
||||
/// where the host's dies
|
||||
#[test]
|
||||
fn the_window_s_cursor_position_is_none_while_paused() {
|
||||
let fx = Fx::new();
|
||||
fx.w32(sp::CURSOR_POSITION, 0x0004_0003);
|
||||
assert_eq!(
|
||||
fx.guest_display.cursor_position_unless_paused(),
|
||||
Some(DisplayCoord { x: 3, y: 4 })
|
||||
);
|
||||
fx.guest_display.pause();
|
||||
let r = catch_death(|| fx.guest_display.cursor_position_unless_paused());
|
||||
assert_eq!(r.ok(), Some(None));
|
||||
}
|
||||
|
||||
mod update_mode_list {
|
||||
use super::*;
|
||||
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
//! A display's render pipelines, by the target's pixel format and whether there is a gamma
|
||||
//! table. The table is looked up and set under its mutex, never iterated.
|
||||
//! table, and the pipelines its window draws over a frame with, by the target's pixel format
|
||||
//! ([`DisplayPipelineCache::overlay_for`]). Each table is looked up and set under its mutex, never
|
||||
//! iterated.
|
||||
|
||||
use crate::collections::LookupMap;
|
||||
use crate::display::DeathKind;
|
||||
use crate::platform::device::GpuDevice;
|
||||
use crate::platform::resource::Library;
|
||||
use crate::platform::types::{MtlScissorRect, MtlViewport};
|
||||
use crate::platform::values::RenderPipelineDesc;
|
||||
use crate::platform::{Handle, Platform};
|
||||
use crate::raise::OnFault;
|
||||
@@ -18,6 +21,8 @@ pub const FRAGMENT_FUNCTION_GAMMA_COLOR_MATRIX: &str =
|
||||
"displayPresentFragmentWithGammaTableAndColorMatrix";
|
||||
/// The pipeline label.
|
||||
pub const PIPELINE_LABEL: &str = "reims-vgpu.display-present";
|
||||
/// The overlay pipeline's label.
|
||||
pub const OVERLAY_LABEL: &str = "reims-vgpu.window-cursor";
|
||||
|
||||
/// Which pipeline: the render target's pixel format, and whether it applies the gamma table and
|
||||
/// the colour matrix.
|
||||
@@ -41,6 +46,25 @@ pub struct DisplayPipelineCache<P: Platform> {
|
||||
pub fragment_function_gamma_color_matrix: P::Function,
|
||||
/// The pipelines made so far.
|
||||
pub table: parking_lot::Mutex<LookupMap<PipelineKey, P::RenderPipeline>>,
|
||||
/// The overlay pipelines made so far, by the target's `MTLPixelFormat`.
|
||||
pub overlays: parking_lot::Mutex<LookupMap<u64, P::RenderPipeline>>,
|
||||
}
|
||||
|
||||
/// A quad the display's own window draws over the frame, in the display's render pass after the
|
||||
/// frame's draw
|
||||
/// ([`DisplayCore::encode_current_frame_with`](super::DisplayCore::encode_current_frame_with)):
|
||||
/// the display's strip, a quad over the whole viewport, the texture's top row at its top, drawn
|
||||
/// with `pipeline` over `viewport`, clipped by `scissor`, sampling `texture`.
|
||||
pub struct OverlayDraw<'a, P: Platform> {
|
||||
/// The display's overlay pipeline for the target's format
|
||||
/// ([`DisplayPipelineCache::overlay_for`]).
|
||||
pub pipeline: &'a P::RenderPipeline,
|
||||
/// The texture the quad samples, fragment texture 0.
|
||||
pub texture: &'a P::Texture,
|
||||
/// Where the quad is drawn, in the target's pixels.
|
||||
pub viewport: MtlViewport,
|
||||
/// The pixels it may touch, inside the target.
|
||||
pub scissor: MtlScissorRect,
|
||||
}
|
||||
|
||||
impl<P: Platform> DisplayPipelineCache<P> {
|
||||
@@ -77,6 +101,7 @@ impl<P: Platform> DisplayPipelineCache<P> {
|
||||
fragment_function,
|
||||
fragment_function_gamma_color_matrix,
|
||||
table: parking_lot::Mutex::new(LookupMap::new()),
|
||||
overlays: parking_lot::Mutex::new(LookupMap::new()),
|
||||
};
|
||||
drop(library);
|
||||
Some(made)
|
||||
@@ -101,6 +126,7 @@ impl<P: Platform> DisplayPipelineCache<P> {
|
||||
&self.fragment_function
|
||||
},
|
||||
color0_pixel_format: key.format,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.ok()
|
||||
@@ -112,12 +138,48 @@ impl<P: Platform> DisplayPipelineCache<P> {
|
||||
drop(table);
|
||||
pipeline
|
||||
}
|
||||
|
||||
/// The pipeline the display's window draws over a frame in a target of `format` with (a new
|
||||
/// reference): the vertex function and the plain fragment function, with colour attachment 0
|
||||
/// blending over what its pass loaded ([`RenderPipelineDesc::blend_over`]). Made on a miss with
|
||||
/// no lock held, so that no present's [`DisplayPipelineCache::pipeline_for`] waits for its
|
||||
/// making, and kept with the display's pipelines, which go before the functions they are
|
||||
/// made of. A failed creation answers nil and keeps nothing; of two made for one format at
|
||||
/// once, the first kept is answered and the other let go. A raise making it dies at its send.
|
||||
pub fn overlay_for(&self, format: u64) -> Option<P::RenderPipeline> {
|
||||
if let Some(pipeline) = self.overlays.lock().get(&format) {
|
||||
return Some(pipeline.clone_ref());
|
||||
}
|
||||
let made = self
|
||||
.mtl_device
|
||||
.new_render_pipeline_state(&RenderPipelineDesc {
|
||||
label: Some(OVERLAY_LABEL),
|
||||
vertex: &self.vertex_function,
|
||||
fragment: &self.fragment_function,
|
||||
color0_pixel_format: format,
|
||||
blend_over: true,
|
||||
resource_index: None,
|
||||
})
|
||||
.ok()
|
||||
.flatten()?;
|
||||
let mut overlays = self.overlays.lock();
|
||||
let kept = match overlays.get(&format) {
|
||||
Some(kept) => kept.clone_ref(),
|
||||
None => {
|
||||
overlays.insert(format, made.clone_ref());
|
||||
made
|
||||
}
|
||||
};
|
||||
drop(overlays);
|
||||
Some(kept)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> Drop for DisplayPipelineCache<P> {
|
||||
/// The pipelines first, then the fields in their order.
|
||||
fn drop(&mut self) {
|
||||
self.table.get_mut().clear();
|
||||
self.overlays.get_mut().clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -233,6 +295,7 @@ mod tests {
|
||||
&c.fragment_function
|
||||
},
|
||||
color0_pixel_format: key.format,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
}
|
||||
}
|
||||
@@ -305,6 +368,72 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
mod overlay_for_descriptor {
|
||||
use super::*;
|
||||
|
||||
/// The descriptor of the overlay pipeline for `format`: its label, the vertex function,
|
||||
/// the plain fragment function, the format, blending over, and no resource index.
|
||||
fn desc(
|
||||
c: &DisplayPipelineCache<FakePlatform>,
|
||||
format: u64,
|
||||
) -> RenderPipelineDesc<'_, FakePlatform> {
|
||||
RenderPipelineDesc {
|
||||
label: Some("reims-vgpu.window-cursor"),
|
||||
vertex: &c.vertex_function,
|
||||
fragment: &c.fragment_function,
|
||||
color0_pixel_format: format,
|
||||
blend_over: true,
|
||||
resource_index: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A miss makes the overlay pipeline from its descriptor, kept apart from the display's
|
||||
/// own (whose table stays empty); a hit returns it without Metal
|
||||
#[test]
|
||||
fn miss_builds_then_hit_reuses() {
|
||||
let p = FakePlatform::new();
|
||||
let c = cache(&p);
|
||||
let m = p.call_log().mark();
|
||||
let a = c.overlay_for(80).unwrap();
|
||||
let calls = p.call_log().since(m);
|
||||
assert_eq!(calls.len(), 1);
|
||||
assert_eq!(calls[0].sel, "newRenderPipelineStateWithDescriptor:error:");
|
||||
assert_eq!(calls[0].args, vec![Arg::val(&desc(&c, 80))]);
|
||||
assert!(c.table.lock().is_empty());
|
||||
let m = p.call_log().mark();
|
||||
let b = c.overlay_for(80).unwrap();
|
||||
assert!(p.call_log().since(m).is_empty());
|
||||
assert_eq!(a.id(), b.id());
|
||||
let other = c.overlay_for(81).unwrap();
|
||||
assert_ne!(other.id(), a.id());
|
||||
}
|
||||
|
||||
/// A failed creation returns nil, keeps nothing, and is tried again
|
||||
#[test]
|
||||
fn failure_is_not_kept() {
|
||||
let p = FakePlatform::new();
|
||||
let c = cache(&p);
|
||||
p.script().push(
|
||||
"newRenderPipelineStateWithDescriptor:error:",
|
||||
Step::Error(Default::default()),
|
||||
);
|
||||
assert!(c.overlay_for(80).is_none());
|
||||
assert!(c.overlays.lock().is_empty());
|
||||
assert!(c.overlay_for(80).is_some());
|
||||
}
|
||||
}
|
||||
|
||||
/// The overlay pipelines are released with the display's
|
||||
#[test]
|
||||
fn drop_releases_overlay_pipelines() {
|
||||
let p = FakePlatform::new();
|
||||
let c = cache(&p);
|
||||
let a = c.overlay_for(80).unwrap();
|
||||
let held = a.retain_count();
|
||||
drop(c);
|
||||
assert_eq!(a.retain_count(), held - 1);
|
||||
}
|
||||
|
||||
/// The table's pipelines are released
|
||||
#[test]
|
||||
fn drop_releases_pipelines() {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use crate::display::pipeline::PipelineKey;
|
||||
use crate::display::pipeline::{OverlayDraw, PipelineKey};
|
||||
use crate::display::{DeathKind, Display, DisplayCore, DisplayLocked};
|
||||
use crate::guest::GuestPtr;
|
||||
use crate::platform::command::{CommandBuffer, CompletedInfo};
|
||||
@@ -94,6 +94,45 @@ pub(crate) fn f32_bytes(floats: &[f32]) -> Vec<u8> {
|
||||
floats.iter().flat_map(|f| f.to_ne_bytes()).collect()
|
||||
}
|
||||
|
||||
/// The commands that draw `overlay` in the display's pass, after the frame's draw: its pipeline,
|
||||
/// viewport and scissor, the strip's two buffers bound again (a pass with no frame bound none),
|
||||
/// its texture, and the strip's draw.
|
||||
fn overlay_commands<'a, P: Platform>(
|
||||
g: &'a DisplayLocked<P>,
|
||||
overlay: &OverlayDraw<'a, P>,
|
||||
) -> [RenderCmd<'a, P>; 7] {
|
||||
[
|
||||
RenderCmd::SetRenderPipelineState {
|
||||
pipeline_state: Some(overlay.pipeline),
|
||||
},
|
||||
RenderCmd::SetViewport {
|
||||
viewport: overlay.viewport,
|
||||
},
|
||||
RenderCmd::SetScissorRect {
|
||||
rect: overlay.scissor,
|
||||
},
|
||||
RenderCmd::SetVertexBuffer {
|
||||
buffer: g.pos_buf.as_ref(),
|
||||
offset: 0,
|
||||
index: 0,
|
||||
},
|
||||
RenderCmd::SetVertexBuffer {
|
||||
buffer: g.tex_buf.as_ref(),
|
||||
offset: 0,
|
||||
index: 1,
|
||||
},
|
||||
RenderCmd::SetFragmentTexture {
|
||||
texture: Some(overlay.texture),
|
||||
index: 0,
|
||||
},
|
||||
RenderCmd::DrawPrimitives {
|
||||
primitive_type: MTL_PRIMITIVE_TYPE_TRIANGLE_STRIP,
|
||||
vertex_start: 0,
|
||||
vertex_count: g.vtx_count,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
impl<P: Platform> Display<P> {
|
||||
/// The initializer's render state, under the display mutex: both BGRA8 pipelines pre-warmed,
|
||||
/// the strip's two buffers filled, the property buffer, and the identity matrix. Metal
|
||||
@@ -151,6 +190,18 @@ impl<P: Platform> DisplayCore<P> {
|
||||
command_buffer: &P::CommandBuffer,
|
||||
texture: &P::Texture,
|
||||
region: MtlRegion,
|
||||
) -> RaiseResult<bool> {
|
||||
self.encode_current_frame_with(command_buffer, texture, region, None)
|
||||
}
|
||||
|
||||
/// [`DisplayCore::encode_current_frame`], with `overlay`, where given, drawn over the frame in
|
||||
/// the same pass, after the frame's draw: the display's own window's cursor.
|
||||
pub fn encode_current_frame_with(
|
||||
&self,
|
||||
command_buffer: &P::CommandBuffer,
|
||||
texture: &P::Texture,
|
||||
region: MtlRegion,
|
||||
overlay: Option<&OverlayDraw<'_, P>>,
|
||||
) -> RaiseResult<bool> {
|
||||
let dev = self.mtl_device().map(Handle::id);
|
||||
// Pointer identity, short-circuit.
|
||||
@@ -161,7 +212,7 @@ impl<P: Platform> DisplayCore<P> {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut g = self.display_mutex.lock();
|
||||
self.internal_encode_locked(&mut g, command_buffer, texture, region)?;
|
||||
self.internal_encode_locked(&mut g, command_buffer, texture, region, overlay)?;
|
||||
if g.current_frame.is_some() && !self.current_frame_encoded.load(Ordering::SeqCst) {
|
||||
// A load and a store of the count.
|
||||
let host = self.host_present_count().wrapping_add(1);
|
||||
@@ -180,16 +231,18 @@ impl<P: Platform> DisplayCore<P> {
|
||||
region: MtlRegion,
|
||||
) -> RaiseResult<()> {
|
||||
let mut g = self.display_mutex.lock();
|
||||
self.internal_encode_locked(&mut g, command_buffer, texture, region)
|
||||
self.internal_encode_locked(&mut g, command_buffer, texture, region, None)
|
||||
}
|
||||
|
||||
/// The current frame into `texture` over `region`, with the display mutex held.
|
||||
/// The current frame into `texture` over `region`, with `overlay` over it where given, with
|
||||
/// the display mutex held.
|
||||
fn internal_encode_locked(
|
||||
&self,
|
||||
g: &mut DisplayLocked<P>,
|
||||
command_buffer: &P::CommandBuffer,
|
||||
texture: &P::Texture,
|
||||
region: MtlRegion,
|
||||
overlay: Option<&OverlayDraw<'_, P>>,
|
||||
) -> RaiseResult<()> {
|
||||
// The region's depth and z are dropped; znear = zfar = 0.
|
||||
#[expect(clippy::as_conversions, reason = "u64 to f64 rounds to nearest")]
|
||||
@@ -201,7 +254,7 @@ impl<P: Platform> DisplayCore<P> {
|
||||
znear: 0.0,
|
||||
zfar: 0.0,
|
||||
};
|
||||
self.encode_render_frame_locked(g, None, texture, command_buffer, viewport)
|
||||
self.encode_render_frame_locked(g, None, texture, command_buffer, viewport, overlay)
|
||||
}
|
||||
|
||||
/// An encode of `frame`, taking the display mutex (tests; the product holds it).
|
||||
@@ -214,13 +267,14 @@ impl<P: Platform> DisplayCore<P> {
|
||||
viewport: MtlViewport,
|
||||
) -> RaiseResult<()> {
|
||||
let mut g = self.display_mutex.lock();
|
||||
self.encode_render_frame_locked(&mut g, Some(frame), dst, command_buffer, viewport)
|
||||
self.encode_render_frame_locked(&mut g, Some(frame), dst, command_buffer, viewport, None)
|
||||
}
|
||||
|
||||
/// The pass that draws `frame` (`None`: the current frame) into `dst`, with the display mutex
|
||||
/// held, and its completion, which counts the frame out of flight. Even with no frame and no
|
||||
/// guest display, one frame is counted in. Only the host's encode, an API entry with no
|
||||
/// handler, runs it, so a raise in a send dies there.
|
||||
/// The pass that draws `frame` (`None`: the current frame) into `dst`, then `overlay` over
|
||||
/// it where given ([`overlay_commands`]), with the display mutex held, and its completion,
|
||||
/// which counts the frame out of flight. Even with no frame and no guest display, one frame
|
||||
/// is counted in. Only the host's encode, an API entry with no handler, runs it, so a raise
|
||||
/// in a send dies there.
|
||||
fn encode_render_frame_locked(
|
||||
&self,
|
||||
g: &mut DisplayLocked<P>,
|
||||
@@ -228,6 +282,7 @@ impl<P: Platform> DisplayCore<P> {
|
||||
dst: &P::Texture,
|
||||
command_buffer: &P::CommandBuffer,
|
||||
viewport: MtlViewport,
|
||||
overlay: Option<&OverlayDraw<'_, P>>,
|
||||
) -> RaiseResult<()> {
|
||||
// Still under the display mutex, in a pool (the pass descriptor and the encoder are
|
||||
// Metal's `+0`), which a raise leaves pushed.
|
||||
@@ -348,6 +403,11 @@ impl<P: Platform> DisplayCore<P> {
|
||||
} else {
|
||||
encoder = command_buffer.render_encoder(OnFault::Die, &pass)?;
|
||||
}
|
||||
if let Some(overlay) = overlay {
|
||||
for cmd in overlay_commands(g, overlay) {
|
||||
crate::nil_send!(encoder, encode(OnFault::Die, cmd))?;
|
||||
}
|
||||
}
|
||||
crate::nil_send!(encoder, encode(OnFault::Die, RenderCmd::EndEncoding))?;
|
||||
// The encoder and the pass go before the pool pops.
|
||||
drop(encoder);
|
||||
|
||||
@@ -701,6 +701,78 @@ mod encode_current_frame {
|
||||
assert_eq!(d.in_flight_frame_count.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
/// An overlay is drawn in the frame's own pass, after the frame's draw and before the end:
|
||||
/// its pipeline, viewport and scissor, the strip's buffers, its texture and the strip; with
|
||||
/// none, the pass is the frame's alone. A pass with no frame draws the overlay too
|
||||
#[test]
|
||||
fn an_overlay_is_drawn_in_the_frame_s_pass() {
|
||||
use crate::display::pipeline::OverlayDraw;
|
||||
use crate::platform::types::MtlScissorRect;
|
||||
|
||||
let e = env();
|
||||
let d = make(&e);
|
||||
let pipeline = d.overlay_pipeline(80).unwrap();
|
||||
let glyph = texture(&e, 4, 4);
|
||||
let overlay = OverlayDraw {
|
||||
pipeline: &pipeline,
|
||||
texture: &glyph,
|
||||
viewport: MtlViewport {
|
||||
origin_x: -1.0,
|
||||
origin_y: 2.0,
|
||||
width: 4.0,
|
||||
height: 4.0,
|
||||
znear: 0.0,
|
||||
zfar: 1.0,
|
||||
},
|
||||
scissor: MtlScissorRect {
|
||||
x: 0,
|
||||
y: 2,
|
||||
width: 3,
|
||||
height: 4,
|
||||
},
|
||||
};
|
||||
let tail = |with: Option<&OverlayDraw<'_, P>>| {
|
||||
let cb = cmdbuf(&e);
|
||||
let m = e.p.call_log().mark();
|
||||
assert!(
|
||||
d.encode_current_frame_with(&cb, &texture(&e, 8, 8), region(8, 8), with)
|
||||
.unwrap()
|
||||
);
|
||||
let calls = e.p.call_log().since(m);
|
||||
complete(&e, &cb, CommandBufferStatus::COMPLETED);
|
||||
let first = calls
|
||||
.iter()
|
||||
.position(|c| c.sel == "renderCommandEncoderWithDescriptor:")
|
||||
.unwrap();
|
||||
let end = calls.iter().position(|c| c.sel == "endEncoding").unwrap();
|
||||
calls[first + 1..=end]
|
||||
.iter()
|
||||
.map(|c| c.sel)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let overlay_sels = [
|
||||
"setRenderPipelineState:",
|
||||
"setViewport:",
|
||||
"setScissorRect:",
|
||||
"setVertexBuffer:offset:atIndex:",
|
||||
"setVertexBuffer:offset:atIndex:",
|
||||
"setFragmentTexture:atIndex:",
|
||||
"drawPrimitives:vertexStart:vertexCount:",
|
||||
"endEncoding",
|
||||
];
|
||||
assert_eq!(
|
||||
tail(Some(&overlay)),
|
||||
overlay_sels,
|
||||
"no frame: the overlay alone"
|
||||
);
|
||||
present(Hold::NONE, &d, Some(texture(&e, 8, 8))).unwrap();
|
||||
let plain = tail(None);
|
||||
let with = tail(Some(&overlay));
|
||||
assert_eq!(plain.last(), Some(&"endEncoding"));
|
||||
assert_eq!(with[..plain.len() - 1], plain[..plain.len() - 1]);
|
||||
assert_eq!(with[plain.len() - 1..], overlay_sels);
|
||||
}
|
||||
|
||||
/// The internal entry encodes the current frame with the region's viewport.
|
||||
#[test]
|
||||
fn internal_entry() {
|
||||
@@ -1182,6 +1254,26 @@ fn cursor_position_without_guest_display() {
|
||||
);
|
||||
}
|
||||
|
||||
/// No guest display: the window reads no cursor position
|
||||
#[test]
|
||||
fn guest_cursor_position_without_guest_display() {
|
||||
let e = env();
|
||||
let d = make(&e);
|
||||
assert_eq!(d.guest_cursor_position(), None);
|
||||
}
|
||||
|
||||
/// The window's overlay pipeline for a format is made once, apart from the display's own
|
||||
#[test]
|
||||
fn the_overlay_pipeline_is_made_once_per_format() {
|
||||
let e = env();
|
||||
let d = make(&e);
|
||||
let a = d.overlay_pipeline(80).unwrap();
|
||||
let m = e.p.call_log().mark();
|
||||
let b = d.overlay_pipeline(80).unwrap();
|
||||
assert!(e.p.call_log().since(m).is_empty());
|
||||
assert_eq!(a.id(), b.id());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protection_options() {
|
||||
let e = env();
|
||||
|
||||
@@ -209,10 +209,10 @@ pub struct IcbDesc {
|
||||
pub resource_index: Option<u64>,
|
||||
}
|
||||
|
||||
/// `MTLRenderPipelineDescriptor` for the display's pipeline, as a value. Order: label, vertex
|
||||
/// function, fragment function, then colour attachment 0's pixel format (through
|
||||
/// `colorAttachments` and `objectAtIndexedSubscript:`, which may raise), then the resource index
|
||||
/// and its force flag.
|
||||
/// `MTLRenderPipelineDescriptor` for the display's pipeline, or a window's cursor's, as a value.
|
||||
/// Order: label, vertex function, fragment function, then colour attachment 0's pixel format
|
||||
/// (through `colorAttachments` and `objectAtIndexedSubscript:`, which may raise) and, where set,
|
||||
/// its blending, then the resource index and its force flag.
|
||||
pub struct RenderPipelineDesc<'a, P: Platform> {
|
||||
/// `setLabel:`, when set.
|
||||
pub label: Option<&'a str>,
|
||||
@@ -222,6 +222,11 @@ pub struct RenderPipelineDesc<'a, P: Platform> {
|
||||
pub fragment: &'a P::Function,
|
||||
/// `colorAttachments[0].pixelFormat`.
|
||||
pub color0_pixel_format: u64,
|
||||
/// Colour attachment 0 blends each fragment over the target by its alpha, its colour taken
|
||||
/// as premultiplied: `setBlendingEnabled:`, then both source factors `one` and both
|
||||
/// destination factors `oneMinusSourceAlpha`. Off (Metal's default, `one` over `zero`) for
|
||||
/// the display's own pipelines.
|
||||
pub blend_over: bool,
|
||||
/// `setResourceIndex:` then `setForceResourceIndex:` (SPI), when set.
|
||||
pub resource_index: Option<(u64, bool)>,
|
||||
}
|
||||
@@ -233,6 +238,7 @@ impl<P: Platform> fmt::Debug for RenderPipelineDesc<'_, P> {
|
||||
.field("vertex", &self.vertex.id())
|
||||
.field("fragment", &self.fragment.id())
|
||||
.field("color0_pixel_format", &self.color0_pixel_format)
|
||||
.field("blend_over", &self.blend_over)
|
||||
.field("resource_index", &self.resource_index)
|
||||
.finish()
|
||||
}
|
||||
@@ -677,6 +683,7 @@ mod tests {
|
||||
vertex: &v,
|
||||
fragment: &f,
|
||||
color0_pixel_format: 80,
|
||||
blend_over: false,
|
||||
resource_index: Some((12, true)),
|
||||
})
|
||||
.unwrap()
|
||||
|
||||
@@ -655,8 +655,8 @@ pub fn apply_compute_pass(desc: &ComputePassDesc, d: &MetalComputePassDescriptor
|
||||
|
||||
/// Makes `d` hold `desc`. Order: label, vertex function, fragment function, then colour
|
||||
/// attachment 0's pixel format (`colorAttachments`, then `objectAtIndexedSubscript:`, whose raise
|
||||
/// dies at the send: no path reaches it under a handler), then the resource index and its force
|
||||
/// flag.
|
||||
/// dies at the send: no path reaches it under a handler) and, with `blend_over`, its blending,
|
||||
/// then the resource index and its force flag.
|
||||
pub fn apply_render_pipeline(
|
||||
desc: &RenderPipelineDesc<'_, MetalPlatform>,
|
||||
d: &MetalRenderPipelineDescriptor,
|
||||
@@ -683,12 +683,33 @@ pub fn apply_render_pipeline(
|
||||
MTLPixelFormat(desc.color0_pixel_format.to_usize()),
|
||||
);
|
||||
msg::get("setPixelFormat:", || a.setPixelFormat(v));
|
||||
if desc.blend_over {
|
||||
blend_over(a);
|
||||
}
|
||||
}
|
||||
if let Some((index, force)) = desc.resource_index {
|
||||
pipeline_resource_index(o, index, force);
|
||||
}
|
||||
}
|
||||
|
||||
/// Has `a` blend each fragment, its colour premultiplied, over the target by its alpha
|
||||
/// (`RenderPipelineDesc::blend_over`).
|
||||
fn blend_over(a: &MTLRenderPipelineColorAttachmentDescriptor) {
|
||||
msg::get("setBlendingEnabled:", || a.setBlendingEnabled(true));
|
||||
msg::get("setSourceRGBBlendFactor:", || {
|
||||
a.setSourceRGBBlendFactor(MTLBlendFactor::One);
|
||||
});
|
||||
msg::get("setDestinationRGBBlendFactor:", || {
|
||||
a.setDestinationRGBBlendFactor(MTLBlendFactor::OneMinusSourceAlpha);
|
||||
});
|
||||
msg::get("setSourceAlphaBlendFactor:", || {
|
||||
a.setSourceAlphaBlendFactor(MTLBlendFactor::One);
|
||||
});
|
||||
msg::get("setDestinationAlphaBlendFactor:", || {
|
||||
a.setDestinationAlphaBlendFactor(MTLBlendFactor::OneMinusSourceAlpha);
|
||||
});
|
||||
}
|
||||
|
||||
/// `setResourceIndex:` then `setForceResourceIndex:` on a render pipeline descriptor.
|
||||
fn pipeline_resource_index(o: &MTLRenderPipelineDescriptor, index: u64, force: bool) {
|
||||
msg::get("setResourceIndex:", || {
|
||||
@@ -1251,6 +1272,7 @@ mod tests {
|
||||
vertex: &k.function,
|
||||
fragment: &k.function,
|
||||
color0_pixel_format: 80,
|
||||
blend_over: false,
|
||||
resource_index: Some((2, true)),
|
||||
},
|
||||
&x,
|
||||
@@ -1270,6 +1292,41 @@ mod tests {
|
||||
// SAFETY: index 0 of the colour attachments.
|
||||
let c = unsafe { a.objectAtIndexedSubscript(0) };
|
||||
assert_eq!(c.pixelFormat(), MTLPixelFormat(80));
|
||||
assert!(!c.isBlendingEnabled());
|
||||
}
|
||||
|
||||
/// `blend_over` has colour attachment 0 blend the fragment, premultiplied, over by its alpha
|
||||
#[test]
|
||||
fn a_blended_pipeline_value_blends_over_by_alpha() {
|
||||
let k = kit();
|
||||
let x: MetalRenderPipelineDescriptor =
|
||||
Obj::from_retained(MTLRenderPipelineDescriptor::new());
|
||||
apply_render_pipeline(
|
||||
&RenderPipelineDesc {
|
||||
label: None,
|
||||
vertex: &k.function,
|
||||
fragment: &k.function,
|
||||
color0_pixel_format: 80,
|
||||
blend_over: true,
|
||||
resource_index: None,
|
||||
},
|
||||
&x,
|
||||
);
|
||||
let a = x.get().colorAttachments();
|
||||
// SAFETY: index 0 of the colour attachments.
|
||||
let c = unsafe { a.objectAtIndexedSubscript(0) };
|
||||
assert_eq!(c.pixelFormat(), MTLPixelFormat(80));
|
||||
assert!(c.isBlendingEnabled());
|
||||
assert_eq!(c.sourceRGBBlendFactor(), MTLBlendFactor::One);
|
||||
assert_eq!(
|
||||
c.destinationRGBBlendFactor(),
|
||||
MTLBlendFactor::OneMinusSourceAlpha
|
||||
);
|
||||
assert_eq!(c.sourceAlphaBlendFactor(), MTLBlendFactor::One);
|
||||
assert_eq!(
|
||||
c.destinationAlphaBlendFactor(),
|
||||
MTLBlendFactor::OneMinusSourceAlpha
|
||||
);
|
||||
}
|
||||
|
||||
/// setContents: and setDeallocator: (SPI) on the private buffer descriptor: the buffer Metal
|
||||
|
||||
@@ -1455,6 +1455,7 @@ pub(crate) mod tests {
|
||||
vertex: &v,
|
||||
fragment: &f,
|
||||
color0_pixel_format: MTLPixelFormat::BGRA8Unorm.0.to_u64(),
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
@@ -517,6 +517,18 @@ impl VulkanDevice {
|
||||
})
|
||||
}
|
||||
|
||||
/// A texture of `descriptor` of the platform's own, for a helper the guest never reaches
|
||||
/// (the window's cursor glyph): it takes no range of Metal's space ([`metal_space::Hold`]'s
|
||||
/// `NONE`) and no resource ID (the runtime's `IdPlacement::Outside`, whose texture answers 0),
|
||||
/// so no guest-visible address or ID depends on it. `None` where the runtime refuses it.
|
||||
pub fn new_own_texture(&self, descriptor: &VulkanTextureDescriptor) -> Option<VulkanTexture> {
|
||||
let fields = descriptor.fields();
|
||||
let mut desc = fields.descriptor("newTextureWithDescriptor:", Maker::Other);
|
||||
desc.placement = rt::IdPlacement::Outside;
|
||||
let raw = plain(|| self.raw.new_texture(&desc)).ok()?;
|
||||
Some(self.texture_of(raw, None, 0, Arc::new(metal_space::Hold::NONE)))
|
||||
}
|
||||
|
||||
/// The handle of a buffer this device made, over `surface` when it was made on one.
|
||||
pub(crate) fn buffer(&self, raw: rt::Buffer, surface: Option<Arc<OsSurface>>) -> VulkanBuffer {
|
||||
let id = raw.object_id();
|
||||
@@ -2535,6 +2547,40 @@ pub(crate) mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The platform's own texture takes no resource ID and none of Metal's space: it answers 0,
|
||||
/// and a guest texture and buffer made while it lives take the ID and the address they take
|
||||
/// without it, where a guest texture held in its place moves them
|
||||
#[test]
|
||||
fn an_own_texture_takes_no_resource_id_or_metal_space() {
|
||||
use reims_vgpu_core::platform::Platform as _;
|
||||
use reims_vgpu_core::platform::resource::{Buffer as _, Texture as _};
|
||||
use reims_vgpu_core::platform::values::TextureDesc;
|
||||
let p = crate::platform::tests::platform();
|
||||
let d = dev();
|
||||
let desc = p.texture_descriptor(&TextureDesc {
|
||||
width: 32,
|
||||
height: 32,
|
||||
..TextureDesc::default()
|
||||
});
|
||||
let guest = || {
|
||||
let texture = d.new_texture(OnFault::Return, &desc).unwrap().unwrap();
|
||||
let buffer = d
|
||||
.new_buffer_of_length(OnFault::Return, 64, 0)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
(texture.unique_identifier(), buffer.gpu_address())
|
||||
};
|
||||
let without = guest();
|
||||
let own = d.new_own_texture(&desc).unwrap();
|
||||
assert_eq!(own.unique_identifier(), 0);
|
||||
assert_eq!(guest(), without);
|
||||
let held = d.new_texture(OnFault::Return, &desc).unwrap().unwrap();
|
||||
let (id, address) = guest();
|
||||
assert_ne!(id, without.0);
|
||||
assert_ne!(address, without.1);
|
||||
drop((own, held));
|
||||
}
|
||||
|
||||
/// Every compute pipeline creation takes a new nonzero identifier, even of one function twice,
|
||||
/// and every reference to a state answers its own
|
||||
#[test]
|
||||
|
||||
@@ -3779,6 +3779,7 @@ pub(crate) mod tests {
|
||||
vertex: &v,
|
||||
fragment: &f,
|
||||
color0_pixel_format: BGRA8,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap()
|
||||
@@ -4615,6 +4616,7 @@ pub(crate) mod tests {
|
||||
vertex: &vertex,
|
||||
fragment: &fragment,
|
||||
color0_pixel_format: BGRA8,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap()
|
||||
|
||||
@@ -264,6 +264,7 @@ impl<P: Platform> Objects<P> {
|
||||
vertex: &vertex,
|
||||
fragment: &fragment,
|
||||
color0_pixel_format: BGRA8,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap()
|
||||
|
||||
@@ -2616,6 +2616,7 @@ fn surface_references<P: Platform<Surface = OsSurface>>(
|
||||
vertex: &vertex,
|
||||
fragment: &fragment,
|
||||
color0_pixel_format: 80,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap()
|
||||
@@ -3746,6 +3747,7 @@ fn rotated_uses<P: Platform<Surface = OsSurface>>(
|
||||
vertex: &vertex,
|
||||
fragment: &fragment,
|
||||
color0_pixel_format: 80,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap()
|
||||
@@ -3907,6 +3909,7 @@ fn rotated_view_pass<P: Platform<Surface = OsSurface>>(
|
||||
vertex: &vertex,
|
||||
fragment: &fragment,
|
||||
color0_pixel_format: view,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap()
|
||||
|
||||
@@ -455,20 +455,32 @@ fn color_attachment(raw: u64) -> Option<ColorAttachmentDescriptor> {
|
||||
.then(|| ColorAttachmentDescriptor::new(crate::gpu::pixel_format("setPixelFormat:", raw)))
|
||||
}
|
||||
|
||||
/// `newRenderPipelineStateWithDescriptor:error:` of the display's value: its two functions and
|
||||
/// colour 0's format, blending off, no vertex descriptor, the resource index as the placement.
|
||||
/// The compile's refusal of a format the functions cannot write (an integer target) is the
|
||||
/// `newRenderPipelineStateWithDescriptor:error:` of the display's value, or a window cursor's:
|
||||
/// its two functions and colour 0's format, blending off or, with `blend_over`, the fragment's
|
||||
/// premultiplied colour over by its alpha, no vertex descriptor, the resource index as the placement. The
|
||||
/// compile's refusal of a format the functions cannot write (an integer target) is the
|
||||
/// `NSError`, as Metal answers nil and an error there; no path reaches it under a handler, so
|
||||
/// every other refusal dies at the send.
|
||||
pub(crate) fn new_render_pipeline_state(
|
||||
device: &VulkanDevice,
|
||||
desc: &RenderPipelineDesc<'_, VulkanPlatform>,
|
||||
) -> Result<Option<VulkanRenderPipeline>, NsErrorText> {
|
||||
use metal2vulkan::metal::BlendFactor;
|
||||
|
||||
let sel = "newRenderPipelineStateWithDescriptor:error:";
|
||||
let mut d =
|
||||
RenderPipelineDescriptor::new(StageSource::Function(desc.vertex.function_descriptor()));
|
||||
d.fragment = Some(StageSource::Function(desc.fragment.function_descriptor()));
|
||||
d.color_attachments[0] = color_attachment(desc.color0_pixel_format);
|
||||
if desc.blend_over
|
||||
&& let Some(c) = d.color_attachments[0].as_mut()
|
||||
{
|
||||
c.blending_enabled = true;
|
||||
c.source_rgb_blend_factor = BlendFactor::One;
|
||||
c.destination_rgb_blend_factor = BlendFactor::OneMinusSourceAlpha;
|
||||
c.source_alpha_blend_factor = BlendFactor::One;
|
||||
c.destination_alpha_blend_factor = BlendFactor::OneMinusSourceAlpha;
|
||||
}
|
||||
let mut options = rt::PipelineOptions::default();
|
||||
options.placement = placement(desc.resource_index);
|
||||
options.label = desc.label.map(str::to_owned);
|
||||
@@ -1006,6 +1018,7 @@ mod tests {
|
||||
vertex,
|
||||
fragment,
|
||||
color0_pixel_format: 80,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap()
|
||||
|
||||
@@ -139,6 +139,7 @@ fn numbered_ids<P: reims_vgpu_core::platform::Platform>(d: &P::Device) -> Vec<(&
|
||||
vertex: &v,
|
||||
fragment: &fr,
|
||||
color0_pixel_format: 80,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
};
|
||||
let r = pooled(|| d.new_render_pipeline_state(&desc).unwrap().unwrap());
|
||||
@@ -722,6 +723,7 @@ fn held_draw<P: reims_vgpu_core::platform::Platform>(
|
||||
vertex: &vertex,
|
||||
fragment: &fragment,
|
||||
color0_pixel_format: 80,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap()
|
||||
|
||||
@@ -441,6 +441,7 @@ pub(crate) fn drawn<P: Platform>(
|
||||
vertex: &vertex,
|
||||
fragment: &fragment,
|
||||
color0_pixel_format: 80,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap()
|
||||
|
||||
@@ -2181,6 +2181,7 @@ fn written_at<P: Platform<Surface = OsSurface>>(
|
||||
vertex: &vertex,
|
||||
fragment: &fragment,
|
||||
color0_pixel_format: format,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap()
|
||||
@@ -2246,6 +2247,7 @@ fn written_at<P: Platform<Surface = OsSurface>>(
|
||||
vertex: &vertex,
|
||||
fragment: &fragment,
|
||||
color0_pixel_format: 80,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap()
|
||||
|
||||
@@ -456,6 +456,7 @@ fn case<P: Platform>(p: &P, d: &P::Device, c: Case) -> Seen {
|
||||
vertex: &v,
|
||||
fragment: &f,
|
||||
color0_pixel_format: BGRA8,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap()
|
||||
@@ -509,6 +510,7 @@ fn case<P: Platform>(p: &P, d: &P::Device, c: Case) -> Seen {
|
||||
vertex: &v,
|
||||
fragment: &f,
|
||||
color0_pixel_format: BGRA8,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap()
|
||||
@@ -718,6 +720,7 @@ fn case<P: Platform>(p: &P, d: &P::Device, c: Case) -> Seen {
|
||||
vertex: &v,
|
||||
fragment: &f,
|
||||
color0_pixel_format: BGRA8,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap()
|
||||
@@ -1462,6 +1465,7 @@ fn this_platform_dies_at_every_way_a_write_reaches_the_surface() {
|
||||
vertex: &v,
|
||||
fragment: &f,
|
||||
color0_pixel_format: BGRA8,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap()
|
||||
@@ -1694,6 +1698,7 @@ fn this_platform_draws_through_a_device_pointer_into_a_read_only_buffer() {
|
||||
vertex: &vertex,
|
||||
fragment: &fragment,
|
||||
color0_pixel_format: BGRA8,
|
||||
blend_over: false,
|
||||
resource_index: None,
|
||||
})
|
||||
.unwrap()
|
||||
|
||||
@@ -277,6 +277,18 @@ QEMU's `usb-tablet`, for which the host gets each event's notches too,
|
||||
`test: native::macos::cursor::the_cursor_is_the_glyph_at_the_images_scale`
|
||||
- It hides when the guest hides its cursor.
|
||||
`test: native::macos::cursor::a_hidden_guest_cursor_is_invisible`, `manual`
|
||||
- Where the guest's cursor position changes with no pointer move of the
|
||||
window's in the second before (a mouse passed through to the guest with
|
||||
QEMU's `usb-host`, which the host's pointer never sees, or the guest placing
|
||||
its own), the window draws the guest's cursor into the image where the guest
|
||||
puts it, at the image's scale and clipped to it, and the host's cursor is
|
||||
invisible over the image. A show, a hide or a glyph change that leaves the
|
||||
cursor where it was moves nothing. The window's next pointer move gives the
|
||||
cursor back to the host's pointer.
|
||||
`test: handle::the_guest_leads_its_cursor_when_nothing_of_the_window_s_moved_it`,
|
||||
`test: handle::a_doorbell_reads_the_guest_s_cursor_through_the_sink`,
|
||||
`test: handle::a_cursor_the_guest_moves_on_its_own_is_the_window_s_to_draw`,
|
||||
`manual`
|
||||
- Over the bars and the title bar, it is the host's arrow. `manual`
|
||||
|
||||
## Leaving
|
||||
@@ -393,9 +405,14 @@ runtime's own device. The switches above apply, and `resolution=` too.
|
||||
`test: native::linux::input::the_wheel_sends_the_devices_own_direction`
|
||||
- Cursor: over the image the guest's glyph at the image's scale, with an
|
||||
image at the screen's own scale for HiDPI; hidden when the guest hides
|
||||
its own; the host's arrow over the bars and the title bar.
|
||||
its own; the host's arrow over the bars and the title bar. Where the guest's
|
||||
cursor position changes with no pointer move of the window's in the second
|
||||
before, the window draws the cursor into the image where the guest puts it,
|
||||
and hides the host's over the image, as on macOS.
|
||||
`test: sdl::cursor::a_glyph_is_resampled_by_nearest_pixel`,
|
||||
`test: sdl::cursor::a_short_or_empty_glyph`, `manual`
|
||||
`test: sdl::cursor::a_short_or_empty_glyph`,
|
||||
`test: handle::a_cursor_the_guest_moves_on_its_own_is_the_window_s_to_draw`,
|
||||
`manual`
|
||||
- Leaving: closing a window asks the host to end the VM; the window closes
|
||||
at the display's release, once its swapchain is gone. `manual`
|
||||
|
||||
|
||||
@@ -28,10 +28,26 @@
|
||||
//! on the UI thread, and the opening reads the guest's state itself; one posted after it runs
|
||||
//! behind it. The opening takes the cursor refresh ([`Window::opening`]) before it reads the
|
||||
//! state, so a refresh that found no window does not keep the next change from posting one.
|
||||
//!
|
||||
//! **Who moves the guest's cursor.** The window's pointer events move it, through the host, and
|
||||
//! over the image the host's cursor takes the guest's glyph, at the host's pointer. At each of
|
||||
//! the guest's cursor doorbells the window reads the guest's cursor position through its sink
|
||||
//! ([`Window::cursor_moved`]); a doorbell that leaves it where it was (one rung for a show or a
|
||||
//! hide, say) moves nothing, and so does the first position read. Where the guest moves its
|
||||
//! cursor with no pointer event of the window's in the [`POINTER_LEADS_FOR`] before, something
|
||||
//! else moves it: a mouse the host passed through to the guest, which the host's pointer never
|
||||
//! sees, or the guest placing its own. The window then draws the guest's cursor into its image
|
||||
//! itself, at the position it read ([`DrawnCursor`], which the render thread hands the sink with
|
||||
//! each draw), each move drawing again, and the host's cursor is invisible over the image. The
|
||||
//! window's next pointer event gives the cursor back to the host's pointer. A move the guest
|
||||
//! reports soon after a pointer event of the window's is the guest following it, however late its
|
||||
//! report comes within that time.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use reims_vgpu_core::platform::os::MonoTime;
|
||||
use reims_vgpu_core::sync::Mutex;
|
||||
|
||||
pub use crate::native::FrameSink;
|
||||
@@ -69,28 +85,107 @@ pub struct PixelRect {
|
||||
pub height: u64,
|
||||
}
|
||||
|
||||
/// How long after a pointer event of the window's the guest's cursor moves are taken as following
|
||||
/// it: a move of the guest's later than that, with none of the window's between, is the guest's
|
||||
/// own (the module doc). Well past the guest's answer to a move under load, and short enough that
|
||||
/// a passed-through mouse is followed from its first move once the host's pointer rests.
|
||||
pub(crate) const POINTER_LEADS_FOR: Duration = Duration::from_secs(1);
|
||||
|
||||
/// The guest's side of the window, as the display's callbacks last reported it.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct GuestState {
|
||||
/// The guest's mode, once it has set one.
|
||||
pub(crate) mode: Option<(u16, u16)>,
|
||||
/// The guest's cursor glyph: width, height, hot spot and RGBA pixels.
|
||||
pub(crate) cursor: Option<Glyph>,
|
||||
pub(crate) cursor: Option<Arc<Glyph>>,
|
||||
/// Whether the guest shows its cursor.
|
||||
pub(crate) cursor_visible: bool,
|
||||
/// Who moves the guest's cursor.
|
||||
pub(crate) lead: CursorLead,
|
||||
}
|
||||
|
||||
impl GuestState {
|
||||
/// Whether the host's cursor shows the guest's over the image: while the guest shows its
|
||||
/// cursor and the window does not draw it itself.
|
||||
pub(crate) fn host_cursor_visible(&self) -> bool {
|
||||
self.cursor_visible && !self.lead.guest_leads()
|
||||
}
|
||||
}
|
||||
|
||||
/// Who moves the guest's cursor: the window's pointer events, or the guest on its own, and then
|
||||
/// the window draws the cursor itself (the module doc).
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) struct CursorLead {
|
||||
/// When the window last sent the host a pointer event, on the monotonic clock.
|
||||
pointer_sent: Option<MonoTime>,
|
||||
/// The guest moved its cursor on its own, since the window's last pointer event.
|
||||
guest_leads: bool,
|
||||
/// The guest's cursor position last read, in its mode's pixels.
|
||||
at: Option<(u16, u16)>,
|
||||
}
|
||||
|
||||
impl CursorLead {
|
||||
/// Whether the guest moves its cursor on its own: the window draws it.
|
||||
pub(crate) fn guest_leads(&self) -> bool {
|
||||
self.guest_leads
|
||||
}
|
||||
|
||||
/// The window sent the host a pointer event at `now`: the host's pointer leads. Whether that
|
||||
/// changed who does.
|
||||
pub(crate) fn pointer_sent(&mut self, now: MonoTime) -> bool {
|
||||
self.pointer_sent = Some(now);
|
||||
std::mem::replace(&mut self.guest_leads, false)
|
||||
}
|
||||
|
||||
/// The guest's cursor position last read.
|
||||
pub(crate) fn at(&self) -> Option<(u16, u16)> {
|
||||
self.at
|
||||
}
|
||||
|
||||
/// The guest's cursor was read at `at` at `now`: a move where the position last read was
|
||||
/// another, which makes the guest lead unless the window sent a pointer event within
|
||||
/// [`POINTER_LEADS_FOR`] before. `None` where it did not move (the first read included);
|
||||
/// else whether who leads changed.
|
||||
pub(crate) fn guest_at(&mut self, now: MonoTime, at: (u16, u16)) -> Option<bool> {
|
||||
if self.at.replace(at).is_none_or(|before| before == at) {
|
||||
return None;
|
||||
}
|
||||
let following = self
|
||||
.pointer_sent
|
||||
.is_some_and(|sent| now.saturating_duration_since(sent) < POINTER_LEADS_FOR);
|
||||
if following || self.guest_leads {
|
||||
return Some(false);
|
||||
}
|
||||
self.guest_leads = true;
|
||||
Some(true)
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor glyph, copied from the guest's.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Glyph {
|
||||
pub struct Glyph {
|
||||
/// Pixels wide.
|
||||
pub(crate) width: u32,
|
||||
pub width: u32,
|
||||
/// Pixels high.
|
||||
pub(crate) height: u32,
|
||||
pub height: u32,
|
||||
/// The hot spot, in pixels from the top left.
|
||||
pub(crate) hot_spot: (u16, u16),
|
||||
/// `width * 4` bytes a row, `height` rows, RGBA.
|
||||
pub(crate) rgba: Vec<u8>,
|
||||
pub hot_spot: (u16, u16),
|
||||
/// `width * 4` bytes a row, `height` rows, RGBA, the alpha straight. A row the bytes do not
|
||||
/// reach is transparent.
|
||||
pub rgba: Vec<u8>,
|
||||
}
|
||||
|
||||
/// The guest's cursor as the window draws it into its image, where the guest moves it on its own
|
||||
/// (the module doc): the sink draws `glyph` over the frame, its hot spot at `at` in `mode`'s
|
||||
/// pixels, a glyph pixel to a guest pixel as the image scales the mode, clipped to the image.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DrawnCursor {
|
||||
/// The guest's glyph.
|
||||
pub glyph: Arc<Glyph>,
|
||||
/// The guest's mode, whose pixels `at` is in.
|
||||
pub mode: (u16, u16),
|
||||
/// The guest's cursor position, as the window last read it.
|
||||
pub at: (u16, u16),
|
||||
}
|
||||
|
||||
/// What a window posts to its UI thread: `native`'s posts, or a test's.
|
||||
@@ -260,21 +355,70 @@ impl Window {
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest set a cursor glyph: `rgba` holds `height` rows of `width * 4` bytes.
|
||||
/// The guest set a cursor glyph: `rgba` holds `height` rows of `width * 4` bytes. A cursor
|
||||
/// the window draws is drawn again.
|
||||
pub fn cursor_glyph(&self, width: u32, height: u32, hot_spot: (u16, u16), rgba: &[u8]) {
|
||||
self.guest.lock().cursor = Some(Glyph {
|
||||
width,
|
||||
height,
|
||||
hot_spot,
|
||||
rgba: rgba.to_vec(),
|
||||
});
|
||||
let drawn = {
|
||||
let mut guest = self.guest.lock();
|
||||
guest.cursor = Some(Arc::new(Glyph {
|
||||
width,
|
||||
height,
|
||||
hot_spot,
|
||||
rgba: rgba.to_vec(),
|
||||
}));
|
||||
guest.lead.guest_leads()
|
||||
};
|
||||
self.post_cursor_refresh();
|
||||
if drawn {
|
||||
self.surface.request_draw();
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest showed (`true`) or hid its cursor.
|
||||
/// The guest showed (`true`) or hid its cursor. A cursor the window draws is drawn again.
|
||||
pub fn cursor_show(&self, show: bool) {
|
||||
self.guest.lock().cursor_visible = show;
|
||||
let drawn = {
|
||||
let mut guest = self.guest.lock();
|
||||
guest.cursor_visible = show;
|
||||
guest.lead.guest_leads()
|
||||
};
|
||||
self.post_cursor_refresh();
|
||||
if drawn {
|
||||
self.surface.request_draw();
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest rang the doorbell that reports its cursor's moves: the window reads its cursor
|
||||
/// position through the sink ([`FrameSink::guest_cursor_position`]), on this thread, and
|
||||
/// takes it as `Window::cursor_at` does. Nothing before the sink is attached, after the
|
||||
/// display has ended, without a guest display, or while it is paused.
|
||||
pub fn cursor_moved(&self) {
|
||||
let sink = self.sink.lock().clone();
|
||||
if let Some(at) = sink.and_then(|sink| sink.guest_cursor_position()) {
|
||||
self.cursor_at(at);
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest's cursor is at `at`: where it moved, with no pointer event of the window's in
|
||||
/// the [`POINTER_LEADS_FOR`] before, the window draws the guest's cursor there, and hides the
|
||||
/// host's over the image (the module doc). Each move then draws again.
|
||||
pub(crate) fn cursor_at(&self, at: (u16, u16)) {
|
||||
let (changed, drawn) = {
|
||||
let mut guest = self.guest.lock();
|
||||
let Some(changed) = guest.lead.guest_at(native::now(), at) else {
|
||||
return;
|
||||
};
|
||||
(changed, guest.lead.guest_leads())
|
||||
};
|
||||
if changed {
|
||||
log::debug!(
|
||||
target: "reims_vgpu_window",
|
||||
"the guest moves its cursor on its own: the window draws it"
|
||||
);
|
||||
self.post_cursor_refresh();
|
||||
}
|
||||
if drawn {
|
||||
self.surface.request_draw();
|
||||
}
|
||||
}
|
||||
|
||||
/// Posts a cursor refresh to the UI thread, unless one is posted and has not run yet: it
|
||||
@@ -366,6 +510,34 @@ impl Window {
|
||||
}
|
||||
}
|
||||
|
||||
/// The window is about to send the host a pointer event, which moves the guest's cursor: the
|
||||
/// host's pointer leads it again, and a cursor the window drew goes (the module doc). On the
|
||||
/// UI thread, as the event's callback.
|
||||
pub(crate) fn pointer_sent(&self) {
|
||||
if self.guest.lock().lead.pointer_sent(native::now()) {
|
||||
log::debug!(
|
||||
target: "reims_vgpu_window",
|
||||
"the window moves the guest's cursor: the host's cursor shows it again"
|
||||
);
|
||||
self.post_cursor_refresh();
|
||||
self.surface.request_draw();
|
||||
}
|
||||
}
|
||||
|
||||
/// The cursor the render thread has the sink draw into the image: the guest's, where the
|
||||
/// guest moves it on its own and shows it, once it has a glyph and a mode; else none.
|
||||
pub(crate) fn drawn_cursor(&self) -> Option<DrawnCursor> {
|
||||
let guest = self.guest.lock();
|
||||
if !(guest.lead.guest_leads() && guest.cursor_visible) {
|
||||
return None;
|
||||
}
|
||||
Some(DrawnCursor {
|
||||
glyph: Arc::clone(guest.cursor.as_ref()?),
|
||||
mode: guest.mode?,
|
||||
at: guest.lead.at()?,
|
||||
})
|
||||
}
|
||||
|
||||
/// What the guest last reported.
|
||||
pub(crate) fn guest(&self) -> GuestState {
|
||||
self.guest.lock().clone()
|
||||
@@ -457,7 +629,7 @@ mod tests {
|
||||
/// The guest's mode as the window last read it.
|
||||
mode: Option<(u16, u16)>,
|
||||
/// The guest's cursor glyph as the window last read it.
|
||||
cursor: Option<Glyph>,
|
||||
cursor: Option<Arc<Glyph>>,
|
||||
/// What the display thread does while the opening is posted: before it is queued, and
|
||||
/// once the UI thread has run it, before the attach returns.
|
||||
meanwhile: Option<(Act, Act)>,
|
||||
@@ -568,4 +740,145 @@ mod tests {
|
||||
assert_eq!(read(), (Some((1024, 768)), Some(3)));
|
||||
window.close();
|
||||
}
|
||||
|
||||
/// The guest leads its cursor when it moves it with no pointer event of the window's in the
|
||||
/// time before; a move soon after one is the guest following it; the window's next pointer
|
||||
/// event leads again. The first position read and a read of the same position are no moves.
|
||||
/// Each move's answer says whether who leads changed
|
||||
#[test]
|
||||
fn the_guest_leads_its_cursor_when_nothing_of_the_window_s_moved_it() {
|
||||
let t0 = MonoTime::from_nanos(1_000);
|
||||
let mut lead = CursorLead::default();
|
||||
assert_eq!(
|
||||
lead.guest_at(t0, (5, 5)),
|
||||
None,
|
||||
"the first read moves nothing"
|
||||
);
|
||||
assert_eq!(lead.guest_at(t0, (5, 5)), None, "nor does the same place");
|
||||
assert!(!lead.guest_leads());
|
||||
assert_eq!(
|
||||
lead.guest_at(t0, (6, 5)),
|
||||
Some(true),
|
||||
"no pointer event yet: the guest's own"
|
||||
);
|
||||
let later = t0.saturating_add(POINTER_LEADS_FOR);
|
||||
assert_eq!(lead.guest_at(later, (7, 5)), Some(false));
|
||||
assert!(lead.guest_leads() && lead.at() == Some((7, 5)));
|
||||
let t1 = t0.saturating_add(2 * POINTER_LEADS_FOR);
|
||||
assert!(lead.pointer_sent(t1), "the window's pointer leads again");
|
||||
assert!(!lead.guest_leads() && !lead.pointer_sent(t1));
|
||||
let soon = t1.saturating_add(POINTER_LEADS_FOR - Duration::from_millis(1));
|
||||
assert_eq!(
|
||||
lead.guest_at(soon, (8, 5)),
|
||||
Some(false),
|
||||
"the guest following the pointer"
|
||||
);
|
||||
assert!(!lead.guest_leads());
|
||||
let idle = t1.saturating_add(2 * POINTER_LEADS_FOR);
|
||||
assert_eq!(
|
||||
lead.guest_at(idle, (8, 5)),
|
||||
None,
|
||||
"a doorbell that moves nothing"
|
||||
);
|
||||
assert!(!lead.guest_leads());
|
||||
assert_eq!(
|
||||
lead.guest_at(idle, (9, 5)),
|
||||
Some(true),
|
||||
"the guest's own again"
|
||||
);
|
||||
assert!(lead.guest_leads());
|
||||
}
|
||||
|
||||
/// A sink that answers only the guest's cursor position, as the test sets it.
|
||||
struct PositionSink(Mutex<Option<(u16, u16)>>);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl FrameSink for PositionSink {
|
||||
fn device(
|
||||
&self,
|
||||
) -> Option<objc2::rc::Retained<objc2::runtime::ProtocolObject<dyn objc2_metal::MTLDevice>>>
|
||||
{
|
||||
None
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
_drawable: &objc2::runtime::ProtocolObject<dyn objc2_quartz_core::CAMetalDrawable>,
|
||||
_region: PixelRect,
|
||||
_cursor: Option<&DrawnCursor>,
|
||||
) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn guest_cursor_position(&self) -> Option<(u16, u16)> {
|
||||
*self.0.lock()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl FrameSink for PositionSink {
|
||||
fn presenter(
|
||||
&self,
|
||||
_target: &dyn crate::VulkanTarget,
|
||||
) -> Option<Box<dyn crate::Presenter>> {
|
||||
None
|
||||
}
|
||||
|
||||
fn guest_cursor_position(&self) -> Option<(u16, u16)> {
|
||||
*self.0.lock()
|
||||
}
|
||||
}
|
||||
|
||||
/// At each doorbell the window reads the guest's cursor position through its sink: none
|
||||
/// reads nothing, the first position is no move, and a new one is
|
||||
#[test]
|
||||
fn a_doorbell_reads_the_guest_s_cursor_through_the_sink() {
|
||||
let window = Window::new(WindowConfig::default(), 0, title(0));
|
||||
let sink = Arc::new(PositionSink(Mutex::new(None)));
|
||||
*window.sink.lock() = Some(Arc::clone(&sink) as Arc<dyn FrameSink>);
|
||||
window.cursor_moved();
|
||||
assert_eq!(window.guest().lead.at(), None);
|
||||
*sink.0.lock() = Some((3, 4));
|
||||
window.cursor_moved();
|
||||
assert_eq!(window.guest().lead.at(), Some((3, 4)));
|
||||
assert!(!window.guest().lead.guest_leads());
|
||||
*sink.0.lock() = Some((5, 4));
|
||||
window.cursor_moved();
|
||||
assert!(window.guest().lead.guest_leads());
|
||||
window.close();
|
||||
}
|
||||
|
||||
/// While the guest moves its cursor on its own, the window draws it, with its glyph, in the
|
||||
/// guest's mode, and the host's cursor is invisible over the image; a hidden guest cursor is
|
||||
/// drawn by neither; the window's pointer event gives it back to the host's cursor
|
||||
#[test]
|
||||
fn a_cursor_the_guest_moves_on_its_own_is_the_window_s_to_draw() {
|
||||
let window = Window::new(WindowConfig::default(), 0, title(0));
|
||||
let g = glyph(4);
|
||||
window.cursor_show(true);
|
||||
window.cursor_moved();
|
||||
assert_eq!(window.guest().lead.at(), None, "no sink, no position");
|
||||
window.cursor_at((10, 20));
|
||||
window.cursor_at((11, 20));
|
||||
assert!(window.drawn_cursor().is_none(), "no glyph or mode yet");
|
||||
window.cursor_glyph(g.width, g.height, g.hot_spot, &g.rgba);
|
||||
window.guest_mode(800, 600);
|
||||
let drawn = window.drawn_cursor().unwrap();
|
||||
assert_eq!((*drawn.glyph).clone(), g);
|
||||
assert_eq!((drawn.mode, drawn.at), ((800, 600), (11, 20)));
|
||||
assert!(!window.guest().host_cursor_visible());
|
||||
window.cursor_show(false);
|
||||
assert!(window.drawn_cursor().is_none());
|
||||
assert!(!window.guest().host_cursor_visible());
|
||||
window.cursor_show(true);
|
||||
window.pointer_sent();
|
||||
assert!(window.drawn_cursor().is_none());
|
||||
assert!(window.guest().host_cursor_visible());
|
||||
window.cursor_at((12, 20));
|
||||
assert!(
|
||||
window.drawn_cursor().is_none(),
|
||||
"the guest following the pointer"
|
||||
);
|
||||
window.close();
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,7 @@ pub use config::{
|
||||
MomentumPhase, PointerFn, ScrollEvent, ScrollFn, ScrollPhase, WheelFn, WindowCallbacks,
|
||||
WindowConfig,
|
||||
};
|
||||
pub use handle::{FrameSink, PixelRect, Window};
|
||||
pub use handle::{DrawnCursor, FrameSink, Glyph, PixelRect, Window};
|
||||
pub use policy::{Density, OfferedMode};
|
||||
pub use present::{Drawn, Presenter, VulkanTarget};
|
||||
pub use screens::HostScreen;
|
||||
|
||||
@@ -20,7 +20,7 @@ mod macos;
|
||||
pub use linux::FrameSink;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) use linux::{
|
||||
Surface, close, cursor_changed, guest_mode_changed, host_screens, open, sdl as sdl_os,
|
||||
Surface, close, cursor_changed, guest_mode_changed, host_screens, now, open, sdl as sdl_os,
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
pub use macos::FrameSink;
|
||||
@@ -29,6 +29,6 @@ pub(crate) use macos::sdl as sdl_os;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) use macos::{
|
||||
Surface, close, cursor_changed, guest_mode_changed, host_screens, input_takes, is_iso_keyboard,
|
||||
key_input_captured, launched, monitored_events, open, quit_requested, release_key_input,
|
||||
key_input_captured, launched, monitored_events, now, open, quit_requested, release_key_input,
|
||||
screens_changed,
|
||||
};
|
||||
@@ -14,6 +14,9 @@ mod ui;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_core::platform::os::{Clock as _, MonoTime};
|
||||
use reims_vgpu_vulkan::os::OsClock;
|
||||
|
||||
pub use render::FrameSink;
|
||||
pub(crate) use render::Surface;
|
||||
|
||||
@@ -49,6 +52,11 @@ pub(crate) fn close(id: u64) {
|
||||
ui::post(move || shell::close(id));
|
||||
}
|
||||
|
||||
/// Now, on the monotonic clock the library's platform reads (`OsClock`).
|
||||
pub(crate) fn now() -> MonoTime {
|
||||
OsClock::new().now_mono()
|
||||
}
|
||||
|
||||
/// The host's screens, as SDL lists them (`ui`).
|
||||
pub(crate) fn host_screens() -> Vec<HostScreen> {
|
||||
ui::screens()
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
//!
|
||||
//! One thread per window (`reims-vgpu.window`), started when the window attaches. It waits until
|
||||
//! there is something to draw: a new guest frame, a new layout (the window resized, or moved to a
|
||||
//! screen of another scale, or the guest set a mode) or the window showing again. It draws only
|
||||
//! screen of another scale, or the guest set a mode), the window showing again, or a change of
|
||||
//! the guest's cursor where the window draws it ([`Window::drawn_cursor`], which each draw hands
|
||||
//! the presenter). It draws only
|
||||
//! while the window is shown, once SDL's window and the layout exist, through a presenter the sink
|
||||
//! makes over the window ([`FrameSink::presenter`]), which makes the window's Vulkan surface
|
||||
//! ([`VulkanTarget`]), as `crate::present` says: made at the first draw, tried again after
|
||||
@@ -41,6 +43,14 @@ pub trait FrameSink: Send + Sync {
|
||||
/// Vulkan instance and a swapchain over it. `None` where there is none (the display has
|
||||
/// ended, or this host has no swapchain): the window then stays empty.
|
||||
fn presenter(&self, target: &dyn VulkanTarget) -> Option<Box<dyn Presenter>>;
|
||||
|
||||
/// The guest's cursor position, in its mode's pixels, as the display reads it now: `None`
|
||||
/// once the display has ended, without a guest display, while it is paused, and for a sink
|
||||
/// that cannot tell. Asked on the thread of the display's callbacks
|
||||
/// ([`Window::cursor_moved`](crate::Window::cursor_moved)).
|
||||
fn guest_cursor_position(&self) -> Option<(u16, u16)> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// SDL's window, as its render thread holds it: only to make the window's Vulkan surface of it.
|
||||
@@ -235,7 +245,8 @@ fn run(window: &Window) {
|
||||
};
|
||||
presenting.make(|| sink.presenter(&work.target));
|
||||
}
|
||||
if presenting.draw(work.layout.drawable, work.layout.pixels) {
|
||||
let cursor = window.drawn_cursor();
|
||||
if presenting.draw(work.layout.drawable, work.layout.pixels, cursor.as_ref()) {
|
||||
retry = Some(work);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,9 +107,15 @@ impl Input {
|
||||
}
|
||||
|
||||
/// Sends what the input queued to `window`'s callbacks, while the window lives
|
||||
/// ([`Window::send_each`]).
|
||||
/// ([`Window::send_each`]), each pointer event telling the window first
|
||||
/// ([`Window::pointer_sent`]).
|
||||
pub(crate) fn flush(&mut self, window: &Window) {
|
||||
window.send_each(self.0.take(), input::send);
|
||||
window.send_each(self.0.take(), |callbacks, event| {
|
||||
if matches!(event, input::ToHost::Pointer { .. }) {
|
||||
window.pointer_sent();
|
||||
}
|
||||
input::send(callbacks, event);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -43,13 +43,15 @@ use objc2::runtime::ProtocolObject;
|
||||
use objc2_app_kit::{NSEvent, NSEventMask};
|
||||
use objc2_metal::MTLDevice;
|
||||
use objc2_quartz_core::CAMetalDrawable;
|
||||
use reims_vgpu_core::platform::os::{Clock as _, MonoTime};
|
||||
use reims_vgpu_metal::os::clock::MetalClock;
|
||||
|
||||
pub(crate) use self::iso::is_iso_keyboard;
|
||||
pub(crate) use self::screens::host_screens;
|
||||
pub(crate) use render::Surface;
|
||||
|
||||
use crate::env::WindowImpl;
|
||||
use crate::handle::{PixelRect, Window};
|
||||
use crate::handle::{DrawnCursor, PixelRect, Window};
|
||||
use crate::present::{Presenter, VulkanTarget};
|
||||
use main_thread::post_main;
|
||||
|
||||
@@ -68,13 +70,19 @@ pub trait FrameSink: Send + Sync {
|
||||
fn device(&self) -> Option<Retained<ProtocolObject<dyn MTLDevice>>>;
|
||||
|
||||
/// Draws the display's current frame into `drawable`'s texture over `region`, clearing the
|
||||
/// rest of it, and has the drawable presented, waiting for nothing. False when nothing was
|
||||
/// rest of it, with `cursor` over it where the window draws the guest's cursor, and has the
|
||||
/// drawable presented, waiting for nothing. False when nothing was
|
||||
/// drawn (the display has ended, or refused the encode): the drawable is then dropped
|
||||
/// unpresented. A sink that finishes the frame after it returns (one that copies a frame
|
||||
/// drawn elsewhere into the drawable once it completes) may still drop the drawable
|
||||
/// unpresented where that later step fails, after answering true: the window then shows its
|
||||
/// last image until its next draw.
|
||||
fn draw(&self, drawable: &ProtocolObject<dyn CAMetalDrawable>, region: PixelRect) -> bool;
|
||||
fn draw(
|
||||
&self,
|
||||
drawable: &ProtocolObject<dyn CAMetalDrawable>,
|
||||
region: PixelRect,
|
||||
cursor: Option<&DrawnCursor>,
|
||||
) -> bool;
|
||||
|
||||
/// Whether the sink writes a drawable's texture only as a render target, so that the layer's
|
||||
/// drawables can be framebuffer-only. A sink that copies a frame into the drawable answers
|
||||
@@ -97,6 +105,14 @@ pub trait FrameSink: Send + Sync {
|
||||
let _ = target;
|
||||
None
|
||||
}
|
||||
|
||||
/// The guest's cursor position, in its mode's pixels, as the display reads it now: `None`
|
||||
/// once the display has ended, without a guest display, while it is paused, and for a sink
|
||||
/// that cannot tell. Asked on the thread of the display's callbacks
|
||||
/// ([`Window::cursor_moved`](crate::Window::cursor_moved)).
|
||||
fn guest_cursor_position(&self) -> Option<(u16, u16)> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `REIMS_VGPU_WINDOW_IMPL` names SDL3's window.
|
||||
@@ -160,6 +176,11 @@ pub(crate) fn close(id: u64) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Now, on the monotonic clock the library's platform reads (`MetalClock`).
|
||||
pub(crate) fn now() -> MonoTime {
|
||||
MetalClock::new().now_mono()
|
||||
}
|
||||
|
||||
/// The application has launched, before the windows posted so far open: SDL's video starts,
|
||||
/// where the windows are SDL3's; where the variable names SDL's in a build without it, that is
|
||||
/// logged once, and the windows are AppKit's.
|
||||
|
||||
@@ -546,10 +546,16 @@ impl InputState {
|
||||
}
|
||||
|
||||
/// Sends what the event decided through the host's callbacks while the window lives
|
||||
/// ([`Window::send_each`]), and has the system's hot keys follow capture.
|
||||
/// ([`Window::send_each`]), each pointer event telling the window first
|
||||
/// ([`Window::pointer_sent`]), and has the system's hot keys follow capture.
|
||||
fn finish(&mut self, reaction: Reaction) -> Reaction {
|
||||
self.window
|
||||
.send_each(std::mem::take(&mut self.logic.out), call_host);
|
||||
let window = &self.window;
|
||||
window.send_each(std::mem::take(&mut self.logic.out), |callbacks, event| {
|
||||
if matches!(event, ToHost::Pointer(_)) {
|
||||
window.pointer_sent();
|
||||
}
|
||||
call_host(callbacks, event);
|
||||
});
|
||||
let captured = self.logic.capture.is_captured();
|
||||
if captured != self.holds_hotkeys {
|
||||
self.holds_hotkeys = captured;
|
||||
|
||||
@@ -4,8 +4,10 @@
|
||||
//!
|
||||
//! One thread per window (`reims-vgpu.window`), started when the window attaches. It waits until
|
||||
//! there is something to draw: a new guest frame, a new layout (the view resized or moved to a
|
||||
//! screen of another scale, or the guest set a mode) or the window showing again. It draws only
|
||||
//! while the window is at least partly visible, once its layer and layout exist.
|
||||
//! screen of another scale, or the guest set a mode), the window showing again, or a change of
|
||||
//! the guest's cursor where the window draws it ([`Window::drawn_cursor`], which each draw hands
|
||||
//! the sink). It draws only while the window is at least partly visible, once its layer and
|
||||
//! layout exist.
|
||||
//!
|
||||
//! Where the sink presents itself ([`FrameSink::presents`], the Vulkan platform's), each draw
|
||||
//! goes through the sink's presenter over a Vulkan surface of the layer
|
||||
@@ -57,7 +59,7 @@ use reims_vgpu_metal::os::threads::MetalThreads;
|
||||
use super::main_thread::post_main;
|
||||
use super::metal_surface::LayerTarget;
|
||||
use crate::geometry::Layout;
|
||||
use crate::handle::{FrameSink, PixelRect, Window};
|
||||
use crate::handle::{DrawnCursor, FrameSink, PixelRect, Window};
|
||||
use crate::present::{Presenting, RETRY};
|
||||
|
||||
/// The render thread's stack.
|
||||
@@ -308,11 +310,12 @@ fn run(window: &Window) {
|
||||
let Some(sink) = window.sink() else {
|
||||
continue;
|
||||
};
|
||||
let cursor = window.drawn_cursor();
|
||||
if sink.presents() {
|
||||
if presenting.needs_presenter() {
|
||||
presenting.make(|| sink.presenter(&LayerTarget(layer)));
|
||||
}
|
||||
if presenting.draw(work.layout.drawable, work.layout.pixels) {
|
||||
if presenting.draw(work.layout.drawable, work.layout.pixels, cursor.as_ref()) {
|
||||
retry = Some(work.layout);
|
||||
}
|
||||
continue;
|
||||
@@ -321,7 +324,7 @@ fn run(window: &Window) {
|
||||
set_drawable_size(&layer.0, work.layout.drawable);
|
||||
drawable_size = Some(work.layout.drawable);
|
||||
}
|
||||
draw(&layer.0, &*sink, work.layout.pixels);
|
||||
draw(&layer.0, &*sink, work.layout.pixels, cursor.as_ref());
|
||||
}
|
||||
// The swapchain and the surface go before the layer under them.
|
||||
drop(presenting);
|
||||
@@ -342,16 +345,21 @@ fn set_drawable_size(layer: &CAMetalLayer, (width, height): (u64, u64)) {
|
||||
msg::get("commit", CATransaction::commit);
|
||||
}
|
||||
|
||||
/// Draws the current frame into `layer`'s next drawable over `region`, inside a pool of its own:
|
||||
/// nothing when the layer gives no drawable. A drawable the sink draws nothing into is dropped
|
||||
/// unpresented.
|
||||
fn draw(layer: &CAMetalLayer, sink: &dyn FrameSink, region: PixelRect) {
|
||||
/// Draws the current frame into `layer`'s next drawable over `region`, with `cursor` over it,
|
||||
/// inside a pool of its own: nothing when the layer gives no drawable. A drawable the sink draws
|
||||
/// nothing into is dropped unpresented.
|
||||
fn draw(
|
||||
layer: &CAMetalLayer,
|
||||
sink: &dyn FrameSink,
|
||||
region: PixelRect,
|
||||
cursor: Option<&DrawnCursor>,
|
||||
) {
|
||||
autoreleasepool(|_| {
|
||||
let Some(drawable) = msg::get("nextDrawable", || layer.nextDrawable()) else {
|
||||
log::debug!("no drawable: the frame is skipped");
|
||||
return;
|
||||
};
|
||||
let drew = sink.draw(&drawable, region);
|
||||
let drew = sink.draw(&drawable, region, cursor);
|
||||
log::trace!("drawn into a drawable over {region:?}: {drew}");
|
||||
});
|
||||
}
|
||||
|
||||
@@ -495,8 +495,9 @@ impl DisplayView {
|
||||
self.invalidate_cursor();
|
||||
}
|
||||
|
||||
/// The cursor rectangle over the image, with the guest's cursor; none (the host's arrow)
|
||||
/// before the guest has set one.
|
||||
/// The cursor rectangle over the image, with the guest's cursor, invisible while the window
|
||||
/// draws it itself (`handle`'s module doc); none (the host's arrow) before the guest has set
|
||||
/// one.
|
||||
fn add_cursor_rect(&self) {
|
||||
let ivars = self.ivars();
|
||||
let guest = ivars.window.guest();
|
||||
@@ -504,8 +505,8 @@ impl DisplayView {
|
||||
let per_pixel = geometry::cursor_points_per_pixel(image, guest.mode.unwrap_or((0, 0)));
|
||||
let cursor = ivars.cursors.try_borrow_mut().ok().and_then(|mut cursors| {
|
||||
cursors.cursor(
|
||||
guest.cursor.as_ref(),
|
||||
guest.cursor_visible,
|
||||
guest.cursor.as_deref(),
|
||||
guest.host_cursor_visible(),
|
||||
per_pixel,
|
||||
self.mtm(),
|
||||
)
|
||||
|
||||
@@ -17,7 +17,7 @@ use std::time::Duration;
|
||||
|
||||
use ash::vk;
|
||||
|
||||
use crate::handle::PixelRect;
|
||||
use crate::handle::{DrawnCursor, PixelRect};
|
||||
|
||||
/// How long the render thread waits before it draws again where no image came in time: about a
|
||||
/// refresh at 120 Hz. Before it answers [`Drawn::Retry`] for want of an image, the presenter has
|
||||
@@ -48,9 +48,15 @@ pub enum Drawn {
|
||||
/// What a window's render thread presents through: the sink's, over the window's swapchain.
|
||||
pub trait Presenter: Send {
|
||||
/// Draws the display's current frame into the next image of `drawable` pixels (width,
|
||||
/// height), over `region` of it, clearing the rest, and presents it. Blocks only for the next
|
||||
/// image, up to a few frames.
|
||||
fn draw(&mut self, drawable: (u64, u64), region: PixelRect) -> Drawn;
|
||||
/// height), over `region` of it, clearing the rest, with `cursor` over it where the window
|
||||
/// draws the guest's cursor, and presents it. Blocks only for the next image, up to a few
|
||||
/// frames.
|
||||
fn draw(
|
||||
&mut self,
|
||||
drawable: (u64, u64),
|
||||
region: PixelRect,
|
||||
cursor: Option<&DrawnCursor>,
|
||||
) -> Drawn;
|
||||
}
|
||||
|
||||
/// What makes a window's Vulkan surface, on its render thread: on Linux SDL's window, on macOS
|
||||
@@ -93,16 +99,21 @@ impl Presenting {
|
||||
}
|
||||
|
||||
/// Has the presenter draw the current frame into an image of `drawable` pixels over
|
||||
/// `region`: whether to draw again after [`RETRY`] (no image came in time). Nothing without
|
||||
/// a presenter.
|
||||
pub(crate) fn draw(&mut self, drawable: (u64, u64), region: PixelRect) -> bool {
|
||||
/// `region`, with `cursor` over it: whether to draw again after [`RETRY`] (no image came in
|
||||
/// time). Nothing without a presenter.
|
||||
pub(crate) fn draw(
|
||||
&mut self,
|
||||
drawable: (u64, u64),
|
||||
region: PixelRect,
|
||||
cursor: Option<&DrawnCursor>,
|
||||
) -> bool {
|
||||
if self.ended {
|
||||
return false;
|
||||
}
|
||||
let Some(presenter) = self.presenter.as_mut() else {
|
||||
return false;
|
||||
};
|
||||
let drawn = presenter.draw(drawable, region);
|
||||
let drawn = presenter.draw(drawable, region, cursor);
|
||||
if drawn == Drawn::Ended {
|
||||
self.presenter = None;
|
||||
}
|
||||
@@ -144,7 +155,12 @@ mod tests {
|
||||
struct Scripted(VecDeque<Drawn>);
|
||||
|
||||
impl Presenter for Scripted {
|
||||
fn draw(&mut self, _drawable: (u64, u64), _region: PixelRect) -> Drawn {
|
||||
fn draw(
|
||||
&mut self,
|
||||
_drawable: (u64, u64),
|
||||
_region: PixelRect,
|
||||
_cursor: Option<&DrawnCursor>,
|
||||
) -> Drawn {
|
||||
self.0.pop_front().unwrap_or(Drawn::Presented)
|
||||
}
|
||||
}
|
||||
@@ -187,16 +203,16 @@ mod tests {
|
||||
assert!(p.needs_presenter());
|
||||
p.make(|| scripted(&[Drawn::Retry, Drawn::Presented, Drawn::Ended]));
|
||||
assert!(!p.needs_presenter());
|
||||
assert!(p.draw((4, 4), REGION), "no image: a retry");
|
||||
assert!(!p.draw((4, 4), REGION));
|
||||
assert!(!p.draw((4, 4), REGION));
|
||||
assert!(p.draw((4, 4), REGION, None), "no image: a retry");
|
||||
assert!(!p.draw((4, 4), REGION, None));
|
||||
assert!(!p.draw((4, 4), REGION, None));
|
||||
assert!(p.needs_presenter(), "an ended presenter is made again");
|
||||
p.make(|| None);
|
||||
assert!(
|
||||
!p.needs_presenter(),
|
||||
"no presenter: the window stays as it is"
|
||||
);
|
||||
assert!(!p.draw((4, 4), REGION));
|
||||
assert!(!p.draw((4, 4), REGION, None));
|
||||
}
|
||||
|
||||
/// Presenters that end too many times in a row leave the window as it is
|
||||
@@ -206,7 +222,7 @@ mod tests {
|
||||
for _ in 0..=RENEWALS {
|
||||
assert!(p.needs_presenter());
|
||||
p.make(|| scripted(&[Drawn::Ended]));
|
||||
p.draw((4, 4), REGION);
|
||||
p.draw((4, 4), REGION, None);
|
||||
}
|
||||
assert!(!p.needs_presenter());
|
||||
}
|
||||
|
||||
@@ -476,20 +476,21 @@ impl Shell {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the cursor: over the image the guest's, or none while the guest hides its own; the
|
||||
/// host's arrow elsewhere and before the guest has set one.
|
||||
/// Sets the cursor: over the image the guest's, or none while the guest hides its own or the
|
||||
/// window draws it itself (`handle`'s module doc); the host's arrow elsewhere and before the
|
||||
/// guest has set one.
|
||||
fn refresh_cursor(&mut self) {
|
||||
let guest = self.window.guest();
|
||||
let ours = if self.over_image {
|
||||
let per_pixel =
|
||||
geometry::cursor_points_per_pixel(self.layout.image, guest.mode.unwrap_or((0, 0)));
|
||||
if !guest.cursor_visible && guest.cursor.is_some() {
|
||||
if !guest.host_cursor_visible() && guest.cursor.is_some() {
|
||||
// SAFETY: SDL's video runs on this thread.
|
||||
unsafe { SDL_HideCursor() };
|
||||
return;
|
||||
}
|
||||
self.cursor
|
||||
.cursor(guest.cursor.as_ref(), per_pixel, self.density)
|
||||
.cursor(guest.cursor.as_deref(), per_pixel, self.density)
|
||||
.map(|c| c.raw())
|
||||
} else {
|
||||
None
|
||||
|
||||
@@ -11,6 +11,13 @@
|
||||
//! bits. Each callback tells the window first, then calls the host's where the host gave one.
|
||||
//! Without a window, nothing here runs and the display is as the config says.
|
||||
//!
|
||||
//! **The guest's cursor.** At each cursor doorbell the window reads the guest's cursor position
|
||||
//! through its sink ([`SinkDisplay::cursor_position`]), on the thread of the display's callbacks,
|
||||
//! through the display's core, which never ends the process: none while the guest display is
|
||||
//! paused. Where the guest moves its cursor on its own (`reims_vgpu_window`'s `handle`), each
|
||||
//! sink has the display draw it over the frame at that position, in the frame's own render pass,
|
||||
//! with the objects made before the frame's encode (`cursor`).
|
||||
//!
|
||||
//! **Lifetime: a window frame is a frame.** Nothing on the window's side holds the display: the
|
||||
//! tee's closures hold the window, and the sink holds the display weakly. A draw upgrades that
|
||||
//! reference for its encode and commit alone, and the encode's completion handler holds the
|
||||
@@ -25,13 +32,14 @@
|
||||
use std::any::{Any, TypeId};
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use reims_vgpu_core::display::Display as CoreDisplay;
|
||||
use reims_vgpu_core::display::{Display as CoreDisplay, DisplayCore};
|
||||
use reims_vgpu_core::platform::Platform;
|
||||
use reims_vgpu_core::platform::command::{CommandBuffer as _, CommandQueue as _};
|
||||
use reims_vgpu_core::platform::types::{MtlOrigin, MtlRegion, MtlSize};
|
||||
use reims_vgpu_core::raise::OnFault;
|
||||
use reims_vgpu_core::sync::Mutex;
|
||||
use reims_vgpu_window::policy::{self, Density, OfferedMode};
|
||||
use reims_vgpu_window::{FrameSink, HostScreen, PixelRect, Window};
|
||||
use reims_vgpu_window::{DrawnCursor, FrameSink, HostScreen, PixelRect, Window};
|
||||
|
||||
use crate::display::{CursorGlyph, DisplayCallbacks, no_catch};
|
||||
use crate::entry;
|
||||
@@ -139,6 +147,8 @@ pub(crate) trait GuestEvents: Send + Sync + 'static {
|
||||
fn cursor_glyph(&self, glyph: &CursorGlyph<'_>);
|
||||
/// The guest showed (`true`) or hid its cursor.
|
||||
fn cursor_show(&self, show: bool);
|
||||
/// The guest moved its cursor, or rang the doorbell that reports its moves.
|
||||
fn cursor_moved(&self);
|
||||
}
|
||||
|
||||
impl GuestEvents for Window {
|
||||
@@ -157,12 +167,15 @@ impl GuestEvents for Window {
|
||||
fn cursor_show(&self, show: bool) {
|
||||
Window::cursor_show(self, show);
|
||||
}
|
||||
|
||||
fn cursor_moved(&self) {
|
||||
Window::cursor_moved(self);
|
||||
}
|
||||
}
|
||||
|
||||
/// A window display's callbacks: each of the first four tells `window`, then calls the host's
|
||||
/// in `host` where it gave one; `cursor_move` is the host's alone, and does nothing without it.
|
||||
/// All five are present, which the guest reads (module doc). The closures hold the window and
|
||||
/// the host's closures, never the display.
|
||||
/// A window display's callbacks: each tells `window`, then calls the host's in `host` where it
|
||||
/// gave one. All five are present, which the guest reads (module doc). The closures hold the
|
||||
/// window and the host's closures, never the display.
|
||||
pub(crate) fn tee<W: GuestEvents>(window: &Arc<W>, host: DisplayCallbacks) -> DisplayCallbacks {
|
||||
let DisplayCallbacks {
|
||||
mode_change,
|
||||
@@ -199,7 +212,13 @@ pub(crate) fn tee<W: GuestEvents>(window: &Arc<W>, host: DisplayCallbacks) -> Di
|
||||
f(show);
|
||||
}
|
||||
});
|
||||
let cursor_move: crate::CursorMoveFn = cursor_move.unwrap_or_else(|| Arc::new(|| {}));
|
||||
let w = window.clone();
|
||||
let cursor_move: crate::CursorMoveFn = Arc::new(move || {
|
||||
w.cursor_moved();
|
||||
if let Some(f) = &cursor_move {
|
||||
f();
|
||||
}
|
||||
});
|
||||
DisplayCallbacks {
|
||||
mode_change: Some(mode_change),
|
||||
new_frame: Some(new_frame),
|
||||
@@ -237,8 +256,9 @@ impl Drop for WindowLink {
|
||||
|
||||
/// What a window sink draws from: the display, held weakly, and the process's frame queue for its
|
||||
/// device, whose command buffers the sink's frames are encoded in. Neither keeps the display
|
||||
/// alive (module doc). Every sink draws through it, each frame a [`WindowFrame`], and each frame
|
||||
/// it commits counts as a window frame in the display's statistics, where they are on
|
||||
/// alive (module doc). Every sink draws through it, each frame a [`WindowFrame`], with the
|
||||
/// guest's cursor over it where the window draws it ([`cursor::CursorPass`]), and each frame it
|
||||
/// commits counts as a window frame in the display's statistics, where they are on
|
||||
/// ([`crate::stats`]).
|
||||
#[cfg_attr(
|
||||
not(any(target_os = "macos", feature = "vulkan")),
|
||||
@@ -247,10 +267,14 @@ impl Drop for WindowLink {
|
||||
pub(crate) struct SinkDisplay<P: Platform> {
|
||||
/// The display, held only for a draw.
|
||||
display: Weak<CoreDisplay<P>>,
|
||||
/// Its core, which the guest's cursor position is read through.
|
||||
core: Weak<DisplayCore<P>>,
|
||||
/// The frame queue.
|
||||
queue: P::CommandQueue,
|
||||
/// The display's statistics, where they are on.
|
||||
stats: Option<Arc<DisplayStats>>,
|
||||
/// What draws the guest's cursor over a frame; only the window's render thread draws.
|
||||
cursor: Mutex<cursor::CursorPass<P>>,
|
||||
}
|
||||
|
||||
/// One window frame, as a sink draws it: the steps in which the sinks differ, which
|
||||
@@ -274,15 +298,38 @@ pub(crate) trait WindowFrame<P: Platform> {
|
||||
expect(dead_code, reason = "only the Metal and Vulkan platforms' sinks draw")
|
||||
)]
|
||||
impl<P: Platform> SinkDisplay<P> {
|
||||
/// `display`, drawn in command buffers of `queue`, the frame queue of its device.
|
||||
pub(crate) fn new(display: Weak<CoreDisplay<P>>, queue: P::CommandQueue) -> SinkDisplay<P> {
|
||||
/// `display`, drawn in command buffers of `queue`, the frame queue of its device, the
|
||||
/// guest's cursor glyph in textures `own_texture` makes ([`cursor::OwnTexture`]). Its maker
|
||||
/// holds the display, just made, so the upgrade that reaches its core is never its last
|
||||
/// release.
|
||||
pub(crate) fn new(
|
||||
display: Weak<CoreDisplay<P>>,
|
||||
queue: P::CommandQueue,
|
||||
own_texture: cursor::OwnTexture<P>,
|
||||
) -> SinkDisplay<P> {
|
||||
let core = display
|
||||
.upgrade()
|
||||
.map_or_else(Weak::new, |d| Arc::downgrade(d.core()));
|
||||
SinkDisplay {
|
||||
stats: stats::of_display(&display),
|
||||
display,
|
||||
core,
|
||||
queue,
|
||||
cursor: Mutex::new(cursor::CursorPass::new(own_texture)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest's cursor position, in its mode's pixels, as the display reads it now
|
||||
/// ([`DisplayCore::guest_cursor_position`]): what the sinks answer
|
||||
/// [`FrameSink::guest_cursor_position`] with. Asked on the thread of the display's callbacks,
|
||||
/// where the block that runs one holds the core, so the core's upgrade here is never its last
|
||||
/// release, and never the display's end, which its own reference runs. `None` once the core
|
||||
/// has gone.
|
||||
pub(crate) fn cursor_position(&self) -> Option<(u16, u16)> {
|
||||
let at = self.core.upgrade()?.guest_cursor_position()?;
|
||||
Some((at.x, at.y))
|
||||
}
|
||||
|
||||
/// The display's statistics, where they are on: a sink that measures its frames' GPU time
|
||||
/// reports it there.
|
||||
#[cfg_attr(
|
||||
@@ -296,10 +343,12 @@ impl<P: Platform> SinkDisplay<P> {
|
||||
self.stats.as_ref()
|
||||
}
|
||||
|
||||
/// Draws `frame`: the display's current frame over `region` into its texture, in a new
|
||||
/// command buffer of the frame queue, which is committed after `frame` has seen it. In order:
|
||||
/// the display's upgrade, the command buffer, [`WindowFrame::texture`], the encode,
|
||||
/// [`WindowFrame::encoded`] and the commit: `true` once committed. `false`, with nothing
|
||||
/// Draws `frame`: the display's current frame over `region` into its texture, with `cursor`
|
||||
/// over it, in a new command buffer of the frame queue, which is committed after `frame` has
|
||||
/// seen it. In order: the display's upgrade, the command buffer, [`WindowFrame::texture`], the
|
||||
/// cursor's objects ([`cursor::CursorPass::prepare`]), the encode, with the cursor drawn in
|
||||
/// the display's pass ([`cursor::Prepared::draw`]), [`WindowFrame::encoded`] and the commit:
|
||||
/// `true` once committed. `false`, with nothing
|
||||
/// committed, when the display has ended, when the frame queue gives no command buffer, when
|
||||
/// the frame has no texture, or when the display refuses the encode (a texture on another
|
||||
/// device, or one it cannot render into). A command buffer not committed goes with nothing
|
||||
@@ -308,12 +357,17 @@ impl<P: Platform> SinkDisplay<P> {
|
||||
/// The display is held from its upgrade to the commit, and the encode's completion handler
|
||||
/// holds it on until the frame completes. So when the host has released the display in the
|
||||
/// meantime, this draw's release, inside this entry, may be the display's end.
|
||||
pub(crate) fn encode(&self, region: PixelRect, frame: impl WindowFrame<P>) -> bool {
|
||||
pub(crate) fn encode(
|
||||
&self,
|
||||
region: PixelRect,
|
||||
cursor: Option<&DrawnCursor>,
|
||||
frame: impl WindowFrame<P>,
|
||||
) -> bool {
|
||||
entry::run(|_| {
|
||||
let Some(display) = self.display.upgrade() else {
|
||||
return false;
|
||||
};
|
||||
let committed = self.commit_frame(&display, region, frame);
|
||||
let committed = self.commit_frame(&display, region, cursor, frame);
|
||||
drop(display);
|
||||
committed
|
||||
})
|
||||
@@ -324,6 +378,7 @@ impl<P: Platform> SinkDisplay<P> {
|
||||
&self,
|
||||
display: &CoreDisplay<P>,
|
||||
region: PixelRect,
|
||||
cursor: Option<&DrawnCursor>,
|
||||
mut frame: impl WindowFrame<P>,
|
||||
) -> bool {
|
||||
let Some(command_buffer) = no_catch(self.queue.command_buffer(OnFault::Die)) else {
|
||||
@@ -332,11 +387,19 @@ impl<P: Platform> SinkDisplay<P> {
|
||||
let Some(texture) = frame.texture() else {
|
||||
return false;
|
||||
};
|
||||
let region = MtlRegion::new(
|
||||
let cursor = cursor.and_then(|c| self.cursor.lock().prepare(display, texture, region, c));
|
||||
let frame_region = MtlRegion::new(
|
||||
MtlOrigin::new(region.x, region.y, 0),
|
||||
MtlSize::new(region.width, region.height, 1),
|
||||
);
|
||||
if !no_catch(display.encode_current_frame(&command_buffer, texture, region)) {
|
||||
let overlay = cursor.as_ref().map(cursor::Prepared::draw);
|
||||
let encoded = display.encode_current_frame_with(
|
||||
&command_buffer,
|
||||
texture,
|
||||
frame_region,
|
||||
overlay.as_ref(),
|
||||
);
|
||||
if !no_catch(encoded) {
|
||||
return false;
|
||||
}
|
||||
frame.encoded(&command_buffer);
|
||||
@@ -348,6 +411,11 @@ impl<P: Platform> SinkDisplay<P> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(
|
||||
not(any(target_os = "macos", feature = "vulkan")),
|
||||
expect(dead_code, reason = "only the Metal and Vulkan platforms' sinks draw")
|
||||
)]
|
||||
mod cursor;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod metal;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
//! The guest's cursor drawn into a window frame where the window draws it itself, the guest moving
|
||||
//! it on its own ([`DrawnCursor`], `reims_vgpu_window::handle`'s module doc): the glyph over the
|
||||
//! frame the display drew, by its alpha, at the guest's cursor position the window last read.
|
||||
//!
|
||||
//! The glyph is a second draw in the display's own render pass, after the frame's
|
||||
//! ([`DisplayCore::encode_current_frame_with`]), so the frame's target is stored once, with no
|
||||
//! pass that loads it again: the display's strip, a quad over the whole viewport, drawn over a
|
||||
//! viewport that is the glyph's rectangle in the target, its hot spot at the cursor's position, a
|
||||
//! glyph pixel to a guest pixel at the image's scale, with a scissor that clips it to the image.
|
||||
//! It draws with the display's overlay pipeline for the target's format
|
||||
//! ([`DisplayCore::overlay_pipeline`]): the display's vertex function and
|
||||
//! `displayPresentFragment`, which samples the glyph as the frame is sampled, filtered where the
|
||||
//! image scales it, blending over by alpha (`RenderPipelineDesc::blend_over`). The guest's alpha
|
||||
//! is straight, and the texture holds the glyph premultiplied, so that the filter, where the
|
||||
//! image scales the glyph, does not darken its edges with the colour of its transparent pixels:
|
||||
//! at one texel a pixel, each pixel is the glyph's colour over the frame's by its alpha, as with
|
||||
//! straight alpha. The glyph's colours are drawn as the guest gives them, with no gamma table or
|
||||
//! colour matrix, as the host's cursor shows them over the image.
|
||||
//!
|
||||
//! **What the guest reads.** The draw makes no buffer: it binds the display's. The pipeline is
|
||||
//! the display's, kept in its cache with its own and made of its functions, so it lives as they
|
||||
//! do. The glyph's texture is the sink's platform's own ([`OwnTexture`]): on the Vulkan platform
|
||||
//! one that takes no resource ID and no range of Metal's space, so that no address or ID the
|
||||
//! guest reads moves for it; on Metal a plain texture, a resource of Metal's like the layer's
|
||||
//! drawables the window already draws into. The texture is made again only for a new glyph.
|
||||
//!
|
||||
//! **Before the frame.** The pipeline and the texture are made before the display encodes the
|
||||
//! frame ([`CursorPass::prepare`]), from which the frame counts as in flight, which a guest's
|
||||
//! present waits on. What the platform refuses of them leaves the frame without the guest's
|
||||
//! cursor, logged once; the host's cursor stays hidden over the image while the guest leads, so
|
||||
//! neither shows. An encode the platform refuses dies at its send, as the display's own does; the
|
||||
//! draw's values are ones the platforms take: a scissor inside the target, and a viewport inside
|
||||
//! the least bounds Vulkan sets every device (the runtime hands a viewport to Vulkan as it is),
|
||||
//! [`VIEWPORT_BOUNDS`] and [`VIEWPORT_DIMENSION`]; a glyph that would reach past them is not drawn
|
||||
//! (only near the far edge of a window over 8000 pixels across). Nothing here reaches the guest
|
||||
//! or the C API: the cursor is in the window's pixels alone.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_core::display::DisplayCore;
|
||||
use reims_vgpu_core::display::pipeline::OverlayDraw;
|
||||
use reims_vgpu_core::platform::resource::Texture as _;
|
||||
use reims_vgpu_core::platform::types::{
|
||||
MtlOrigin, MtlRegion, MtlScissorRect, MtlSize, MtlViewport,
|
||||
};
|
||||
use reims_vgpu_core::platform::values::TextureDesc;
|
||||
use reims_vgpu_core::platform::{Handle as _, HostRange, Platform};
|
||||
use reims_vgpu_window::{DrawnCursor, Glyph, PixelRect};
|
||||
|
||||
use crate::display::no_catch;
|
||||
|
||||
/// The least `viewportBoundsRange` Vulkan sets every device: a viewport's edges lie inside it.
|
||||
const VIEWPORT_BOUNDS: (f64, f64) = (-8192.0, 8191.0);
|
||||
/// The least `maxViewportDimensions` Vulkan sets every device: a viewport's width and height.
|
||||
const VIEWPORT_DIMENSION: f64 = 4096.0;
|
||||
|
||||
/// How a sink's platform makes the glyph's texture from its descriptor: a texture the guest never
|
||||
/// reaches (the module doc), or `None` where the platform makes none.
|
||||
pub(crate) type OwnTexture<P> = fn(
|
||||
&<P as Platform>::Device,
|
||||
&<P as Platform>::TextureDescriptor,
|
||||
) -> Option<<P as Platform>::Texture>;
|
||||
|
||||
/// What draws the guest's cursor over a window's frames, kept from one frame to the next.
|
||||
pub(crate) struct CursorPass<P: Platform> {
|
||||
/// How the glyph's texture is made.
|
||||
own_texture: OwnTexture<P>,
|
||||
/// The glyph last drawn, and its texture.
|
||||
glyph: Option<(Arc<Glyph>, P::Texture)>,
|
||||
/// A refusal of the platform's has been logged.
|
||||
refusal_logged: bool,
|
||||
}
|
||||
|
||||
/// One frame's cursor, made ready before the display encodes the frame
|
||||
/// ([`CursorPass::prepare`]), which draws it ([`Prepared::draw`]).
|
||||
pub(crate) struct Prepared<P: Platform> {
|
||||
/// The display's overlay pipeline for the target's format.
|
||||
pipeline: P::RenderPipeline,
|
||||
/// The glyph's texture.
|
||||
texture: P::Texture,
|
||||
/// The glyph's rectangle in the target, and its clip to the image ([`placement`]).
|
||||
viewport: MtlViewport,
|
||||
/// The scissor.
|
||||
scissor: MtlScissorRect,
|
||||
}
|
||||
|
||||
impl<P: Platform> CursorPass<P> {
|
||||
/// A pass that has made nothing yet, whose glyph textures `own_texture` makes.
|
||||
pub(crate) fn new(own_texture: OwnTexture<P>) -> CursorPass<P> {
|
||||
CursorPass {
|
||||
own_texture,
|
||||
glyph: None,
|
||||
refusal_logged: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// What drawing `cursor` over the frame `display` draws into `target` over `region` binds:
|
||||
/// the display's overlay pipeline for the target's format, made the first time
|
||||
/// ([`DisplayCore::overlay_pipeline`]), the glyph's texture, made again only for a new
|
||||
/// glyph, and where it draws ([`placement`]). Asked before the frame is encoded (the module
|
||||
/// doc). `None` where nothing would show, and where the platform refuses the pipeline or the
|
||||
/// texture (logged once).
|
||||
pub(crate) fn prepare(
|
||||
&mut self,
|
||||
display: &DisplayCore<P>,
|
||||
target: &P::Texture,
|
||||
region: PixelRect,
|
||||
cursor: &DrawnCursor,
|
||||
) -> Option<Prepared<P>> {
|
||||
let (viewport, scissor) = placement(region, (target.width(), target.height()), cursor)?;
|
||||
let Some(pipeline) = display.overlay_pipeline(target.pixel_format()) else {
|
||||
return self.refused("the pipeline");
|
||||
};
|
||||
let texture = match &self.glyph {
|
||||
Some((drawn, texture)) if Arc::ptr_eq(drawn, &cursor.glyph) => texture.clone_ref(),
|
||||
_ => {
|
||||
let made = display.mtl_device().and_then(|device| {
|
||||
glyph_texture(display.platform(), device, self.own_texture, &cursor.glyph)
|
||||
});
|
||||
let Some(texture) = made else {
|
||||
return self.refused("a texture for the glyph");
|
||||
};
|
||||
self.glyph = Some((Arc::clone(&cursor.glyph), texture.clone_ref()));
|
||||
texture
|
||||
}
|
||||
};
|
||||
Some(Prepared {
|
||||
pipeline,
|
||||
texture,
|
||||
viewport,
|
||||
scissor,
|
||||
})
|
||||
}
|
||||
|
||||
/// Logs, the first time, that the platform refused `what`: the cursor is not drawn.
|
||||
fn refused<T>(&mut self, what: &str) -> Option<T> {
|
||||
if !std::mem::replace(&mut self.refusal_logged, true) {
|
||||
log::warn!(
|
||||
target: "reims_vgpu::window",
|
||||
"the window draws no guest cursor: the platform refused {what}"
|
||||
);
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> Prepared<P> {
|
||||
/// The draw the display makes of the cursor in its pass, after the frame's (the module doc).
|
||||
pub(crate) fn draw(&self) -> OverlayDraw<'_, P> {
|
||||
OverlayDraw {
|
||||
pipeline: &self.pipeline,
|
||||
texture: &self.texture,
|
||||
viewport: self.viewport,
|
||||
scissor: self.scissor,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where `cursor` draws over `region` of a target of `size` pixels: the viewport, the glyph's
|
||||
/// rectangle in the target, its hot spot at the cursor's position in the mode's pixels, a glyph
|
||||
/// pixel to a guest pixel at the image's scale; and the scissor, the target's pixels that
|
||||
/// rectangle touches inside the image and the target. The viewport may reach past the target,
|
||||
/// which only the scissor clips. `None` where nothing would show: an empty mode, glyph or
|
||||
/// region, or a glyph wholly off the image; and where the viewport would reach past
|
||||
/// [`VIEWPORT_BOUNDS`] or be larger than [`VIEWPORT_DIMENSION`] (the module doc).
|
||||
fn placement(
|
||||
region: PixelRect,
|
||||
size: (u64, u64),
|
||||
cursor: &DrawnCursor,
|
||||
) -> Option<(MtlViewport, MtlScissorRect)> {
|
||||
let (mode, glyph) = (cursor.mode, &cursor.glyph);
|
||||
if mode.0 == 0 || mode.1 == 0 || glyph.width == 0 || glyph.height == 0 {
|
||||
return None;
|
||||
}
|
||||
#[expect(clippy::as_conversions, reason = "u64 to f64 rounds to nearest")]
|
||||
let [x, y, width, height, target_width, target_height] = [
|
||||
region.x,
|
||||
region.y,
|
||||
region.width,
|
||||
region.height,
|
||||
size.0,
|
||||
size.1,
|
||||
]
|
||||
.map(|v| v as f64);
|
||||
let (per_x, per_y) = (width / f64::from(mode.0), height / f64::from(mode.1));
|
||||
let left = x + (f64::from(cursor.at.0) - f64::from(glyph.hot_spot.0)) * per_x;
|
||||
let top = y + (f64::from(cursor.at.1) - f64::from(glyph.hot_spot.1)) * per_y;
|
||||
let (glyph_width, glyph_height) = (
|
||||
f64::from(glyph.width) * per_x,
|
||||
f64::from(glyph.height) * per_y,
|
||||
);
|
||||
let (x0, y0) = (left.floor().max(x), top.floor().max(y));
|
||||
let x1 = (left + glyph_width).ceil().min(x + width).min(target_width);
|
||||
let y1 = (top + glyph_height)
|
||||
.ceil()
|
||||
.min(y + height)
|
||||
.min(target_height);
|
||||
if x1 <= x0 || y1 <= y0 {
|
||||
return None;
|
||||
}
|
||||
let (low, high) = VIEWPORT_BOUNDS;
|
||||
let within = |start: f64, length: f64| {
|
||||
start >= low && start + length <= high && length <= VIEWPORT_DIMENSION
|
||||
};
|
||||
if !(within(left, glyph_width) && within(top, glyph_height)) {
|
||||
return None;
|
||||
}
|
||||
#[expect(
|
||||
clippy::as_conversions,
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
reason = "whole pixels inside the target, which u64 holds"
|
||||
)]
|
||||
let [sx, sy, sw, sh] = [x0, y0, x1 - x0, y1 - y0].map(|v| v as u64);
|
||||
let viewport = MtlViewport {
|
||||
origin_x: left,
|
||||
origin_y: top,
|
||||
width: glyph_width,
|
||||
height: glyph_height,
|
||||
znear: 0.0,
|
||||
zfar: 1.0,
|
||||
};
|
||||
let scissor = MtlScissorRect {
|
||||
x: sx,
|
||||
y: sy,
|
||||
width: sw,
|
||||
height: sh,
|
||||
};
|
||||
Some((viewport, scissor))
|
||||
}
|
||||
|
||||
/// `glyph`'s pixels in a texture `own_texture` makes, RGBA8, premultiplied (module doc), read by
|
||||
/// shaders, a row its bytes do not reach transparent; `None` for a glyph with no pixels, or
|
||||
/// where the platform makes no texture.
|
||||
fn glyph_texture<P: Platform>(
|
||||
platform: &Arc<P>,
|
||||
device: &P::Device,
|
||||
own_texture: OwnTexture<P>,
|
||||
glyph: &Glyph,
|
||||
) -> Option<P::Texture> {
|
||||
let (width, height) = (u64::from(glyph.width), u64::from(glyph.height));
|
||||
let row = width.checked_mul(4)?;
|
||||
let length = usize::try_from(row.checked_mul(height)?).ok()?;
|
||||
if length == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut bytes = glyph.rgba.get(..length).unwrap_or(&glyph.rgba).to_vec();
|
||||
bytes.resize(length, 0);
|
||||
premultiply(&mut bytes);
|
||||
let descriptor = platform.texture_descriptor(&TextureDesc {
|
||||
width,
|
||||
height,
|
||||
..TextureDesc::default()
|
||||
});
|
||||
let texture = own_texture(device, &descriptor)?;
|
||||
no_catch(texture.replace_region(
|
||||
MtlRegion::new(MtlOrigin::new(0, 0, 0), MtlSize::new(width, height, 1)),
|
||||
0,
|
||||
0,
|
||||
HostRange::of_slice(&bytes),
|
||||
row,
|
||||
row * height,
|
||||
));
|
||||
Some(texture)
|
||||
}
|
||||
|
||||
/// Premultiplies RGBA `pixels` by their alpha, each channel rounded to nearest.
|
||||
fn premultiply(pixels: &mut [u8]) {
|
||||
for [red, green, blue, alpha] in pixels.as_chunks_mut::<4>().0 {
|
||||
let alpha = u16::from(*alpha);
|
||||
for channel in [red, green, blue] {
|
||||
let scaled = (u16::from(*channel) * alpha + 127) / 255;
|
||||
*channel = u8::try_from(scaled).unwrap_or(u8::MAX);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A cursor of a `width` by `height` glyph with its hot spot at `hot_spot`, at `at` in `mode`.
|
||||
fn cursor(
|
||||
(width, height): (u32, u32),
|
||||
hot_spot: (u16, u16),
|
||||
mode: (u16, u16),
|
||||
at: (u16, u16),
|
||||
) -> DrawnCursor {
|
||||
DrawnCursor {
|
||||
glyph: Arc::new(Glyph {
|
||||
width,
|
||||
height,
|
||||
hot_spot,
|
||||
rgba: vec![0xff; usize::try_from(width * height * 4).unwrap()],
|
||||
}),
|
||||
mode,
|
||||
at,
|
||||
}
|
||||
}
|
||||
|
||||
/// A region of the target.
|
||||
fn rect(x: u64, y: u64, width: u64, height: u64) -> PixelRect {
|
||||
PixelRect {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
|
||||
/// The viewport puts the glyph's hot spot at the guest's cursor position, a glyph pixel to a
|
||||
/// guest pixel at the image's scale, in a letterboxed image too, and the scissor is the
|
||||
/// glyph's rectangle where it lies inside the image
|
||||
#[test]
|
||||
fn the_viewport_puts_the_hot_spot_at_the_cursor() {
|
||||
let c = cursor((10, 5), (10, 0), (100, 50), (60, 20));
|
||||
let (v, s) = placement(rect(0, 0, 100, 50), (100, 50), &c).unwrap();
|
||||
assert_eq!(
|
||||
(v.origin_x, v.origin_y, v.width, v.height),
|
||||
(50.0, 20.0, 10.0, 5.0)
|
||||
);
|
||||
assert_eq!((s.x, s.y, s.width, s.height), (50, 20, 10, 5));
|
||||
// Twice the size, 30 pixels from the left and 10 from the top.
|
||||
let (v, s) = placement(rect(30, 10, 200, 100), (260, 120), &c).unwrap();
|
||||
assert_eq!(
|
||||
(v.origin_x, v.origin_y, v.width, v.height),
|
||||
(130.0, 50.0, 20.0, 10.0)
|
||||
);
|
||||
assert_eq!((s.x, s.y, s.width, s.height), (130, 50, 20, 10));
|
||||
// At a scale of 1.5 the rectangle's edges fall inside pixels, which the scissor takes.
|
||||
let (v, s) = placement(rect(0, 0, 150, 75), (150, 75), &c).unwrap();
|
||||
assert_eq!((v.origin_x, v.width), (75.0, 15.0));
|
||||
assert_eq!((v.origin_y, v.height), (30.0, 7.5));
|
||||
assert_eq!((s.x, s.y, s.width, s.height), (75, 30, 15, 8));
|
||||
}
|
||||
|
||||
/// A glyph partly off the image keeps its whole viewport, past the target where it reaches
|
||||
/// there, and the scissor clips it to the image; one wholly off it, an empty glyph and an
|
||||
/// empty mode draw nothing
|
||||
#[test]
|
||||
fn the_scissor_clips_the_glyph_to_the_image() {
|
||||
let region = rect(20, 10, 100, 100);
|
||||
let size = (140, 120);
|
||||
let g = (16, 16);
|
||||
let (v, s) = placement(region, size, &cursor(g, (4, 4), (100, 100), (0, 0))).unwrap();
|
||||
assert_eq!((v.origin_x, v.origin_y, v.width), (16.0, 6.0, 16.0));
|
||||
assert_eq!((s.x, s.y, s.width, s.height), (20, 10, 12, 12));
|
||||
let (v, s) = placement(region, size, &cursor(g, (0, 0), (100, 100), (95, 95))).unwrap();
|
||||
assert_eq!((v.origin_x, v.origin_y), (115.0, 105.0));
|
||||
assert_eq!((s.x, s.y, s.width, s.height), (115, 105, 5, 5));
|
||||
let at_edge = cursor(g, (8, 8), (100, 100), (0, 0));
|
||||
let (v, s) = placement(rect(0, 0, 100, 100), (100, 100), &at_edge).unwrap();
|
||||
assert_eq!((v.origin_x, v.origin_y), (-8.0, -8.0));
|
||||
assert_eq!((s.x, s.y, s.width, s.height), (0, 0, 8, 8));
|
||||
let none = |c: &DrawnCursor| placement(region, size, c).is_none();
|
||||
assert!(none(&cursor(g, (0, 0), (100, 100), (100, 50))));
|
||||
assert!(none(&cursor(g, (0, 0), (100, 100), (50, 100))));
|
||||
assert!(none(&cursor(g, (0, 0), (100, 100), (u16::MAX, u16::MAX))));
|
||||
assert!(none(&cursor(g, (20, 20), (100, 100), (0, 0))));
|
||||
assert!(none(&cursor((0, 16), (0, 0), (100, 100), (50, 50))));
|
||||
assert!(none(&cursor(g, (0, 0), (0, 100), (50, 50))));
|
||||
assert!(
|
||||
placement(
|
||||
rect(20, 10, 0, 100),
|
||||
size,
|
||||
&cursor(g, (0, 0), (100, 100), (5, 5))
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
/// A glyph whose viewport would reach past Vulkan's least viewport bounds, or be larger than
|
||||
/// its least viewport size, is not drawn, though it shows in the image
|
||||
#[test]
|
||||
fn a_viewport_past_vulkan_s_least_bounds_draws_nothing() {
|
||||
let wide = rect(0, 0, 8192, 100);
|
||||
let size = (8192, 100);
|
||||
let g = (16, 16);
|
||||
assert!(placement(wide, size, &cursor(g, (0, 0), (8192, 100), (8170, 10))).is_some());
|
||||
assert!(placement(wide, size, &cursor(g, (0, 0), (8192, 100), (8180, 10))).is_none());
|
||||
// A glyph of 256 pixels at 17 pixels to a guest pixel is 4352 wide.
|
||||
let scaled = rect(0, 0, 1700, 1700);
|
||||
let big = cursor((256, 1), (0, 0), (100, 100), (0, 0));
|
||||
assert!(placement(scaled, (1700, 1700), &big).is_none());
|
||||
let fits = cursor((240, 1), (0, 0), (100, 100), (0, 0));
|
||||
assert!(placement(scaled, (1700, 1700), &fits).is_some());
|
||||
}
|
||||
|
||||
/// Premultiplying scales each colour channel by the alpha, to nearest, and keeps the alpha
|
||||
#[test]
|
||||
fn premultiplying_scales_the_colour_by_the_alpha() {
|
||||
let mut pixels = [
|
||||
0xff, 0x80, 0x00, 0xff, 0xff, 0x80, 0x10, 0x80, 0xff, 0xff, 0xff, 0x00,
|
||||
];
|
||||
premultiply(&mut pixels);
|
||||
assert_eq!(
|
||||
pixels,
|
||||
[
|
||||
0xff, 0x80, 0x00, 0xff, 0x80, 0x40, 0x08, 0x80, 0x00, 0x00, 0x00, 0x00
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,13 @@ use objc2_metal::{MTLCommandBuffer as _, MTLCommandQueue as _, MTLDevice, MTLDra
|
||||
use objc2_quartz_core::CAMetalDrawable;
|
||||
use reims_vgpu_core::display::Display as CoreDisplay;
|
||||
use reims_vgpu_core::platform::Platform;
|
||||
use reims_vgpu_core::platform::device::GpuDevice as _;
|
||||
use reims_vgpu_core::raise::OnFault;
|
||||
use reims_vgpu_metal::{MetalPlatform, Obj, msg};
|
||||
use reims_vgpu_window::{FrameSink, PixelRect};
|
||||
use reims_vgpu_window::{DrawnCursor, FrameSink, PixelRect};
|
||||
|
||||
use super::{SinkDisplay, WindowFrame};
|
||||
use crate::display::no_catch;
|
||||
use crate::entry;
|
||||
|
||||
/// The sink of a display of the product's platform ([`super::window_sink`]): a [`MetalSink`] over
|
||||
@@ -79,24 +82,35 @@ impl MetalSink {
|
||||
) -> MetalSink {
|
||||
let device = Obj::from_retained(msg::get("device", || queue.device()));
|
||||
MetalSink {
|
||||
display: SinkDisplay::new(display, queue),
|
||||
display: SinkDisplay::new(display, queue, own_texture),
|
||||
device,
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes the display's current frame into `texture` over `region` in a new command buffer
|
||||
/// of the frame queue, presents `present` in it when there is one, and commits
|
||||
/// ([`SinkDisplay::encode`], whose `false` and lifetimes are this one's).
|
||||
/// Encodes the display's current frame into `texture` over `region`, with `cursor` over it,
|
||||
/// in a new command buffer of the frame queue, presents `present` in it when there is one,
|
||||
/// and commits ([`SinkDisplay::encode`], whose `false` and lifetimes are this one's).
|
||||
pub(crate) fn encode_into(
|
||||
&self,
|
||||
texture: &<MetalPlatform as Platform>::Texture,
|
||||
region: PixelRect,
|
||||
cursor: Option<&DrawnCursor>,
|
||||
present: Option<&ProtocolObject<dyn CAMetalDrawable>>,
|
||||
) -> bool {
|
||||
self.display.encode(region, MetalFrame { texture, present })
|
||||
self.display
|
||||
.encode(region, cursor, MetalFrame { texture, present })
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest's cursor glyph's texture on Metal: a plain one, a resource of Metal's as the layer's
|
||||
/// drawables are (`super::cursor`'s module doc).
|
||||
pub(crate) fn own_texture(
|
||||
device: &<MetalPlatform as Platform>::Device,
|
||||
descriptor: &<MetalPlatform as Platform>::TextureDescriptor,
|
||||
) -> Option<<MetalPlatform as Platform>::Texture> {
|
||||
no_catch(device.new_texture(OnFault::Die, descriptor))
|
||||
}
|
||||
|
||||
/// A frame of [`MetalSink`]'s: encoded straight into `texture`, the drawable presented in the
|
||||
/// same command buffer.
|
||||
struct MetalFrame<'a> {
|
||||
@@ -129,7 +143,19 @@ impl FrameSink for MetalSink {
|
||||
}
|
||||
|
||||
/// The drawable's texture, then [`MetalSink::encode_into`] with the drawable to present.
|
||||
fn draw(&self, drawable: &ProtocolObject<dyn CAMetalDrawable>, region: PixelRect) -> bool {
|
||||
entry::run(|_| self.encode_into(&drawable_texture(drawable), region, Some(drawable)))
|
||||
fn draw(
|
||||
&self,
|
||||
drawable: &ProtocolObject<dyn CAMetalDrawable>,
|
||||
region: PixelRect,
|
||||
cursor: Option<&DrawnCursor>,
|
||||
) -> bool {
|
||||
entry::run(|_| {
|
||||
self.encode_into(&drawable_texture(drawable), region, cursor, Some(drawable))
|
||||
})
|
||||
}
|
||||
|
||||
/// The display's ([`SinkDisplay::cursor_position`]).
|
||||
fn guest_cursor_position(&self) -> Option<(u16, u16)> {
|
||||
entry::run(|_| self.display.cursor_position())
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,10 @@ impl GuestEvents for Recorder {
|
||||
fn cursor_show(&self, show: bool) {
|
||||
self.0.lock().push(format!("window show {show}"));
|
||||
}
|
||||
|
||||
fn cursor_moved(&self) {
|
||||
self.0.lock().push("window move".to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
/// The host's five callbacks, recorded.
|
||||
@@ -125,7 +129,7 @@ fn call_all(cb: &DisplayCallbacks) {
|
||||
}
|
||||
|
||||
/// Each guest callback reaches the window, then the host's, with the arguments core passed; the
|
||||
/// cursor's show byte is the window's bool; a cursor move is the host's alone
|
||||
/// cursor's show byte is the window's bool
|
||||
#[test]
|
||||
fn the_tee_tells_the_window_before_the_host() {
|
||||
let log = Log::default();
|
||||
@@ -145,13 +149,14 @@ fn the_tee_tells_the_window_before_the_host() {
|
||||
"host show 0",
|
||||
"window show true",
|
||||
"host show 2",
|
||||
"window move",
|
||||
"host move",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// With no callback of the host's, the tee still has all five, each the window's alone (a cursor
|
||||
/// move does nothing); its closures hold the window, which they let go of when they drop
|
||||
/// With no callback of the host's, the tee still has all five, each the window's alone; its
|
||||
/// closures hold the window, which they let go of when they drop
|
||||
#[test]
|
||||
fn the_tee_has_all_five_callbacks_without_the_host_s() {
|
||||
let log = Log::default();
|
||||
@@ -166,9 +171,10 @@ fn the_tee_has_all_five_callbacks_without_the_host_s() {
|
||||
"window glyph 1x1 at 3,4 [1, 2, 3, 4]",
|
||||
"window show false",
|
||||
"window show true",
|
||||
"window move",
|
||||
]
|
||||
);
|
||||
assert_eq!(Arc::strong_count(&window), 5);
|
||||
assert_eq!(Arc::strong_count(&window), 6);
|
||||
drop(cb);
|
||||
assert_eq!(Arc::strong_count(&window), 1);
|
||||
}
|
||||
@@ -489,7 +495,7 @@ fn a_window_frame_keeps_its_display_until_it_completes() {
|
||||
width: 48,
|
||||
height: 48,
|
||||
};
|
||||
assert!(sink.encode_into(target.texture(), region, None));
|
||||
assert!(sink.encode_into(target.texture(), region, None, None));
|
||||
drop(display);
|
||||
assert!(alive.upgrade().is_some());
|
||||
assert_eq!(
|
||||
@@ -507,7 +513,168 @@ fn a_window_frame_keeps_its_display_until_it_completes() {
|
||||
let again = device.new_display(DisplayConfig::new(0, 0x5eed_7a02));
|
||||
assert!(again.is_ok());
|
||||
assert!(sink.device().is_none());
|
||||
assert!(!sink.encode_into(target.texture(), region, None));
|
||||
assert!(!sink.encode_into(target.texture(), region, None, None));
|
||||
}
|
||||
|
||||
/// Set in the child of [`a_metal_window_frame_has_the_guest_s_cursor_over_it`].
|
||||
#[cfg(target_os = "macos")]
|
||||
const METAL_CURSOR_CHILD: &str = "RVG_WINDOW_METAL_CURSOR_CHILD";
|
||||
|
||||
/// On Metal, a sink draws the guest's cursor over a window frame by its straight alpha, where the
|
||||
/// window draws it: over a display with no frame yet, all the clear's black, in an image
|
||||
/// letterboxed in the target, the glyph's opaque rows are its colour, its half-transparent row
|
||||
/// half of it, its transparent row black whatever its colour bytes, and the rest stays black;
|
||||
/// a glyph past the image's top left edge is clipped there, the bars beside it left black. In a
|
||||
/// child, as the process's platform installs the aborting panic hook
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn a_metal_window_frame_has_the_guest_s_cursor_over_it() {
|
||||
use reims_vgpu_core::platform::Handle as _;
|
||||
use reims_vgpu_core::platform::blit::{BlitCmd, BlitEncoder as _};
|
||||
use reims_vgpu_core::platform::device::GpuDevice as _;
|
||||
use reims_vgpu_core::platform::resource::Buffer as _;
|
||||
use reims_vgpu_metal::MetalPlatform;
|
||||
use reims_vgpu_window::{DrawnCursor, Glyph};
|
||||
|
||||
use crate::PixelFormat;
|
||||
use crate::platform::api_state;
|
||||
|
||||
/// A frame drawn into the test's target, copied into `buffer` in its command buffer.
|
||||
struct Readback<'a> {
|
||||
texture: &'a <MetalPlatform as Platform>::Texture,
|
||||
buffer: &'a <MetalPlatform as Platform>::Buffer,
|
||||
committed: Option<<MetalPlatform as Platform>::CommandBuffer>,
|
||||
}
|
||||
|
||||
impl WindowFrame<MetalPlatform> for &mut Readback<'_> {
|
||||
fn texture(&mut self) -> Option<&<MetalPlatform as Platform>::Texture> {
|
||||
Some(self.texture)
|
||||
}
|
||||
|
||||
fn encoded(&mut self, command_buffer: &<MetalPlatform as Platform>::CommandBuffer) {
|
||||
let blit = no_catch(command_buffer.blit_encoder(OnFault::Die)).unwrap();
|
||||
no_catch(blit.encode(
|
||||
OnFault::Die,
|
||||
BlitCmd::CopyTextureToBuffer {
|
||||
source_texture: self.texture,
|
||||
source_slice: 0,
|
||||
source_level: 0,
|
||||
source_origin: MtlOrigin::new(0, 0, 0),
|
||||
source_size: MtlSize::new(WIDTH, HEIGHT, 1),
|
||||
destination_buffer: self.buffer,
|
||||
destination_offset: 0,
|
||||
destination_bytes_per_row: WIDTH * 4,
|
||||
destination_bytes_per_image: WIDTH * HEIGHT * 4,
|
||||
},
|
||||
));
|
||||
no_catch(blit.encode(OnFault::Die, BlitCmd::EndEncoding));
|
||||
self.committed = Some(command_buffer.clone_ref());
|
||||
}
|
||||
}
|
||||
|
||||
const WIDTH: u64 = 24;
|
||||
const HEIGHT: u64 = 20;
|
||||
if std::env::var_os(METAL_CURSOR_CHILD).is_none() {
|
||||
let out = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"window::tests::a_metal_window_frame_has_the_guest_s_cursor_over_it",
|
||||
"--nocapture",
|
||||
"--test-threads=1",
|
||||
])
|
||||
.env(METAL_CURSOR_CHILD, "1")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
assert!(
|
||||
String::from_utf8_lossy(&out.stdout).contains(" 1 passed"),
|
||||
"{out:?}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
let device = Device::new(DeviceConfig::default()).unwrap();
|
||||
let target = device
|
||||
.new_frame_target(24, 20, PixelFormat::Bgra8Unorm)
|
||||
.unwrap();
|
||||
let display = device
|
||||
.new_display(DisplayConfig::new(0, 0x5eed_7a20))
|
||||
.unwrap();
|
||||
// Four rows of four: opaque red, opaque green, blue at alpha 0x80, white at alpha 0.
|
||||
let rows: [[u8; 4]; 4] = [
|
||||
[0xff, 0, 0, 0xff],
|
||||
[0, 0xff, 0, 0xff],
|
||||
[0, 0, 0xff, 0x80],
|
||||
[0xff, 0xff, 0xff, 0],
|
||||
];
|
||||
let glyph = Arc::new(Glyph {
|
||||
width: 4,
|
||||
height: 4,
|
||||
hot_spot: (1, 2),
|
||||
rgba: rows.iter().flat_map(|row| row.repeat(4)).collect(),
|
||||
});
|
||||
// A 16 by 16 image 4 pixels from the left and 2 from the top.
|
||||
let region = PixelRect {
|
||||
x: 4,
|
||||
y: 2,
|
||||
width: 16,
|
||||
height: 16,
|
||||
};
|
||||
let sink = SinkDisplay::new(
|
||||
display.core().downgrade(),
|
||||
entry::run(|_| {
|
||||
api_state(device.platform())
|
||||
.frame_queue(device.core().mtl_device_ref())
|
||||
.unwrap()
|
||||
}),
|
||||
crate::window::metal::own_texture,
|
||||
);
|
||||
let draw = |at: (u16, u16)| {
|
||||
let cursor = DrawnCursor {
|
||||
glyph: Arc::clone(&glyph),
|
||||
mode: (16, 16),
|
||||
at,
|
||||
};
|
||||
entry::run(|_| {
|
||||
let metal = device.core().mtl_device_ref();
|
||||
let length = WIDTH * HEIGHT * 4;
|
||||
let buffer = no_catch(metal.new_buffer_of_length(OnFault::Die, length, 0)).unwrap();
|
||||
let mut frame = Readback {
|
||||
texture: target.texture(),
|
||||
buffer: &buffer,
|
||||
committed: None,
|
||||
};
|
||||
assert!(sink.encode(region, Some(&cursor), &mut frame));
|
||||
no_catch(frame.committed.unwrap().wait_until_completed(OnFault::Die));
|
||||
// SAFETY: the buffer is shared, `length` bytes long, and the copy into it has
|
||||
// completed.
|
||||
unsafe {
|
||||
std::slice::from_raw_parts(
|
||||
buffer.contents().as_ptr::<u8>(),
|
||||
usize::try_from(length).unwrap(),
|
||||
)
|
||||
}
|
||||
.to_vec()
|
||||
})
|
||||
};
|
||||
// The glyph's top left is the region's, plus the cursor's position, less the hot spot.
|
||||
for (at, left, top) in [((5, 9), 8, 9), ((0, 0), 3, 0)] {
|
||||
let bytes = draw(at);
|
||||
for (i, got) in bytes.chunks(4).enumerate() {
|
||||
let (x, y) = (i % 24, i / 24);
|
||||
let inside = (4..20).contains(&x) && (2..18).contains(&y);
|
||||
let want = match (x.checked_sub(left), y.checked_sub(top)) {
|
||||
(Some(gx), Some(gy)) if inside && gx < 4 && gy < 4 => {
|
||||
let [r, g, b, a] = rows[gy];
|
||||
let over =
|
||||
|v: u8| u8::try_from((u16::from(v) * u16::from(a) + 127) / 255).unwrap();
|
||||
[over(b), over(g), over(r), 0xff]
|
||||
}
|
||||
_ => [0, 0, 0, 0xff],
|
||||
};
|
||||
let near = got.iter().zip(want).all(|(&g, w)| g.abs_diff(w) <= 1);
|
||||
assert!(near, "at {at:?}, ({x}, {y}): {got:?} for {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On the Vulkan platform, the window opens on the host screen CoreGraphics gives for the port,
|
||||
|
||||
@@ -11,4 +11,9 @@ impl FrameSink for SwapchainSink {
|
||||
fn presenter(&self, target: &dyn VulkanTarget) -> Option<Box<dyn Presenter>> {
|
||||
self.make_presenter(target)
|
||||
}
|
||||
|
||||
/// The display's ([`SwapchainSink::cursor_position`]).
|
||||
fn guest_cursor_position(&self) -> Option<(u16, u16)> {
|
||||
self.cursor_position()
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ use objc2::rc::Retained;
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2_metal::MTLDevice;
|
||||
use objc2_quartz_core::CAMetalDrawable;
|
||||
use reims_vgpu_window::{FrameSink, PixelRect, Presenter, VulkanTarget};
|
||||
use reims_vgpu_window::{DrawnCursor, FrameSink, PixelRect, Presenter, VulkanTarget};
|
||||
|
||||
use super::swapchain::SwapchainSink;
|
||||
|
||||
@@ -24,7 +24,12 @@ impl FrameSink for SwapchainSink {
|
||||
}
|
||||
|
||||
/// Nothing: the sink presents itself, and is given no drawable.
|
||||
fn draw(&self, _drawable: &ProtocolObject<dyn CAMetalDrawable>, _region: PixelRect) -> bool {
|
||||
fn draw(
|
||||
&self,
|
||||
_drawable: &ProtocolObject<dyn CAMetalDrawable>,
|
||||
_region: PixelRect,
|
||||
_cursor: Option<&DrawnCursor>,
|
||||
) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
@@ -43,4 +48,9 @@ impl FrameSink for SwapchainSink {
|
||||
fn presenter(&self, target: &dyn VulkanTarget) -> Option<Box<dyn Presenter>> {
|
||||
self.make_presenter(target)
|
||||
}
|
||||
|
||||
/// The display's ([`SwapchainSink::cursor_position`]).
|
||||
fn guest_cursor_position(&self) -> Option<(u16, u16)> {
|
||||
self.cursor_position()
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ use reims_vgpu_vulkan::VulkanPlatform;
|
||||
use reims_vgpu_vulkan::swapchain::Swapchain;
|
||||
use reims_vgpu_window::{PixelRect, VulkanTarget};
|
||||
|
||||
use super::super::swapchain::own_texture;
|
||||
use super::super::swapchain::tests::{draw_and_read_back, read_back};
|
||||
use crate::PixelFormat;
|
||||
use crate::display::no_catch;
|
||||
@@ -210,12 +211,12 @@ fn composed(
|
||||
)
|
||||
.unwrap()
|
||||
});
|
||||
let sink = SinkDisplay::new(display.core().downgrade(), queue.clone_ref());
|
||||
let sink = SinkDisplay::new(display.core().downgrade(), queue.clone_ref(), own_texture);
|
||||
let mut plain = Plain {
|
||||
texture: &texture,
|
||||
committed: None,
|
||||
};
|
||||
assert!(sink.encode(region, &mut plain), "the frame is drawn");
|
||||
assert!(sink.encode(region, None, &mut plain), "the frame is drawn");
|
||||
assert!(plain.committed.is_some());
|
||||
read_back(queue, &texture, size)
|
||||
}
|
||||
@@ -281,3 +282,209 @@ fn the_swapchain_holds_the_composed_frame() {
|
||||
"the first pixel that differs: (x, y, ours, theirs)"
|
||||
);
|
||||
}
|
||||
|
||||
/// What a window frame of `size` pixels shows over `region`, read back: the display's fixed
|
||||
/// frame of `frame_size` alone, then with `cursor` drawn over it, as a sink draws it
|
||||
/// ([`SinkDisplay::encode`]).
|
||||
fn a_frame_with_the_cursor(
|
||||
serial: u32,
|
||||
frame_size: (u64, u64),
|
||||
size: (u64, u64),
|
||||
region: PixelRect,
|
||||
cursor: &reims_vgpu_window::DrawnCursor,
|
||||
) -> (Vec<u8>, Vec<u8>) {
|
||||
let (device, display) = presenting_display(serial);
|
||||
present_a_fixed_frame(&device, &display, frame_size);
|
||||
let queue = frame_queue(&device);
|
||||
let frame = composed(&device, &display, &queue, size, region);
|
||||
let texture = entry::run(|_| {
|
||||
let format = u64::from(PixelFormat::Bgra8Unorm.metal());
|
||||
let td = no_catch(device.platform().texture_2d_descriptor(
|
||||
OnFault::Die,
|
||||
format,
|
||||
size.0,
|
||||
size.1,
|
||||
false,
|
||||
));
|
||||
td.set_usage(MINIMUM_TEXTURE_USAGE);
|
||||
td.set_resource_options(PRIVATE);
|
||||
no_catch(
|
||||
device
|
||||
.core()
|
||||
.mtl_device_ref()
|
||||
.new_texture(OnFault::Die, &td),
|
||||
)
|
||||
.unwrap()
|
||||
});
|
||||
let sink = SinkDisplay::new(display.core().downgrade(), queue.clone_ref(), own_texture);
|
||||
let mut plain = Plain {
|
||||
texture: &texture,
|
||||
committed: None,
|
||||
};
|
||||
assert!(
|
||||
sink.encode(region, Some(cursor), &mut plain),
|
||||
"the frame is drawn"
|
||||
);
|
||||
(frame, read_back(&queue, &texture, size))
|
||||
}
|
||||
|
||||
/// Pixel `(x, y)` of `bytes`, rows of `width` BGRA pixels.
|
||||
fn pixel(bytes: &[u8], width: u64, (x, y): (u64, u64)) -> [u8; 4] {
|
||||
let i = usize::try_from((y * width + x) * 4).unwrap();
|
||||
bytes[i..i + 4].try_into().unwrap()
|
||||
}
|
||||
|
||||
/// Four rows of four: opaque red, opaque green, blue at alpha 0x80, white at alpha 0.
|
||||
const ROWS: [[u8; 4]; 4] = [
|
||||
[0xff, 0, 0, 0xff],
|
||||
[0, 0xff, 0, 0xff],
|
||||
[0, 0, 0xff, 0x80],
|
||||
[0xff, 0xff, 0xff, 0],
|
||||
];
|
||||
|
||||
/// The cursor of [`ROWS`]'s glyph, its hot spot at `hot_spot`, at `at` in a mode of 64 by 40.
|
||||
fn rows_cursor(hot_spot: (u16, u16), at: (u16, u16)) -> reims_vgpu_window::DrawnCursor {
|
||||
reims_vgpu_window::DrawnCursor {
|
||||
glyph: Arc::new(reims_vgpu_window::Glyph {
|
||||
width: 4,
|
||||
height: 4,
|
||||
hot_spot,
|
||||
rgba: ROWS.iter().flat_map(|row| row.repeat(4)).collect(),
|
||||
}),
|
||||
mode: (64, 40),
|
||||
at,
|
||||
}
|
||||
}
|
||||
|
||||
/// `drawn` is `frame`, of `size` pixels, with [`ROWS`]'s glyph over it a pixel to a pixel, its
|
||||
/// top left at `(left, top)`, wherever it lies inside `region`, each pixel over the frame by the
|
||||
/// glyph's alpha (opaque rows the glyph's colour, a half-transparent row half over the frame, a
|
||||
/// transparent row the frame's, whatever its colour bytes); everywhere else it is `frame`.
|
||||
fn assert_rows_over(
|
||||
frame: &[u8],
|
||||
drawn: &[u8],
|
||||
size: (u64, u64),
|
||||
region: PixelRect,
|
||||
(left, top): (i64, i64),
|
||||
) {
|
||||
for y in 0..size.1 {
|
||||
for x in 0..size.0 {
|
||||
let (under, got) = (pixel(frame, size.0, (x, y)), pixel(drawn, size.0, (x, y)));
|
||||
let in_region = (region.x..region.x + region.width).contains(&x)
|
||||
&& (region.y..region.y + region.height).contains(&y);
|
||||
let (gx, gy) = (
|
||||
i64::try_from(x).unwrap() - left,
|
||||
i64::try_from(y).unwrap() - top,
|
||||
);
|
||||
if !(in_region && (0..4).contains(&gx) && (0..4).contains(&gy)) {
|
||||
assert_eq!(got, under, "outside the glyph, ({x}, {y})");
|
||||
continue;
|
||||
}
|
||||
let [r, g, b, a] = ROWS[usize::try_from(gy).unwrap()];
|
||||
// The target is BGRA; each channel the glyph's over the frame's by the glyph's alpha.
|
||||
let over = |glyph: u8, frame: u8| {
|
||||
(f64::from(glyph) * f64::from(a) + f64::from(frame) * f64::from(255 - a)) / 255.0
|
||||
};
|
||||
for (channel, (want, have)) in [over(b, under[0]), over(g, under[1]), over(r, under[2])]
|
||||
.into_iter()
|
||||
.zip(got)
|
||||
.enumerate()
|
||||
{
|
||||
assert!(
|
||||
(want - f64::from(have)).abs() <= 1.0,
|
||||
"({x}, {y}) channel {channel}: {have} for {want:.1}, over {under:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest's cursor, drawn over a frame where the window draws it: its hot spot at the guest's
|
||||
/// position, a glyph pixel to a guest pixel at a 1:1 image, each pixel over the frame by its
|
||||
/// alpha, and the rest of the frame untouched ([`assert_rows_over`])
|
||||
#[test]
|
||||
fn the_guest_s_cursor_is_drawn_over_the_frame_by_its_alpha() {
|
||||
let size = (64, 40);
|
||||
let region = PixelRect {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: size.0,
|
||||
height: size.1,
|
||||
};
|
||||
let cursor = rows_cursor((1, 1), (10, 20));
|
||||
let (frame, drawn) = a_frame_with_the_cursor(0x5eed_7b71, size, size, region, &cursor);
|
||||
// The glyph's top left is the hot spot's place less the hot spot: (9, 19).
|
||||
assert_rows_over(&frame, &drawn, size, region, (9, 19));
|
||||
}
|
||||
|
||||
/// In an image letterboxed in the window, the glyph is placed from the image's top left, and a
|
||||
/// glyph past the image's top left edge is clipped there: the bars beside it keep the frame's
|
||||
/// clear, though the glyph's viewport reaches over them
|
||||
#[test]
|
||||
fn the_guest_s_cursor_is_clipped_to_a_letterboxed_image() {
|
||||
let size = (80, 50);
|
||||
let region = PixelRect {
|
||||
x: 6,
|
||||
y: 4,
|
||||
width: 64,
|
||||
height: 40,
|
||||
};
|
||||
let cursor = rows_cursor((1, 1), (0, 0));
|
||||
let (frame, drawn) = a_frame_with_the_cursor(0x5eed_7b73, (64, 40), size, region, &cursor);
|
||||
// The glyph's top left is (6 - 1, 4 - 1); its first row and column fall on the bars.
|
||||
assert_rows_over(&frame, &drawn, size, region, (5, 3));
|
||||
assert_ne!(
|
||||
pixel(&drawn, size.0, (6, 4)),
|
||||
pixel(&frame, size.0, (6, 4)),
|
||||
"the glyph's second row and column, inside the image"
|
||||
);
|
||||
}
|
||||
|
||||
/// Where the image scales the glyph, its filtered edge is the glyph's coverage of the frame: at
|
||||
/// 2 pixels a guest pixel, an opaque white texel beside a transparent black one gives the pixels
|
||||
/// between them a quarter and three quarters of white over the frame, not the darker values
|
||||
/// filtering straight alpha would give (9/16 and 1/16 of white)
|
||||
#[test]
|
||||
fn a_scaled_glyph_s_edges_are_its_coverage_of_white() {
|
||||
use reims_vgpu_window::{DrawnCursor, Glyph};
|
||||
|
||||
let size = (128, 80);
|
||||
let region = PixelRect {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: size.0,
|
||||
height: size.1,
|
||||
};
|
||||
let cursor = DrawnCursor {
|
||||
glyph: Arc::new(Glyph {
|
||||
width: 2,
|
||||
height: 1,
|
||||
hot_spot: (0, 0),
|
||||
rgba: vec![0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0],
|
||||
}),
|
||||
mode: (64, 40),
|
||||
at: (10, 20),
|
||||
};
|
||||
let (frame, drawn) = a_frame_with_the_cursor(0x5eed_7b72, (64, 40), size, region, &cursor);
|
||||
// The glyph covers pixels 20..24 of rows 40 and 41; the samples of the pixels between its
|
||||
// texels' centres weigh the white texel 3/4 (x 21) and 1/4 (x 22).
|
||||
for y in [40, 41] {
|
||||
for (x, white) in [(20, 1.0), (21, 0.75), (22, 0.25), (23, 0.0)] {
|
||||
let (under, got) = (pixel(&frame, size.0, (x, y)), pixel(&drawn, size.0, (x, y)));
|
||||
for (channel, (&have, &frame)) in got.iter().zip(&under).take(3).enumerate() {
|
||||
let want = 255.0 * white + f64::from(frame) * (1.0 - white);
|
||||
assert!(
|
||||
(want - f64::from(have)).abs() <= 2.0,
|
||||
"({x}, {y}) channel {channel}: {have} for {want:.1}, over {under:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (x, y) in [(19, 40), (24, 40), (20, 39), (20, 42)] {
|
||||
assert_eq!(
|
||||
pixel(&drawn, size.0, (x, y)),
|
||||
pixel(&frame, size.0, (x, y)),
|
||||
"outside the glyph, ({x}, {y})"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ use reims_vgpu_core::display::Display as CoreDisplay;
|
||||
use reims_vgpu_core::platform::{Handle as _, Platform};
|
||||
use reims_vgpu_vulkan::VulkanPlatform;
|
||||
use reims_vgpu_vulkan::swapchain::{self, Acquired, Frame, Swapchain};
|
||||
use reims_vgpu_window::{Drawn, FrameSink, PixelRect, Presenter, VulkanTarget};
|
||||
use reims_vgpu_window::{Drawn, DrawnCursor, FrameSink, PixelRect, Presenter, VulkanTarget};
|
||||
|
||||
use crate::entry;
|
||||
use crate::stats::DisplayStats;
|
||||
@@ -56,13 +56,23 @@ pub(crate) fn sink(
|
||||
drop(platform);
|
||||
let port = display.upgrade().map(|d| d.port());
|
||||
let sink: Arc<dyn FrameSink> = Arc::new(SwapchainSink {
|
||||
display: Arc::new(SinkDisplay::new(display, queue.clone_ref())),
|
||||
display: Arc::new(SinkDisplay::new(display, queue.clone_ref(), own_texture)),
|
||||
queue,
|
||||
port,
|
||||
});
|
||||
Some(sink)
|
||||
}
|
||||
|
||||
/// The guest's cursor glyph's texture on the Vulkan platform: one of the platform's own, which
|
||||
/// takes no resource ID and no range of Metal's space (`VulkanDevice::new_own_texture`), so no
|
||||
/// address or ID the guest reads moves for it.
|
||||
pub(in crate::window::vulkan) fn own_texture(
|
||||
device: &<VulkanPlatform as Platform>::Device,
|
||||
descriptor: &<VulkanPlatform as Platform>::TextureDescriptor,
|
||||
) -> Option<Texture> {
|
||||
device.new_own_texture(descriptor)
|
||||
}
|
||||
|
||||
/// What draws a display's current frame into its window on the Vulkan platform (module doc).
|
||||
pub(crate) struct SwapchainSink {
|
||||
/// The display, held only for a draw, and the frame queue; shared with the presenters.
|
||||
@@ -74,6 +84,11 @@ pub(crate) struct SwapchainSink {
|
||||
}
|
||||
|
||||
impl SwapchainSink {
|
||||
/// The guest's cursor position, as the display reads it now ([`SinkDisplay::cursor_position`]).
|
||||
pub(crate) fn cursor_position(&self) -> Option<(u16, u16)> {
|
||||
entry::run(|_| self.display.cursor_position())
|
||||
}
|
||||
|
||||
/// The window's surface on the runtime's instance, and a swapchain over it; none where either
|
||||
/// is refused, which is logged, as are the present mode a swapchain takes, MAILBOX where the
|
||||
/// surface offers it, else FIFO, and whether its presents signal fences
|
||||
@@ -123,8 +138,14 @@ struct SwapchainPresenter {
|
||||
}
|
||||
|
||||
impl Presenter for SwapchainPresenter {
|
||||
/// The next image, the display's frame encoded into it, and its present (module doc).
|
||||
fn draw(&mut self, drawable: (u64, u64), region: PixelRect) -> Drawn {
|
||||
/// The next image, the display's frame encoded into it with `cursor` over it, and its
|
||||
/// present (module doc).
|
||||
fn draw(
|
||||
&mut self,
|
||||
drawable: (u64, u64),
|
||||
region: PixelRect,
|
||||
cursor: Option<&DrawnCursor>,
|
||||
) -> Drawn {
|
||||
entry::run(|_| {
|
||||
let frame = match self.swapchain.acquire(drawable) {
|
||||
Acquired::Image(frame) => frame,
|
||||
@@ -141,7 +162,7 @@ impl Presenter for SwapchainPresenter {
|
||||
stats: self.display.stats(),
|
||||
ready: None,
|
||||
};
|
||||
if !self.display.encode(region, &mut image) {
|
||||
if !self.display.encode(region, cursor, &mut image) {
|
||||
return Drawn::Nothing;
|
||||
}
|
||||
let Some(command_buffer) = image.ready else {
|
||||
@@ -276,14 +297,14 @@ pub(super) mod tests {
|
||||
let Acquired::Image(frame) = swapchain.acquire(size) else {
|
||||
panic!("no image of the swapchain");
|
||||
};
|
||||
let sink = SinkDisplay::new(display, queue.clone_ref());
|
||||
let sink = SinkDisplay::new(display, queue.clone_ref(), super::own_texture);
|
||||
let mut image = ImageFrame {
|
||||
swapchain,
|
||||
frame,
|
||||
stats: None,
|
||||
ready: None,
|
||||
};
|
||||
assert!(sink.encode(region, &mut image), "the frame is drawn");
|
||||
assert!(sink.encode(region, None, &mut image), "the frame is drawn");
|
||||
let command_buffer = image.ready.take().unwrap();
|
||||
let bytes = read_back(queue, swapchain.texture(frame).unwrap(), size);
|
||||
swapchain.present(frame, command_buffer);
|
||||
|
||||
@@ -1024,7 +1024,14 @@ section 3 has its types and signatures.
|
||||
`window::vulkan`'s `SwapchainSink` makes a presenter over a swapchain of the window's surface
|
||||
(on macOS one of its `CAMetalLayer`), which encodes the frame into the swapchain's next image,
|
||||
commits, and presents the image on the swapchain's presenting queue once the runtime has
|
||||
scheduled the command buffer, on either OS. Neither waits for the GPU. `Display`
|
||||
scheduled the command buffer, on either OS. Neither waits for the GPU. Where the guest's
|
||||
cursor position, which the window reads through the sink at each cursor doorbell, changes with
|
||||
no pointer event of the window's in the second before (a mouse passed through to the guest),
|
||||
the window hands each draw the guest's cursor at that position, and the sink draws its glyph
|
||||
over the frame in the same command buffer (`window::cursor`: the display's quad buffers and an
|
||||
overlay pipeline of its shaders blending by alpha, both the display's, and a glyph texture
|
||||
that on the Vulkan platform takes no resource ID or range of Metal's space, made before the
|
||||
frame's encode), while the host's cursor is invisible over the image. `Display`
|
||||
holds a `WindowLink` every `clone_ref` shares; its explicit `Drop` lets go of that share
|
||||
before the reference itself, so the last reference closes the window before it releases the
|
||||
display (15.3). A refused create closes the window before it returns.
|
||||
|
||||
Reference in new issue
Block a user