Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e68e3ce939 | ||
|
|
9324949b55 | ||
|
|
48dd6d2fad | ||
|
|
2df30ffea9 | ||
|
|
6b7e7d7cad | ||
|
|
1a6d1626ca | ||
|
|
1ac525f616 | ||
|
|
0427583422 | ||
|
|
0824c15d61 | ||
|
|
7e7b50364b | ||
|
|
9835066ce3 | ||
|
|
8ae206e06a | ||
|
|
bfea2dc988 | ||
|
|
3fdde46abd |
No files matched your search
@@ -2,7 +2,7 @@ name: Queue Runtime Alpha
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [codex/intel-vm-suspend]
|
||||
branches: [intel-vm-suspend]
|
||||
|
||||
permissions:
|
||||
actions: write
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
[submodule "vendor/qemu"]
|
||||
path = vendor/qemu
|
||||
url = https://github.com/yxc0915/qemu-reims-vgpu.git
|
||||
branch = codex/intel-vm-suspend
|
||||
url = https://github.com/reims-go/qemu-reims-vgpu.git
|
||||
branch = intel-vm-suspend
|
||||
Generated
+3
@@ -213,6 +213,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
[[package]]
|
||||
name = "metal2vulkan"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/reims-go/metal2vulkan?rev=19090d5f2e60185359200046e0b72e96ce60099a#19090d5f2e60185359200046e0b72e96ce60099a"
|
||||
dependencies = [
|
||||
"ash",
|
||||
"metal2vulkan-air",
|
||||
@@ -223,6 +224,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "metal2vulkan-air"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/reims-go/metal2vulkan?rev=19090d5f2e60185359200046e0b72e96ce60099a#19090d5f2e60185359200046e0b72e96ce60099a"
|
||||
dependencies = [
|
||||
"sha2 0.11.1",
|
||||
]
|
||||
@@ -230,6 +232,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "metal2vulkan-runtime"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/reims-go/metal2vulkan?rev=19090d5f2e60185359200046e0b72e96ce60099a#19090d5f2e60185359200046e0b72e96ce60099a"
|
||||
dependencies = [
|
||||
"ash",
|
||||
"libc",
|
||||
|
||||
+2
-2
@@ -33,11 +33,11 @@ reims-vgpu-graphics = { path = "crates/reims-vgpu-graphics" }
|
||||
reims-vgpu-video = { path = "crates/reims-vgpu-video" }
|
||||
# metal2vulkan's Metal types, for the Metal enums and descriptor values the runtime's calls take,
|
||||
# from metal2vulkan's public repository at the commit both name.
|
||||
metal2vulkan = { git = "https://github.com/steelbrain/metal2vulkan", rev = "0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" }
|
||||
metal2vulkan = { git = "https://github.com/reims-go/metal2vulkan", rev = "19090d5f2e60185359200046e0b72e96ce60099a" }
|
||||
# The Vulkan platform's runtime (architecture D1), metal2vulkan-runtime: a Metal-shaped API on
|
||||
# Vulkan, one path for every device, under reims-vgpu-vulkan's `rt_platform` and `seam` and
|
||||
# reims-vgpu's `pool::rt_blocks`.
|
||||
metal2vulkan-runtime = { git = "https://github.com/steelbrain/metal2vulkan", rev = "0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" }
|
||||
metal2vulkan-runtime = { git = "https://github.com/reims-go/metal2vulkan", rev = "19090d5f2e60185359200046e0b72e96ce60099a" }
|
||||
# The hashes of the Vulkan platform's metallib sources (reims-vgpu-vulkan/build.rs).
|
||||
sha2 = "0.10.9"
|
||||
# A display window's swapchain on Linux (reims-vgpu-vulkan/src/swapchain.rs), at the runtime's
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! reims-util (<https://github.com/steelbrain/reims-util>) makes what a new x86-64 VM boots from:
|
||||
//! reims-util (<https://github.com/reims-go/reims-util>) makes what a new x86-64 VM boots from:
|
||||
//! an OpenCore image, with OVMF's code and variables beside it, and a macOS installer, downloaded
|
||||
//! from Apple and checked against Apple's chunklists. It also makes an existing VM a new OpenCore
|
||||
//! image presenting the same Mac (opencore.rs). For a VM on reims-vgpu's own device, an image
|
||||
@@ -43,9 +43,9 @@ use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub const REPO: &str = "https://github.com/steelbrain/reims-util";
|
||||
pub const REPO: &str = "https://github.com/reims-go/reims-util";
|
||||
/// The commit [`install`] installs.
|
||||
pub const REV: &str = "7867384c0ab703b4c6aae36cbbb1a35fcffc8321";
|
||||
pub const REV: &str = "573d4a5ffacfc31430ff7372727fce287fef89e1";
|
||||
|
||||
/// The reims-util binary: `REIMS_CTL_UTIL`, else the one beside reims-ctl, where both are
|
||||
/// installed, else the first on PATH.
|
||||
|
||||
@@ -4570,6 +4570,151 @@ mod tests {
|
||||
(platform, device)
|
||||
}
|
||||
|
||||
/// A draw batch records the original Metal calls in order, including each new buffer offset.
|
||||
#[test]
|
||||
fn on_vulkan_draw_batches_record_each_bind_and_draw() {
|
||||
use crate::core::platform::Platform as _;
|
||||
use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _, WorkNames};
|
||||
use crate::core::platform::descriptor::RenderPassDescriptor as _;
|
||||
use crate::core::platform::device::GpuDevice as _;
|
||||
use crate::core::platform::render::{RenderCmd, RenderEncoder as _, VertexDraw};
|
||||
use crate::core::platform::resource::Library as _;
|
||||
use crate::core::platform::values::{
|
||||
ColorAttachmentDesc, ColorAttachmentSet, FullRenderPipelineDesc, TextureDesc,
|
||||
};
|
||||
use crate::core::raise::OnFault;
|
||||
|
||||
in_recording_child(
|
||||
"recorder::tests::on_vulkan_draw_batches_record_each_bind_and_draw",
|
||||
|streams| {
|
||||
let run = || -> Result<(), &'static str> {
|
||||
let (platform, device) = recording_device();
|
||||
let on = OnFault::Return;
|
||||
let function = |bytes: &[u8], name| {
|
||||
let Ok(Ok(Some(library))) = device.new_library(bytes) else {
|
||||
return Err("no library");
|
||||
};
|
||||
library
|
||||
.new_function(on, name)
|
||||
.ok()
|
||||
.flatten()
|
||||
.ok_or("no function")
|
||||
};
|
||||
let vertex = function(
|
||||
include_bytes!("../../../tests/shaders/vert.metallib"),
|
||||
"tri_vert",
|
||||
)?;
|
||||
let fragment = function(
|
||||
include_bytes!("../../../tests/shaders/frag.metallib"),
|
||||
"tri_frag",
|
||||
)?;
|
||||
let mut desc = FullRenderPipelineDesc::new(&vertex, Some(&fragment));
|
||||
desc.colors = vec![(
|
||||
0,
|
||||
ColorAttachmentDesc {
|
||||
pixel_format: 80,
|
||||
..ColorAttachmentDesc::default()
|
||||
},
|
||||
)];
|
||||
let Ok(Some(pipeline)) = device.new_render_pipeline_state_full(&desc) else {
|
||||
return Err("no pipeline");
|
||||
};
|
||||
let Ok(Some(buffer)) = device.new_buffer_of_length(on, 256, 0) else {
|
||||
return Err("no vertex buffer");
|
||||
};
|
||||
let Ok(Some(target)) = device.new_texture(
|
||||
on,
|
||||
&platform.texture_descriptor(&TextureDesc {
|
||||
pixel_format: 80,
|
||||
width: 4,
|
||||
height: 4,
|
||||
usage: 4,
|
||||
..TextureDesc::default()
|
||||
}),
|
||||
) else {
|
||||
return Err("no render target");
|
||||
};
|
||||
let queue = device.new_command_queue().ok_or("no queue")?;
|
||||
let Ok(Some(cb)) = queue.command_buffer(on) else {
|
||||
return Err("no command buffer");
|
||||
};
|
||||
cb.names_work(&std::sync::Arc::new(WorkNames::new(1)));
|
||||
let pass = platform.render_pass_descriptor();
|
||||
assert_eq!(
|
||||
pass.set_color_attachment(
|
||||
on,
|
||||
0,
|
||||
&ColorAttachmentSet {
|
||||
texture: Some(Some(&target)),
|
||||
load_action: Some(2),
|
||||
store_action: Some(1),
|
||||
..ColorAttachmentSet::default()
|
||||
}
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
let Ok(Some(encoder)) = cb.render_encoder(on, &pass) else {
|
||||
return Err("no render encoder");
|
||||
};
|
||||
assert_eq!(
|
||||
encoder.encode(
|
||||
on,
|
||||
RenderCmd::SetRenderPipelineState {
|
||||
pipeline_state: Some(&pipeline),
|
||||
}
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
let draw = VertexDraw {
|
||||
buffer: Some(&buffer),
|
||||
offset: 0,
|
||||
index: 0,
|
||||
primitive_type: 3,
|
||||
vertex_start: 0,
|
||||
vertex_count: 3,
|
||||
};
|
||||
let draws = [draw, VertexDraw { offset: 16, ..draw }];
|
||||
assert_eq!(encoder.encode_draws(on, &draws), Ok(()));
|
||||
assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(()));
|
||||
|
||||
let receiver = id_at(encoder.rec_ptr()).ok_or("no encoder stream id")?;
|
||||
let buffer = id_at(buffer.rec_ptr()).ok_or("no buffer stream id")?;
|
||||
let (calls, _) = recorded(streams, |calls| {
|
||||
calls
|
||||
.iter()
|
||||
.any(|c| c.receiver == receiver && c.selector == "endEncoding")
|
||||
});
|
||||
let selectors_and_args: Vec<_> = calls
|
||||
.iter()
|
||||
.filter(|c| c.receiver == receiver)
|
||||
.map(|c| (c.selector.as_str(), c.args.as_slice()))
|
||||
.collect();
|
||||
assert_eq!(selectors_and_args.len(), 6, "{calls:?}");
|
||||
let bind =
|
||||
|offset| [Value::Object(buffer), Value::Uint(offset), Value::Uint(0)];
|
||||
let primitives = [Value::Uint(3), Value::Uint(0), Value::Uint(3)];
|
||||
assert_eq!(
|
||||
selectors_and_args[1..5],
|
||||
[
|
||||
("setVertexBuffer:offset:atIndex:", bind(0).as_slice()),
|
||||
(
|
||||
"drawPrimitives:vertexStart:vertexCount:",
|
||||
primitives.as_slice()
|
||||
),
|
||||
("setVertexBuffer:offset:atIndex:", bind(16).as_slice()),
|
||||
(
|
||||
"drawPrimitives:vertexStart:vertexCount:",
|
||||
primitives.as_slice()
|
||||
),
|
||||
]
|
||||
);
|
||||
Ok(())
|
||||
};
|
||||
assert_eq!(run(), Ok(()));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// A stream starts with the device's making and then its identity, rt's `deviceName` and
|
||||
/// `hasUnifiedMemory`, before any call on the device.
|
||||
#[test]
|
||||
|
||||
@@ -47,6 +47,7 @@
|
||||
|
||||
use std::ops::Range;
|
||||
|
||||
use metal2vulkan::metal::format;
|
||||
use metal2vulkan_runtime as rt;
|
||||
|
||||
use crate::core::platform::Platform;
|
||||
@@ -56,10 +57,11 @@ use crate::core::raise::{OnFault, RaiseResult};
|
||||
use crate::core::sync::Mutex;
|
||||
|
||||
use super::command::{Kept, OpenMark};
|
||||
use super::copied::Used;
|
||||
use super::diag::Use;
|
||||
use super::fault::{EncoderKind, EncoderNames, Naming, Operands};
|
||||
use super::unbuilt::{RtRefusal, Unbuilt, refuse, refused_as, rt_refused_texture};
|
||||
use super::{RtObj, RtPlatform, RtTexture};
|
||||
use super::{RtBuffer, RtObj, RtPlatform, RtTexture};
|
||||
|
||||
/// `id<MTLBlitCommandEncoder>` on metal2vulkan-runtime.
|
||||
pub struct RtBlitEncoder {
|
||||
@@ -105,10 +107,9 @@ impl RtBlitEncoder {
|
||||
|
||||
/// Notes `cmd`'s textures in its command buffer's `kept`: its copies' as uses
|
||||
/// ([`Kept::used`]), and a mipmap generation's and a synchronize's as tiled textures' uses
|
||||
/// alone (`super::tiled`); and the copies its buffers and textures lie over
|
||||
/// alone (`super::tiled`); and the copies these textures and synchronized buffers lie over
|
||||
/// ([`super::copied::Used`]).
|
||||
fn note_uses(&self, cmd: &BlitCmd<'_, RtPlatform>) {
|
||||
self.note_copies(cmd);
|
||||
let (from, into) = match *cmd {
|
||||
BlitCmd::CopyBufferToTexture {
|
||||
destination_texture,
|
||||
@@ -146,6 +147,12 @@ impl RtBlitEncoder {
|
||||
self.kept.copies().add(texture.copied(), true);
|
||||
(None, None)
|
||||
}
|
||||
BlitCmd::SynchronizeResource {
|
||||
resource: Some(ResourceRef::Buffer(buffer)),
|
||||
} => {
|
||||
self.kept.copies().buffer(buffer);
|
||||
(None, None)
|
||||
}
|
||||
_ => (None, None),
|
||||
};
|
||||
if let Some(texture) = from {
|
||||
@@ -155,47 +162,6 @@ impl RtBlitEncoder {
|
||||
self.kept.used(texture, Use::BlittedInto);
|
||||
}
|
||||
}
|
||||
|
||||
/// Notes the copies `cmd`'s buffers lie over in its command buffer's `kept`
|
||||
/// ([`super::copied::Used`]); its textures' are noted with their uses.
|
||||
fn note_copies(&self, cmd: &BlitCmd<'_, RtPlatform>) {
|
||||
if !super::copied::any() {
|
||||
return;
|
||||
}
|
||||
let used = self.kept.copies();
|
||||
match *cmd {
|
||||
BlitCmd::CopyBufferToTexture {
|
||||
source_buffer: buffer,
|
||||
..
|
||||
} => used.buffer_read(buffer),
|
||||
BlitCmd::CopyTextureToBuffer {
|
||||
destination_buffer: buffer,
|
||||
..
|
||||
}
|
||||
| BlitCmd::FillBufferPattern4 { buffer, .. }
|
||||
| BlitCmd::FillBuffer { buffer, .. }
|
||||
| BlitCmd::SynchronizeResource {
|
||||
resource: Some(ResourceRef::Buffer(buffer)),
|
||||
} => used.buffer(buffer),
|
||||
BlitCmd::CopyBufferToTextureOptions {
|
||||
source_buffer: buffer,
|
||||
..
|
||||
} => buffer.iter().for_each(|b| used.buffer_read(b)),
|
||||
BlitCmd::CopyTextureToBufferOptions {
|
||||
destination_buffer: buffer,
|
||||
..
|
||||
} => buffer.iter().for_each(|b| used.buffer(b)),
|
||||
BlitCmd::CopyBufferToBuffer {
|
||||
source_buffer,
|
||||
destination_buffer,
|
||||
..
|
||||
} => {
|
||||
source_buffer.iter().for_each(|b| used.buffer_read(b));
|
||||
destination_buffer.iter().for_each(|b| used.buffer(b));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Notes in `operands` what `cmd`, a command of an encoder of a command buffer of the host's own,
|
||||
@@ -438,17 +404,24 @@ fn copy_texture(
|
||||
/// ([`super::unbuilt::refusal_detail`]), and is counted with the command ([`report`]).
|
||||
fn copy_bytes(
|
||||
e: &mut rt::BlitCommandEncoder,
|
||||
sel: &'static str,
|
||||
(buffer, lies): (&rt::Buffer, rt::BufferLayout),
|
||||
(sel, used): (&'static str, &Used),
|
||||
(buffer, lies): (&RtBuffer, rt::BufferLayout),
|
||||
size: [u32; 3],
|
||||
(texture, place): (&RtTexture, rt::TexturePlace),
|
||||
into: bool,
|
||||
option: rt::BlitOption,
|
||||
) -> Result<(), Stop> {
|
||||
let copied = if into {
|
||||
e.copy_from_buffer_with_options(buffer, lies, size, texture.rt(), place, option)
|
||||
e.copy_from_buffer_with_options(buffer.rt(), lies, size, texture.rt(), place, option)
|
||||
} else {
|
||||
e.copy_from_texture_to_buffer_with_options(texture.rt(), place, size, buffer, lies, option)
|
||||
e.copy_from_texture_to_buffer_with_options(
|
||||
texture.rt(),
|
||||
place,
|
||||
size,
|
||||
buffer.rt(),
|
||||
lies,
|
||||
option,
|
||||
)
|
||||
};
|
||||
copied.map_err(|error| {
|
||||
let (texture, buffer) = (Copied::of(texture, place), Copied::Buffer(lies));
|
||||
@@ -465,7 +438,70 @@ fn copy_bytes(
|
||||
};
|
||||
super::unbuilt::refusal_detail(sel, &error, Some(&what));
|
||||
Stop::Rt(error)
|
||||
})
|
||||
})?;
|
||||
if buffer.copied().is_some() {
|
||||
match buffer_image_ranges(texture.rt().descriptor(), size, lies, option) {
|
||||
Some(ranges) => used.buffer_ranges(buffer, !into, ranges),
|
||||
None => used.add(buffer.copied(), !into),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The buffer bytes of an accepted image copy, excluding padding between rows and images.
|
||||
fn buffer_image_ranges(
|
||||
desc: &rt::TextureDescriptor,
|
||||
[width, mut height, mut depth]: [u32; 3],
|
||||
layout: rt::BufferLayout,
|
||||
option: rt::BlitOption,
|
||||
) -> Option<impl Iterator<Item = Range<u64>>> {
|
||||
if height == 0
|
||||
&& matches!(
|
||||
desc.texture_type,
|
||||
rt::TextureType::Type1D | rt::TextureType::Type1DArray
|
||||
)
|
||||
{
|
||||
height = 1;
|
||||
}
|
||||
if depth == 0 && desc.texture_type != rt::TextureType::Type3D {
|
||||
depth = 1;
|
||||
}
|
||||
let format = desc.pixel_format;
|
||||
let bytes = match (option, format) {
|
||||
(rt::BlitOption::StencilFromDepthStencil, _) | (NONE, rt::PixelFormat::Stencil8) => 1,
|
||||
(NONE | rt::BlitOption::DepthFromDepthStencil, rt::PixelFormat::Depth16Unorm) => 2,
|
||||
(NONE | rt::BlitOption::DepthFromDepthStencil, rt::PixelFormat::Depth32Float)
|
||||
| (rt::BlitOption::DepthFromDepthStencil, rt::PixelFormat::Depth32FloatStencil8) => 4,
|
||||
(NONE, _) if format::aspects(format) == Some(metal2vulkan::vk::ImageAspectFlags::COLOR) => {
|
||||
format::byte_format(format)?.block()?.size
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
// At a compressed mip's edge, rt clips a whole block to the edge without changing the
|
||||
// number of blocks transferred.
|
||||
let [bw, bh] = format::block_extent(format).unwrap_or([1, 1]);
|
||||
let row = u64::from(width.div_ceil(bw)) * u64::from(bytes);
|
||||
let mut rows = u64::from(height.div_ceil(bh));
|
||||
let mut images = if row == 0 || rows == 0 {
|
||||
0
|
||||
} else {
|
||||
u64::from(depth)
|
||||
};
|
||||
let mut run = row;
|
||||
if images > 0 && (rows == 1 || layout.bytes_per_row == row) {
|
||||
run = row.checked_mul(rows)?;
|
||||
rows = 1;
|
||||
if images == 1 || layout.bytes_per_image == run {
|
||||
run = run.checked_mul(images)?;
|
||||
images = 1;
|
||||
}
|
||||
}
|
||||
Some((0..images).flat_map(move |image| {
|
||||
(0..rows).map(move |row| {
|
||||
let start = layout.offset + image * layout.bytes_per_image + row * layout.bytes_per_row;
|
||||
start..start + run
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
/// What a copy of texels asked of rt, for the process's first line of each kind of rt's refusals
|
||||
@@ -599,7 +635,11 @@ impl std::fmt::Display for CopyDetail {
|
||||
}
|
||||
|
||||
/// Encodes `cmd` into `e`, rt's open encoder (the module's docs); `EndEncoding` is the caller's.
|
||||
fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Result<(), Stop> {
|
||||
fn encode(
|
||||
e: &mut rt::BlitCommandEncoder,
|
||||
cmd: BlitCmd<'_, RtPlatform>,
|
||||
used: &Used,
|
||||
) -> Result<(), Stop> {
|
||||
let sel = cmd.selector();
|
||||
match cmd {
|
||||
BlitCmd::EndEncoding => {}
|
||||
@@ -616,9 +656,17 @@ fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Resul
|
||||
} => {
|
||||
let to = place(destination_slice, destination_level, destination_origin)?;
|
||||
let lies = layout(source_offset, source_bytes_per_row, source_bytes_per_image);
|
||||
let (source, destination) = (source_buffer.rt(), destination_texture);
|
||||
let (source, destination) = (source_buffer, destination_texture);
|
||||
let size = size(source_size)?;
|
||||
copy_bytes(e, sel, (source, lies), size, (destination, to), true, NONE)?;
|
||||
copy_bytes(
|
||||
e,
|
||||
(sel, used),
|
||||
(source, lies),
|
||||
size,
|
||||
(destination, to),
|
||||
true,
|
||||
NONE,
|
||||
)?;
|
||||
}
|
||||
BlitCmd::CopyBufferToTextureOptions {
|
||||
source_buffer,
|
||||
@@ -638,11 +686,10 @@ fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Resul
|
||||
let option = blit_option(options)?;
|
||||
let to = place(destination_slice, destination_level, destination_origin)?;
|
||||
let lies = layout(source_offset, source_bytes_per_row, source_bytes_per_image);
|
||||
let (source, destination) = (source.rt(), destination);
|
||||
let size = size(source_size)?;
|
||||
copy_bytes(
|
||||
e,
|
||||
sel,
|
||||
(sel, used),
|
||||
(source, lies),
|
||||
size,
|
||||
(destination, to),
|
||||
@@ -665,6 +712,18 @@ fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Resul
|
||||
(destination.rt(), destination_offset),
|
||||
);
|
||||
e.copy_from_buffer_to_buffer(from.0, from.1, to.0, to.1, size)?;
|
||||
if size != 0 {
|
||||
used.buffer_ranges(
|
||||
source,
|
||||
false,
|
||||
std::iter::once(source_offset..source_offset + size),
|
||||
);
|
||||
used.buffer_ranges(
|
||||
destination,
|
||||
true,
|
||||
std::iter::once(destination_offset..destination_offset + size),
|
||||
);
|
||||
}
|
||||
}
|
||||
BlitCmd::CopyTextureToBuffer {
|
||||
source_texture,
|
||||
@@ -683,11 +742,11 @@ fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Resul
|
||||
destination_bytes_per_row,
|
||||
destination_bytes_per_image,
|
||||
);
|
||||
let (source, destination) = (source_texture, destination_buffer.rt());
|
||||
let (source, destination) = (source_texture, destination_buffer);
|
||||
let size = size(source_size)?;
|
||||
copy_bytes(
|
||||
e,
|
||||
sel,
|
||||
(sel, used),
|
||||
(destination, lies),
|
||||
size,
|
||||
(source, from),
|
||||
@@ -717,11 +776,10 @@ fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Resul
|
||||
destination_bytes_per_row,
|
||||
destination_bytes_per_image,
|
||||
);
|
||||
let (source, destination) = (source, destination.rt());
|
||||
let size = size(source_size)?;
|
||||
copy_bytes(
|
||||
e,
|
||||
sel,
|
||||
(sel, used),
|
||||
(destination, lies),
|
||||
size,
|
||||
(source, from),
|
||||
@@ -805,13 +863,19 @@ fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Resul
|
||||
if rest.iter().any(|&byte| byte != value) {
|
||||
return Err(Stop::Unbuilt(Unbuilt::Blit));
|
||||
}
|
||||
e.fill_buffer(buffer.rt(), bytes(range)?, value)?;
|
||||
let bytes = bytes(range)?;
|
||||
e.fill_buffer(buffer.rt(), bytes.clone(), value)?;
|
||||
used.buffer_ranges(buffer, true, std::iter::once(bytes));
|
||||
}
|
||||
BlitCmd::FillBuffer {
|
||||
buffer,
|
||||
range,
|
||||
value,
|
||||
} => e.fill_buffer(buffer.rt(), bytes(range)?, value)?,
|
||||
} => {
|
||||
let bytes = bytes(range)?;
|
||||
e.fill_buffer(buffer.rt(), bytes.clone(), value)?;
|
||||
used.buffer_ranges(buffer, true, std::iter::once(bytes));
|
||||
}
|
||||
BlitCmd::FillTexture { .. } => return Err(Stop::Unbuilt(Unbuilt::FillTexture)),
|
||||
BlitCmd::FillTextureColor { .. } => return Err(Stop::Unbuilt(Unbuilt::Blit)),
|
||||
BlitCmd::GenerateMipmaps { texture } => {
|
||||
@@ -874,7 +938,7 @@ impl BlitEncoder<RtPlatform> for RtObj<RtBlitEncoder> {
|
||||
note_operands(operands, &cmd);
|
||||
}
|
||||
let stopped = match open.encoder.as_mut() {
|
||||
Some(e) => encode(e, cmd).err(),
|
||||
Some(e) => encode(e, cmd, self.kept.copies()).err(),
|
||||
None => Some(Stop::Metal("a command after endEncoding")),
|
||||
};
|
||||
if ending && let Some(e) = open.encoder.take() {
|
||||
|
||||
@@ -498,6 +498,8 @@ pub struct RtBuffer {
|
||||
/// The copy of host pages it lies over (`super::copied`), which a command buffer that uses it
|
||||
/// syncs; `None` for any other.
|
||||
copied: Option<Arc<super::copied::Copied>>,
|
||||
/// Whether the buffer was placed over an existing copy by its address or mapping.
|
||||
aliases_copy: bool,
|
||||
/// The guest's object id for it, which its release's entry in the device's history names
|
||||
/// (`super::fault`).
|
||||
named: super::fault::Named,
|
||||
@@ -672,6 +674,11 @@ impl RtBuffer {
|
||||
pub(super) fn copied(&self) -> Option<&Arc<super::copied::Copied>> {
|
||||
self.copied.as_ref()
|
||||
}
|
||||
|
||||
/// A buffer placed by a heap or made over an existing block's mapping.
|
||||
pub(super) fn copied_alias(&self) -> bool {
|
||||
self.in_heap || self.aliases_copy
|
||||
}
|
||||
}
|
||||
|
||||
/// The longest a deferred buffer's memory took to make, in nanoseconds
|
||||
@@ -1202,6 +1209,7 @@ fn deferred_as(
|
||||
#[cfg(unix)]
|
||||
exported: OnceLock::new(),
|
||||
copied: None,
|
||||
aliases_copy: false,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1331,17 +1339,17 @@ fn made(
|
||||
|
||||
/// The buffer's handle, of rt's buffer `rt` answering `options`.
|
||||
fn buffer(device: &RtObj<RtDevice>, rt: rt::Buffer, options: u64) -> RtObj<RtBuffer> {
|
||||
buffer_of(device, rt, options, (false, None), None)
|
||||
buffer_of(device, rt, options, (false, None, false), None)
|
||||
}
|
||||
|
||||
/// The buffer's handle, of rt's buffer `rt` answering `options`, placed by a heap where `in_heap`,
|
||||
/// lying over `copied` where it lies over a copy of host pages (`super::copied`), running
|
||||
/// `deallocator` as it goes where given.
|
||||
/// lying over `copied` where it lies over a copy of host pages (`super::copied`). A buffer
|
||||
/// placed by address or mapping `aliases_copy`. Runs `deallocator` as it goes where given.
|
||||
pub(super) fn buffer_of(
|
||||
device: &RtObj<RtDevice>,
|
||||
rt: rt::Buffer,
|
||||
options: u64,
|
||||
(in_heap, copied): (bool, Option<Arc<super::copied::Copied>>),
|
||||
(in_heap, copied, aliases_copy): (bool, Option<Arc<super::copied::Copied>>, bool),
|
||||
deallocator: Option<Slot>,
|
||||
) -> RtObj<RtBuffer> {
|
||||
RtObj::new(RtBuffer {
|
||||
@@ -1356,6 +1364,7 @@ pub(super) fn buffer_of(
|
||||
#[cfg(unix)]
|
||||
exported: OnceLock::new(),
|
||||
copied,
|
||||
aliases_copy,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1379,6 +1388,7 @@ pub(super) fn with_export(
|
||||
deallocator: None,
|
||||
exported: OnceLock::from(exported),
|
||||
copied: None,
|
||||
aliases_copy: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1428,7 +1438,17 @@ fn in_known(
|
||||
};
|
||||
let (block, offset) = known_at(device, pin, length, class, None)?;
|
||||
match device.rt().new_buffer(block.id, offset, length, zero_from) {
|
||||
Ok(made) => Some(Some(buffer(device, made, o.answered))),
|
||||
Ok(made) => {
|
||||
let copied = super::copied::of(block.id);
|
||||
let aliases_copy = copied.is_some();
|
||||
Some(Some(buffer_of(
|
||||
device,
|
||||
made,
|
||||
o.answered,
|
||||
(false, copied, aliases_copy),
|
||||
None,
|
||||
)))
|
||||
}
|
||||
Err(error) => {
|
||||
rt_refused_create(sel, &error);
|
||||
Some(None)
|
||||
@@ -1639,7 +1659,7 @@ fn no_copy(
|
||||
if in_place {
|
||||
read_only(sel);
|
||||
}
|
||||
let placed = (false, super::copied::of(block.id));
|
||||
let placed = (false, super::copied::of(block.id), deallocator.is_some());
|
||||
Some(buffer_of(device, made, o.answered, placed, deallocator))
|
||||
}
|
||||
|
||||
@@ -5517,6 +5537,85 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texture_blits_sync_only_the_buffer_rows_on_vulkan() -> Result<(), &'static str> {
|
||||
use crate::core::platform::types::{MtlOrigin, MtlSize};
|
||||
|
||||
let platform = RtPlatform::new();
|
||||
let device = platform.system_default_device().ok_or("no Vulkan device")?;
|
||||
let queue = device.new_command_queue().ok_or("no command queue")?;
|
||||
let source = over_a_copy(&device, false);
|
||||
let destination = over_a_copy(&device, false);
|
||||
let page = device.facts().page_size;
|
||||
let pitch = page;
|
||||
let offset = 16;
|
||||
let descriptor = platform.texture_descriptor(&TextureDesc {
|
||||
pixel_format: 70,
|
||||
width: 4,
|
||||
height: 2,
|
||||
..TextureDesc::default()
|
||||
});
|
||||
let texture = device
|
||||
.new_texture(OnFault::Return, &descriptor)
|
||||
.map_err(|_| "texture creation raised")?
|
||||
.ok_or("no texture")?;
|
||||
// SAFETY: the two 16-byte rows and the padding are inside the source's two pages.
|
||||
unsafe {
|
||||
source
|
||||
.pages
|
||||
.wrapping_add(offset)
|
||||
.as_ptr::<u8>()
|
||||
.write_bytes(0x22, 16);
|
||||
source
|
||||
.pages
|
||||
.wrapping_add(offset + pitch)
|
||||
.as_ptr::<u8>()
|
||||
.write_bytes(0x33, 16);
|
||||
destination
|
||||
.pages
|
||||
.wrapping_add(offset + 16)
|
||||
.as_ptr::<u8>()
|
||||
.write(0x44);
|
||||
}
|
||||
let size = MtlSize::new(4, 2, 1);
|
||||
let origin = MtlOrigin::new(0, 0, 0);
|
||||
blit_and_wait(
|
||||
&queue,
|
||||
vec![
|
||||
BlitCmd::CopyBufferToTexture {
|
||||
source_buffer: &source.buffer,
|
||||
source_offset: offset,
|
||||
source_bytes_per_row: pitch,
|
||||
source_bytes_per_image: 0,
|
||||
source_size: size,
|
||||
destination_texture: &texture,
|
||||
destination_slice: 0,
|
||||
destination_level: 0,
|
||||
destination_origin: origin,
|
||||
},
|
||||
BlitCmd::CopyTextureToBuffer {
|
||||
source_texture: &texture,
|
||||
source_slice: 0,
|
||||
source_level: 0,
|
||||
source_origin: origin,
|
||||
source_size: size,
|
||||
destination_buffer: &destination.buffer,
|
||||
destination_offset: offset,
|
||||
destination_bytes_per_row: pitch,
|
||||
destination_bytes_per_image: 0,
|
||||
},
|
||||
],
|
||||
);
|
||||
let mut first = [0x22; 17];
|
||||
first[16] = 0x44;
|
||||
assert_eq!(read(destination.pages.wrapping_add(offset), 17), first);
|
||||
assert_eq!(
|
||||
read(destination.pages.wrapping_add(offset + pitch), 16),
|
||||
[0x33; 16]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// On the GPU the test holds: a copy a compute encoder declares with `useResources:`, as a
|
||||
/// shader that reaches it through an argument buffer's address asks, and binds not, is synced
|
||||
/// for its command buffer: the CPU's bytes copied in at the commit, and, declared for writing
|
||||
|
||||
@@ -58,8 +58,9 @@
|
||||
//! copy.
|
||||
//! - **Copied in at the commits that use it** ([`copy_in`], from `super::command`'s commit,
|
||||
//! before rt is handed the command buffer, so before the work that reads it): every byte of the
|
||||
//! pages that differs from the base is written into the copy and the base. A byte the CPU did
|
||||
//! not change is never written, so a GPU write to the copy by work still in flight stays. Where
|
||||
//! pages in a chunk the work can read or write that differs from the base is written into the
|
||||
//! copy and the base. A byte the CPU did not change is never written, so a GPU write to the copy
|
||||
//! by work still in flight stays. Where
|
||||
//! the device's Shared memory type is host-coherent, the GPU reads the bytes written with no
|
||||
//! flush; where it is not, rt flushes the Shared memory the command buffer keeps before it
|
||||
//! submits it, and flushes then invalidates what it may write before its completed handlers run
|
||||
@@ -68,9 +69,10 @@
|
||||
//! are dropped is written whole instead ("Writes dropped").
|
||||
//! - **Merged back at the completions of the command buffers that can write it** ([`merging`],
|
||||
//! the first of the command buffer's completed handlers, so before core's and before a waiter
|
||||
//! returns): every byte of the copy that differs from the base is written into the pages where
|
||||
//! the pages' byte still is the base's, and the base takes the copy's byte. A byte both sides
|
||||
//! changed keeps the CPU's, which the next commit that uses it copies in, as Metal keeps the
|
||||
//! returns): every byte of the copy in a chunk the work can write that differs from the base
|
||||
//! is written into the pages where the pages' byte still is the base's, and the base takes the
|
||||
//! copy's byte. A byte both sides changed keeps the CPU's, which the next commit that uses it
|
||||
//! copies in, as Metal keeps the
|
||||
//! later of two writes. A byte the guest writes between the merge's read of it and its store is
|
||||
//! lost only where the GPU changed it too. A command buffer whose uses of a copy can only read
|
||||
//! it neither merges it back nor puts back its bytes: its work wrote none of them.
|
||||
@@ -119,6 +121,7 @@
|
||||
//! ([`DECLARATIONS_CODE`]), with the commits that declared one ([`DECLARING_COMMITS_CODE`]).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::ops::Range;
|
||||
use std::ptr::NonNull;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
@@ -502,16 +505,80 @@ impl Drop for Fresh {
|
||||
}
|
||||
}
|
||||
|
||||
/// A copy a command buffer uses, and whether a use of it can write it ([`Used`]).
|
||||
/// A copy a command buffer uses, with byte ranges relative to the start of its block.
|
||||
#[derive(Clone)]
|
||||
pub(super) struct CopyUse {
|
||||
/// The copy.
|
||||
copied: Arc<Copied>,
|
||||
/// Whether a use of it can write it.
|
||||
writes: bool,
|
||||
reads: Ranges,
|
||||
writes: Ranges,
|
||||
}
|
||||
|
||||
/// The copies a command buffer uses, each once, with whether a use of it can write it ("Synced
|
||||
const MAX_RANGES: usize = 16;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
enum Ranges {
|
||||
Known(Vec<Range<usize>>),
|
||||
All,
|
||||
}
|
||||
|
||||
impl Ranges {
|
||||
const EMPTY: Self = Self::Known(Vec::new());
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
matches!(self, Self::Known(ranges) if ranges.is_empty())
|
||||
}
|
||||
|
||||
fn add(&mut self, bytes: Range<usize>) {
|
||||
let Self::Known(ranges) = self else { return };
|
||||
let first = ranges.partition_point(|range| range.end < bytes.start);
|
||||
let count = ranges[first..].partition_point(|range| range.start <= bytes.end);
|
||||
if count == 0 {
|
||||
if ranges.len() == MAX_RANGES {
|
||||
*self = Self::All;
|
||||
} else {
|
||||
ranges.insert(first, bytes);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let last = first + count - 1;
|
||||
ranges[first] = bytes.start.min(ranges[first].start)..bytes.end.max(ranges[last].end);
|
||||
ranges.drain(first + 1..last + 1);
|
||||
}
|
||||
|
||||
/// The union of two sets, rounded out to chunks. Ranges in separate sets can touch the same
|
||||
/// chunk even when their bytes do not.
|
||||
fn chunks<'a>(
|
||||
&'a self,
|
||||
other: &'a Self,
|
||||
len: usize,
|
||||
) -> impl Iterator<Item = Range<usize>> + 'a {
|
||||
let (mut first, mut second, mut whole) = match (self, other) {
|
||||
(Self::Known(first), Self::Known(second)) => (&first[..], &second[..], None),
|
||||
_ => (&[][..], &[][..], Some(0..len / CHUNK)),
|
||||
};
|
||||
let mut end = 0;
|
||||
std::iter::from_fn(move || {
|
||||
if whole.is_some() {
|
||||
return whole.take();
|
||||
}
|
||||
while let Some(next) = match (first.first(), second.first()) {
|
||||
(Some(a), Some(b)) if a.start <= b.start => first.split_off_first(),
|
||||
(_, Some(_)) => second.split_off_first(),
|
||||
_ => first.split_off_first(),
|
||||
} {
|
||||
let start = end.max(next.start / CHUNK);
|
||||
let past = next.end.div_ceil(CHUNK);
|
||||
if start < past {
|
||||
end = past;
|
||||
return Some(start..past);
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The copies a command buffer uses, each once, with the ranges it can read or write ("Synced
|
||||
/// for the command buffers that use it"), noted by its encoders as they set or declare an object
|
||||
/// over one, and taken at its commit.
|
||||
#[derive(Clone, Default)]
|
||||
@@ -524,24 +591,88 @@ impl Used {
|
||||
let Some(copied) = copied else {
|
||||
return;
|
||||
};
|
||||
self.note(copied, |u| {
|
||||
u.reads = Ranges::All;
|
||||
if writes {
|
||||
u.writes = Ranges::All;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn note(&self, copied: &Arc<Copied>, note: impl FnOnce(&mut CopyUse)) {
|
||||
let mut used = self.0.lock();
|
||||
match used.iter_mut().find(|u| Arc::ptr_eq(&u.copied, copied)) {
|
||||
Some(u) => u.writes |= writes,
|
||||
None => used.push(CopyUse {
|
||||
copied: Arc::clone(copied),
|
||||
writes,
|
||||
}),
|
||||
Some(u) => note(u),
|
||||
None => {
|
||||
let mut use_ = CopyUse {
|
||||
copied: Arc::clone(copied),
|
||||
reads: Ranges::EMPTY,
|
||||
writes: Ranges::EMPTY,
|
||||
};
|
||||
note(&mut use_);
|
||||
if !use_.reads.is_empty() || !use_.writes.is_empty() {
|
||||
used.push(use_);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A blit reads or writes these buffer-relative byte ranges.
|
||||
pub(super) fn buffer_ranges(
|
||||
&self,
|
||||
buffer: &RtBuffer,
|
||||
writes: bool,
|
||||
ranges: impl IntoIterator<Item = Range<u64>>,
|
||||
) {
|
||||
let Some(copied) = buffer.copied() else {
|
||||
return;
|
||||
};
|
||||
// A Managed buffer with a separate GPU copy uploads any pending `didModifyRange:` ranges
|
||||
// from its Shared backing at commit time, even if this blit touches a different page.
|
||||
if buffer.copied_alias() || buffer.gpu_copy_apart() {
|
||||
if ranges.into_iter().any(|bytes| !bytes.is_empty()) {
|
||||
self.add(Some(copied), writes);
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.add_ranges(copied, writes, buffer.rt().offset(), ranges);
|
||||
}
|
||||
|
||||
fn add_ranges(
|
||||
&self,
|
||||
copied: &Arc<Copied>,
|
||||
writes: bool,
|
||||
offset: u64,
|
||||
ranges: impl IntoIterator<Item = Range<u64>>,
|
||||
) {
|
||||
self.note(copied, |u| {
|
||||
let used = if writes { &mut u.writes } else { &mut u.reads };
|
||||
for bytes in ranges {
|
||||
if *used == Ranges::All {
|
||||
break;
|
||||
}
|
||||
let at = |byte: u64| {
|
||||
offset
|
||||
.saturating_add(byte)
|
||||
.min(copied.len.to_u64())
|
||||
.to_usize()
|
||||
};
|
||||
let bytes = at(bytes.start)..at(bytes.end);
|
||||
if !bytes.is_empty() {
|
||||
used.add(bytes);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The command buffer uses `buffer` where its work can write it (bound to a shader's slot, a
|
||||
/// blit's destination or fill): its copy, where it lies over one.
|
||||
/// synchronize): its copy, where it lies over one.
|
||||
pub(super) fn buffer(&self, buffer: &RtBuffer) {
|
||||
self.add(buffer.copied(), true);
|
||||
}
|
||||
|
||||
/// The command buffer's work reads `buffer` alone (as indices, as an indirect or tessellation
|
||||
/// factor buffer, as a blit's source): its copy, where it lies over one.
|
||||
/// factor buffer): its copy, where it lies over one.
|
||||
pub(super) fn buffer_read(&self, buffer: &RtBuffer) {
|
||||
self.add(buffer.copied(), false);
|
||||
}
|
||||
@@ -620,7 +751,7 @@ pub(super) fn declare(
|
||||
pub(super) fn writes(copies: &[CopyUse]) -> bool {
|
||||
copies
|
||||
.iter()
|
||||
.any(|u| u.writes && u.copied.kind != Kind::Drops)
|
||||
.any(|u| !u.writes.is_empty() && u.copied.kind != Kind::Drops)
|
||||
}
|
||||
|
||||
/// Counts a render pass `sel` made whose attachments lie in the blocks `blocks` where one is a
|
||||
@@ -656,12 +787,10 @@ pub(super) fn copy_in(copies: &[CopyUse]) {
|
||||
let mut tally = Tally::default();
|
||||
for u in copies {
|
||||
let at = clock.now_mono();
|
||||
let written = u.copied.copy_in();
|
||||
let bytes = match u.copied.kind {
|
||||
Kind::Merges | Kind::Drops => u.copied.len.to_u64(),
|
||||
Kind::Unchanging { .. } => 0,
|
||||
};
|
||||
tally.note(&u.copied, (written, bytes), (&clock, at));
|
||||
// A write needs the pre-submit CPU bytes in the base too. Otherwise merge_back
|
||||
// would see those bytes as CPU writes made during the submission.
|
||||
let chunks = u.reads.chunks(&u.writes, u.copied.len);
|
||||
tally.note(&u.copied, u.copied.copy_in(chunks), (&clock, at));
|
||||
}
|
||||
tally.count(true);
|
||||
synced(IN_BYTES_CODE, tally.written, &clock, began);
|
||||
@@ -688,14 +817,16 @@ fn merge_back(copies: &[CopyUse]) {
|
||||
let clock = crate::os::OsClock::new();
|
||||
let began = clock.now_mono();
|
||||
let mut tally = Tally::default();
|
||||
for u in copies.iter().filter(|u| u.writes) {
|
||||
for u in copies.iter().filter(|u| !u.writes.is_empty()) {
|
||||
let at = clock.now_mono();
|
||||
let written = match u.copied.kind {
|
||||
Kind::Merges => u.copied.merge_back(),
|
||||
let bytes = match u.copied.kind {
|
||||
Kind::Merges => u
|
||||
.copied
|
||||
.merge_back(u.writes.chunks(&Ranges::EMPTY, u.copied.len)),
|
||||
Kind::Drops => continue,
|
||||
Kind::Unchanging { .. } => u.copied.copy_whole(),
|
||||
Kind::Unchanging { .. } => (u.copied.copy_whole(), u.copied.len.to_u64()),
|
||||
};
|
||||
tally.note(&u.copied, (written, u.copied.len.to_u64()), (&clock, at));
|
||||
tally.note(&u.copied, bytes, (&clock, at));
|
||||
}
|
||||
tally.count(false);
|
||||
synced(BACK_BYTES_CODE, tally.written, &clock, began);
|
||||
@@ -815,16 +946,20 @@ impl Copied {
|
||||
/// Writes into the copy the bytes of the pages that differ from the base, and the base takes
|
||||
/// them: the bytes written. The whole of the pages for a copy of read-only pages that may
|
||||
/// change ("Writes dropped"); nothing for one of unchanging pages ("Unchanging pages").
|
||||
fn copy_in(&self) -> u64 {
|
||||
fn copy_in(&self, chunks: impl Iterator<Item = Range<usize>>) -> (u64, u64) {
|
||||
match self.kind {
|
||||
Kind::Merges => {}
|
||||
Kind::Drops => return self.copy_whole(),
|
||||
Kind::Unchanging { .. } => return 0,
|
||||
Kind::Drops => return (self.copy_whole(), self.len.to_u64()),
|
||||
Kind::Unchanging { .. } => return (0, 0),
|
||||
}
|
||||
let mut base = self.base.lock();
|
||||
let mut now = [0_u64; WORDS];
|
||||
let mut written = 0;
|
||||
for (chunk, was) in base.as_chunks_mut::<WORDS>().0.iter_mut().enumerate() {
|
||||
let mut scanned = 0;
|
||||
let base = base.as_chunks_mut::<WORDS>().0;
|
||||
for chunk in chunks.flatten() {
|
||||
scanned += CHUNK.to_u64();
|
||||
let was = &mut base[chunk];
|
||||
let at = chunk * CHUNK;
|
||||
// SAFETY: the chunk lies in the pages, mapped until the copy goes (`new`'s contract).
|
||||
unsafe { read_chunk(self.home.as_ptr().add(at), &mut now) };
|
||||
@@ -842,16 +977,20 @@ impl Copied {
|
||||
}
|
||||
}
|
||||
}
|
||||
written
|
||||
(written, scanned)
|
||||
}
|
||||
|
||||
/// Writes into the pages the bytes of the copy that differ from the base where the pages'
|
||||
/// still are the base's, and the base takes the copy's: the bytes written.
|
||||
fn merge_back(&self) -> u64 {
|
||||
fn merge_back(&self, chunks: impl Iterator<Item = Range<usize>>) -> (u64, u64) {
|
||||
let mut base = self.base.lock();
|
||||
let (mut gpu, mut cpu) = ([0_u64; WORDS], [0_u64; WORDS]);
|
||||
let mut written = 0;
|
||||
for (chunk, was) in base.as_chunks_mut::<WORDS>().0.iter_mut().enumerate() {
|
||||
let mut scanned = 0;
|
||||
let base = base.as_chunks_mut::<WORDS>().0;
|
||||
for chunk in chunks.flatten() {
|
||||
scanned += CHUNK.to_u64();
|
||||
let was = &mut base[chunk];
|
||||
let at = chunk * CHUNK;
|
||||
// SAFETY: the chunk lies in the copy's first bytes, the length of the pages.
|
||||
unsafe { read_chunk(self.copy.as_ptr().add(at), &mut gpu) };
|
||||
@@ -871,7 +1010,7 @@ impl Copied {
|
||||
}
|
||||
}
|
||||
}
|
||||
written
|
||||
(written, scanned)
|
||||
}
|
||||
|
||||
/// Writes the whole of the pages into the copy again, the GPU's writes to it put back ("Writes
|
||||
@@ -954,6 +1093,163 @@ mod tests {
|
||||
unsafe { Copied::new(home, len, kind, (copy, cap, None)) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blit_ranges_coalesce_clamp_and_fall_back_independently() -> Result<(), &'static str> {
|
||||
let mut pages = chunks(3);
|
||||
let home = NonNull::new(pages.as_mut_ptr().cast::<u8>()).ok_or("pages")?;
|
||||
let len = 3 * CHUNK;
|
||||
// SAFETY: the pages outlive the copy.
|
||||
let copied = Arc::new(unsafe { copy_of(home, len, Kind::Merges) }.ok_or("copy")?);
|
||||
let used = Used::default();
|
||||
let end = len.to_u64();
|
||||
used.add_ranges(&copied, false, 10, [3..3, end..u64::MAX]);
|
||||
assert!(used.take().is_empty());
|
||||
used.add_ranges(
|
||||
&copied,
|
||||
false,
|
||||
10,
|
||||
[12..20, 0..7, 6..12, end - 11..u64::MAX],
|
||||
);
|
||||
used.add_ranges(&copied, true, 0, std::iter::once(1..2));
|
||||
let uses = used.take();
|
||||
assert_eq!(uses[0].reads, Ranges::Known(vec![10..30, len - 1..len]));
|
||||
assert_eq!(
|
||||
uses[0]
|
||||
.reads
|
||||
.chunks(&uses[0].writes, len)
|
||||
.collect::<Vec<_>>(),
|
||||
[0..1, 2..3],
|
||||
);
|
||||
used.add_ranges(
|
||||
&copied,
|
||||
true,
|
||||
0,
|
||||
(0..=MAX_RANGES.to_u64()).map(|n| 2 * n..2 * n + 1),
|
||||
);
|
||||
used.add_ranges(&copied, false, 0, std::iter::once(2..3));
|
||||
let uses = used.take();
|
||||
assert_eq!(uses[0].writes, Ranges::All);
|
||||
assert_eq!(
|
||||
uses[0].reads,
|
||||
Ranges::Known(std::iter::once(2..3).collect())
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_shader_use_expands_a_local_blit_use() -> Result<(), &'static str> {
|
||||
let mut pages = chunks(2);
|
||||
let home = NonNull::new(pages.as_mut_ptr().cast::<u8>()).ok_or("pages")?;
|
||||
// SAFETY: the pages outlive the copy.
|
||||
let copied = Arc::new(unsafe { copy_of(home, 2 * CHUNK, Kind::Merges) }.ok_or("copy")?);
|
||||
let used = Used::default();
|
||||
for shader_writes in [false, true] {
|
||||
used.add_ranges(&copied, true, 0, std::iter::once(5..8));
|
||||
used.add(Some(&copied), shader_writes);
|
||||
let uses = used.take();
|
||||
assert_eq!(uses.len(), 1);
|
||||
assert_eq!(uses[0].reads, Ranges::All);
|
||||
let expected = if shader_writes {
|
||||
Ranges::All
|
||||
} else {
|
||||
Ranges::Known(std::iter::once(5..8).collect())
|
||||
};
|
||||
assert_eq!(uses[0].writes, expected);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_blit_syncs_only_its_chunks_and_keeps_cpu_writes() -> Result<(), &'static str> {
|
||||
let mut pages = chunks(5);
|
||||
let home = NonNull::new(pages.as_mut_ptr().cast::<u8>()).ok_or("pages")?;
|
||||
let len = 5 * CHUNK;
|
||||
// SAFETY: the pages outlive the copy.
|
||||
let copied = Arc::new(unsafe { copy_of(home, len, Kind::Merges) }.ok_or("copy")?);
|
||||
let used = Used::default();
|
||||
let (read, write, outside) = (CHUNK, 2 * CHUNK + 8, 4 * CHUNK);
|
||||
used.add_ranges(
|
||||
&copied,
|
||||
false,
|
||||
read.to_u64(),
|
||||
std::iter::once(0..CHUNK.to_u64()),
|
||||
);
|
||||
used.add_ranges(
|
||||
&copied,
|
||||
true,
|
||||
write.to_u64(),
|
||||
std::iter::once(0..CHUNK.to_u64()),
|
||||
);
|
||||
let uses = used.take();
|
||||
// SAFETY: each byte range lies inside its respective allocation.
|
||||
unsafe {
|
||||
home.as_ptr().add(read).write_bytes(0x11, CHUNK);
|
||||
home.as_ptr().add(write).write_bytes(0x22, CHUNK);
|
||||
home.as_ptr().add(outside).write(0x33);
|
||||
}
|
||||
copy_in(&uses);
|
||||
// SAFETY: same bounds as above, including the eight bytes before the destination.
|
||||
unsafe {
|
||||
assert_eq!(bytes(copied.copy.add(read), CHUNK), [0x11; CHUNK]);
|
||||
assert_eq!(bytes(copied.copy.add(write), CHUNK), [0x22; CHUNK]);
|
||||
assert_eq!(copied.copy.as_ptr().add(outside).read(), 0);
|
||||
copied.copy.as_ptr().add(write).write_bytes(0x44, CHUNK);
|
||||
home.as_ptr().add(write).write(0x55);
|
||||
home.as_ptr().add(write - 1).write(0x66);
|
||||
copied.copy.as_ptr().add(outside + 1).write(0x77);
|
||||
}
|
||||
merge_back(&uses);
|
||||
// SAFETY: same bounds as above.
|
||||
unsafe {
|
||||
assert_eq!(bytes(home.add(write - 1), 2), [0x66, 0x55]);
|
||||
assert_eq!(bytes(home.add(write + 1), CHUNK - 1), [0x44; CHUNK - 1]);
|
||||
assert_eq!(bytes(home.add(outside), 2), [0x33, 0]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_64_mib_copy_scans_only_the_chunks_of_a_4_kib_blit() -> Result<(), &'static str> {
|
||||
let len = 64 * 1024 * 1024;
|
||||
let mut pages = chunks(len / CHUNK);
|
||||
let mut memory = chunks(len / CHUNK);
|
||||
let home = NonNull::new(pages.as_mut_ptr().cast::<u8>()).ok_or("pages")?;
|
||||
let copy = NonNull::new(memory.as_mut_ptr().cast::<u8>()).ok_or("copy memory")?;
|
||||
// SAFETY: both allocations are disjoint, aligned and outlive the copy.
|
||||
let copied = Arc::new(
|
||||
unsafe { Copied::new(home, len, Kind::Merges, (copy, len, None)) }.ok_or("copy")?,
|
||||
);
|
||||
let clock = crate::os::OsClock::new();
|
||||
for (offset, expected) in [(len / 2, 1), (len / 2 + 4, 2)] {
|
||||
let used = Used::default();
|
||||
used.add_ranges(
|
||||
&copied,
|
||||
true,
|
||||
offset.to_u64(),
|
||||
std::iter::once(0..CHUNK.to_u64()),
|
||||
);
|
||||
let uses = used.take();
|
||||
for (label, ranges, want) in [
|
||||
("whole", &Ranges::All, 16_384),
|
||||
("local", &uses[0].writes, expected),
|
||||
] {
|
||||
let began = clock.now_mono();
|
||||
let (_, in_bytes) = copied.copy_in(ranges.chunks(&Ranges::EMPTY, len));
|
||||
let incoming = clock.now_mono().saturating_duration_since(began);
|
||||
let began = clock.now_mono();
|
||||
let (_, back_bytes) = copied.merge_back(ranges.chunks(&Ranges::EMPTY, len));
|
||||
let outgoing = clock.now_mono().saturating_duration_since(began);
|
||||
let segments = (in_bytes / CHUNK.to_u64(), back_bytes / CHUNK.to_u64());
|
||||
assert_eq!(segments, (want, want));
|
||||
eprintln!(
|
||||
"64 MiB / 4 KiB, offset {offset}, {label}: copy_in {} chunks {incoming:?}, merge_back {} chunks {outgoing:?}",
|
||||
segments.0, segments.1
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A copy holds its pages' bytes and zeros past them; a commit's copy in writes the bytes the
|
||||
/// CPU changed and leaves the copy's others, which the GPU may have written meanwhile; a
|
||||
/// completion's merge back writes the bytes the GPU changed where the CPU did not, a byte both
|
||||
@@ -971,7 +1267,13 @@ mod tests {
|
||||
// SAFETY: the copy's memory holds `TAIL` bytes past the pages'.
|
||||
let tail = bytes(unsafe { copied.copy.add(len) }, TAIL);
|
||||
assert_eq!(tail, vec![0; TAIL], "zeros past the pages' bytes");
|
||||
assert_eq!((copied.copy_in(), copied.merge_back()), (0, 0));
|
||||
assert_eq!(
|
||||
(
|
||||
copied.copy_in(std::iter::once(0..len / CHUNK)).0,
|
||||
copied.merge_back(std::iter::once(0..len / CHUNK)).0
|
||||
),
|
||||
(0, 0)
|
||||
);
|
||||
|
||||
// The CPU writes 3 bytes of the pages; the GPU, meanwhile, a byte of the copy beside one.
|
||||
// SAFETY: inside the pages and the copy.
|
||||
@@ -979,7 +1281,7 @@ mod tests {
|
||||
home.as_ptr().add(5).write_bytes(0x22, 3);
|
||||
copied.copy.as_ptr().add(8).write(0x33);
|
||||
}
|
||||
assert_eq!(copied.copy_in(), 3);
|
||||
assert_eq!(copied.copy_in(std::iter::once(0..len / CHUNK)).0, 3);
|
||||
let copy = bytes(copied.copy, 16);
|
||||
assert_eq!(copy[..5], [0x11; 5]);
|
||||
assert_eq!(copy[5..8], [0x22; 3]);
|
||||
@@ -994,14 +1296,20 @@ mod tests {
|
||||
copied.copy.as_ptr().add(far + 8).write(0x55);
|
||||
home.as_ptr().add(far + 8).write(0x66);
|
||||
}
|
||||
assert_eq!(copied.merge_back(), 1 + 8);
|
||||
assert_eq!(copied.merge_back(std::iter::once(0..len / CHUNK)).0, 1 + 8);
|
||||
let back = bytes(home, len);
|
||||
assert_eq!(back[8], 0x33);
|
||||
assert_eq!(back[far..far + 8], [0x44; 8]);
|
||||
assert_eq!(back[far + 8], 0x66);
|
||||
assert_eq!(copied.copy_in(), 1);
|
||||
assert_eq!(copied.copy_in(std::iter::once(0..len / CHUNK)).0, 1);
|
||||
assert_eq!(bytes(copied.copy, len), back);
|
||||
assert_eq!((copied.copy_in(), copied.merge_back()), (0, 0));
|
||||
assert_eq!(
|
||||
(
|
||||
copied.copy_in(std::iter::once(0..len / CHUNK)).0,
|
||||
copied.merge_back(std::iter::once(0..len / CHUNK)).0
|
||||
),
|
||||
(0, 0)
|
||||
);
|
||||
}
|
||||
|
||||
/// The count of `code` in the degradation counts' line.
|
||||
@@ -1074,7 +1382,11 @@ mod tests {
|
||||
);
|
||||
let why_now = [why_counts[0] + 1, why_counts[1] + len.to_u64()];
|
||||
assert_eq!(whys.map(counted), why_now, "by the guest's why");
|
||||
assert_eq!(copied.copy_in(), len.to_u64(), "whole at each");
|
||||
assert_eq!(
|
||||
copied.copy_in(std::iter::once(0..len / CHUNK)).0,
|
||||
len.to_u64(),
|
||||
"whole at each"
|
||||
);
|
||||
}
|
||||
|
||||
/// A command buffer's completion merges back only the copies a use of which can write them:
|
||||
@@ -1111,7 +1423,7 @@ mod tests {
|
||||
used.add(Some(written), true);
|
||||
used.add(None, true);
|
||||
let copies = used.take();
|
||||
let uses: Vec<bool> = copies.iter().map(|u| u.writes).collect();
|
||||
let uses: Vec<bool> = copies.iter().map(|u| !u.writes.is_empty()).collect();
|
||||
assert_eq!(uses, [false, false, true], "each copy once");
|
||||
assert!(writes(&copies));
|
||||
assert!(used.take().is_empty(), "taken");
|
||||
@@ -1218,7 +1530,11 @@ mod tests {
|
||||
read.add(Some(&copied), false);
|
||||
let reads = read.take();
|
||||
copy_in(&reads);
|
||||
assert_eq!(copied.copy_in(), 0, "never copied in");
|
||||
assert_eq!(
|
||||
copied.copy_in(std::iter::once(0..len / CHUNK)).0,
|
||||
0,
|
||||
"never copied in"
|
||||
);
|
||||
merge_back(&reads);
|
||||
let mut gpu = vec![0x11; len];
|
||||
gpu[CHUNK + 16..CHUNK + 24].fill(0x44);
|
||||
|
||||
@@ -464,7 +464,7 @@ impl Heap<RtPlatform> for RtObj<RtHeap> {
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
let placed = (true, self.copied.clone());
|
||||
let placed = (true, self.copied.clone(), false);
|
||||
let buffer = buffer::buffer_of(&self.device, made, self.options, placed, None);
|
||||
Ok(Some(buffer))
|
||||
});
|
||||
|
||||
@@ -109,7 +109,7 @@ use metal2vulkan::metal::{
|
||||
};
|
||||
use metal2vulkan_runtime as rt;
|
||||
|
||||
use crate::core::platform::render::{RenderCmd, RenderEncoder};
|
||||
use crate::core::platform::render::{RenderCmd, RenderEncoder, VertexDraw, encode_each};
|
||||
use crate::core::platform::types::{MtlScissorRect, MtlViewport};
|
||||
use crate::core::platform::{Handle, ObjId};
|
||||
use crate::core::raise::{OnFault, RaiseResult};
|
||||
@@ -123,7 +123,7 @@ use super::diag::{self, Bound, Point, Target, Use};
|
||||
use super::fault::{EncoderKind, EncoderNames, Naming};
|
||||
use super::render_pipeline::{Formats, Raster, RtRenderPipeline};
|
||||
use super::texture::RtTexture;
|
||||
use super::unbuilt::{Unbuilt, naming_functions, refuse};
|
||||
use super::unbuilt::{Named, Unbuilt, naming_functions, refuse};
|
||||
use super::{RtBuffer, RtObj, RtPlatform};
|
||||
|
||||
/// A count, a base or an index past rt's 32 bits.
|
||||
@@ -250,6 +250,40 @@ impl RtRenderEncoder {
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a draw gap's details and returns the functions to name when reporting the refusal.
|
||||
#[cold]
|
||||
fn refusal_functions(
|
||||
&self,
|
||||
seen: &Seen,
|
||||
sel: &'static str,
|
||||
stopped: &Stop,
|
||||
draw: bool,
|
||||
primitive: Option<u64>,
|
||||
viewports: Option<Viewports<'_>>,
|
||||
) -> Named {
|
||||
let functions = match (stopped, &seen.state) {
|
||||
(Stop::Rt(_) | Stop::Unbuilt(_), Some(state)) if draw => state.functions(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if let Stop::Rt(error @ rt::Error::Unsupported(rt::Gap::Draw { kind })) = stopped {
|
||||
let what = DrawDetail {
|
||||
primitive,
|
||||
raster: seen.state.as_ref().map(|state| state.raster()),
|
||||
formats: (*kind == rt::DrawKind::AttachmentFormats).then(|| self.formats(seen)),
|
||||
viewports,
|
||||
};
|
||||
naming_functions(functions.clone(), || {
|
||||
super::unbuilt::refusal_detail(sel, error, Some(&what));
|
||||
});
|
||||
match kind {
|
||||
rt::DrawKind::AttachmentRead => self.attachment_read(seen),
|
||||
rt::DrawKind::FetchedAttachment => self.fetched_attachment(seen),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
functions
|
||||
}
|
||||
|
||||
/// Encodes `cmd` but `endEncoding`, which the caller ends.
|
||||
fn command(&self, open: &mut Open, cmd: RenderCmd<'_, RtPlatform>) -> Result<(), Stop> {
|
||||
let Open {
|
||||
@@ -268,8 +302,7 @@ impl RtRenderEncoder {
|
||||
vertex_count,
|
||||
} => {
|
||||
set(*pipeline)?;
|
||||
let (start, count) = (small(vertex_start)?, small(vertex_count)?);
|
||||
e.draw_primitives(primitive(primitive_type)?, start, count, 1, 0)?;
|
||||
draw_primitives(e, primitive_type, vertex_start, vertex_count)?;
|
||||
}
|
||||
RenderCmd::DrawPrimitivesInstances {
|
||||
primitive_type,
|
||||
@@ -688,6 +721,18 @@ fn set(pipeline: Option<ObjId>) -> Result<(), Stop> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The short draw form, after checking that a pipeline is bound.
|
||||
fn draw_primitives(
|
||||
encoder: &mut rt::RenderCommandEncoder,
|
||||
primitive_type: u64,
|
||||
vertex_start: u64,
|
||||
vertex_count: u64,
|
||||
) -> Result<(), Stop> {
|
||||
let (start, count) = (small(vertex_start)?, small(vertex_count)?);
|
||||
encoder.draw_primitives(primitive(primitive_type)?, start, count, 1, 0)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `Ok` where a setting rt has none of is at Metal's default (`at_default`); unbuilt otherwise.
|
||||
fn unbuilt_unless(at_default: bool) -> Result<(), Stop> {
|
||||
match at_default {
|
||||
@@ -1104,30 +1149,9 @@ impl RenderEncoder<RtPlatform> for RtObj<RtRenderEncoder> {
|
||||
note_names(names, &cmd);
|
||||
}
|
||||
let stopped = self.command(&mut open, cmd).err();
|
||||
let functions = match (&stopped, &open.seen.state) {
|
||||
(Some(Stop::Rt(_) | Stop::Unbuilt(_)), Some(state)) if draw => state.functions(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if let Some(Stop::Rt(error @ rt::Error::Unsupported(rt::Gap::Draw { kind }))) = &stopped
|
||||
{
|
||||
let raster = open.seen.state.as_ref().map(|state| state.raster());
|
||||
let formats =
|
||||
(*kind == rt::DrawKind::AttachmentFormats).then(|| self.formats(&open.seen));
|
||||
let what = DrawDetail {
|
||||
primitive,
|
||||
raster,
|
||||
formats,
|
||||
viewports,
|
||||
};
|
||||
naming_functions(functions.clone(), || {
|
||||
super::unbuilt::refusal_detail(sel, error, Some(&what));
|
||||
});
|
||||
match kind {
|
||||
rt::DrawKind::AttachmentRead => self.attachment_read(&open.seen),
|
||||
rt::DrawKind::FetchedAttachment => self.fetched_attachment(&open.seen),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let functions = stopped.as_ref().map_or_else(Vec::new, |stop| {
|
||||
self.refusal_functions(&open.seen, sel, stop, draw, primitive, viewports)
|
||||
});
|
||||
let icb_gap = |error: &rt::Error| {
|
||||
matches!(
|
||||
error,
|
||||
@@ -1153,6 +1177,69 @@ impl RenderEncoder<RtPlatform> for RtObj<RtRenderEncoder> {
|
||||
recorded_answer
|
||||
}
|
||||
|
||||
fn encode_draws(&self, on: OnFault, draws: &[VertexDraw<'_, RtPlatform>]) -> RaiseResult<()> {
|
||||
if draws.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if crate::recorder::on() || super::copied::any() {
|
||||
return encode_each(self, on, draws);
|
||||
}
|
||||
let held = self.open.lock();
|
||||
let mut open = held.borrow_mut();
|
||||
let Open {
|
||||
rt,
|
||||
pipeline,
|
||||
seen,
|
||||
naming,
|
||||
} = &mut *open;
|
||||
let (Some(encoder), Some(_), Some(names)) = (rt, pipeline, naming.names()) else {
|
||||
drop(open);
|
||||
drop(held);
|
||||
return encode_each(self, on, draws);
|
||||
};
|
||||
let mut last = None;
|
||||
let mut buffer = None;
|
||||
for (i, draw) in draws.iter().enumerate() {
|
||||
if let Some(bound) = draw.buffer {
|
||||
names.bound_buffers.add_named(bound.named());
|
||||
}
|
||||
let key = draw.buffer.map(std::ptr::from_ref);
|
||||
if key != last {
|
||||
last = key;
|
||||
buffer = draw.buffer.map(|b| b.rt());
|
||||
}
|
||||
let bound = small(draw.index).and_then(|index| {
|
||||
encoder
|
||||
.set_vertex_buffer(buffer, draw.offset, index)
|
||||
.map_err(Stop::from)
|
||||
});
|
||||
// A refusal is reported once. After a refused bind, the draw still sees the
|
||||
// encoder's existing binding, and only commands that have yet to run go to encode.
|
||||
if let Err(stop) = bound {
|
||||
drop(open);
|
||||
drop(held);
|
||||
report(draw.vertex_buffer().selector(), Some(stop));
|
||||
self.encode(on, draw.primitives())?;
|
||||
return encode_each(self, on, &draws[i + 1..]);
|
||||
}
|
||||
if let Err(stop) = draw_primitives(
|
||||
encoder,
|
||||
draw.primitive_type,
|
||||
draw.vertex_start,
|
||||
draw.vertex_count,
|
||||
) {
|
||||
let sel = draw.primitives().selector();
|
||||
let functions =
|
||||
self.refusal_functions(seen, sel, &stop, true, Some(draw.primitive_type), None);
|
||||
drop(open);
|
||||
drop(held);
|
||||
naming_functions(functions, || report(sel, Some(stop)));
|
||||
return encode_each(self, on, &draws[i + 1..]);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Holds the encoder for `run` ([`RtRenderEncoder`]'s `open`): the commands `run` sends take
|
||||
/// its lock again on this thread, and another thread's wait for it to end.
|
||||
fn encoding<T>(&self, run: impl FnOnce() -> T) -> T {
|
||||
@@ -1515,6 +1602,382 @@ mod tests {
|
||||
words.iter().flat_map(|w| w.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
/// Each draw, including the draw after a refused bind, uses the binding it would see
|
||||
/// alone. The visibility result counts the draws even when a later one covers their pixels.
|
||||
#[test]
|
||||
fn draw_batches_match_individual_commands_on_vulkan() -> Result<(), &'static str> {
|
||||
check_draw_batch(DrawBatchCase::Existing)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draw_batches_clear_and_rebind_a_vertex_buffer_on_vulkan() -> Result<(), &'static str> {
|
||||
check_draw_batch(DrawBatchCase::Unbind)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draw_batches_report_a_gap_and_continue_on_vulkan() -> Result<(), &'static str> {
|
||||
check_draw_batch(DrawBatchCase::Gap)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draw_batches_record_bound_buffer_names_on_vulkan() -> Result<(), &'static str> {
|
||||
check_draw_batch(DrawBatchCase::Names)
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
enum DrawBatchCase {
|
||||
Existing,
|
||||
Unbind,
|
||||
Gap,
|
||||
Names,
|
||||
}
|
||||
|
||||
fn check_draw_batch(case: DrawBatchCase) -> Result<(), &'static str> {
|
||||
use crate::core::platform::command::WorkNames;
|
||||
use crate::rt_platform::fault::{Ids, Operands, name_buffer};
|
||||
use std::sync::Arc;
|
||||
|
||||
let platform = RtPlatform::new();
|
||||
let device = platform.system_default_device().ok_or("no Vulkan device")?;
|
||||
let queue = device.new_command_queue().ok_or("no command queue")?;
|
||||
let state = vdesc_state(&device, &function(&device, COLOR, "render_color"));
|
||||
let (red, green, cyan, blue) = (
|
||||
[255, 0, 0, 255],
|
||||
[0, 255, 0, 255],
|
||||
[0, 255, 255, 255],
|
||||
[0, 0, 255, 255],
|
||||
);
|
||||
let a = shared(&device, &vertices(&[green, cyan]));
|
||||
let b = shared(&device, &vertices(&[blue]));
|
||||
name_buffer(&a, 7);
|
||||
let results = shared(&device, &[0; 8]);
|
||||
let on = OnFault::Return;
|
||||
let Ok(Some(target)) = device.new_texture(
|
||||
on,
|
||||
&platform.texture_descriptor(&TextureDesc {
|
||||
width: 4,
|
||||
height: 4,
|
||||
usage: 5,
|
||||
..TextureDesc::default()
|
||||
}),
|
||||
) else {
|
||||
return Err("no render target");
|
||||
};
|
||||
let pass = pass(&target, 2);
|
||||
pass.set_pass(&PassSet {
|
||||
visibility_result_buffer: Some(Some(&results)),
|
||||
..PassSet::default()
|
||||
});
|
||||
let draw_a = VertexDraw {
|
||||
buffer: Some(&a),
|
||||
offset: 0,
|
||||
index: 0,
|
||||
primitive_type: TRIANGLE,
|
||||
vertex_start: 0,
|
||||
vertex_count: 3,
|
||||
};
|
||||
let next_a = VertexDraw {
|
||||
offset: 36,
|
||||
..draw_a
|
||||
};
|
||||
let draw_b = VertexDraw {
|
||||
buffer: Some(&b),
|
||||
..draw_a
|
||||
};
|
||||
let bad_bind = VertexDraw {
|
||||
index: 31,
|
||||
..draw_b
|
||||
};
|
||||
let bad_draw = VertexDraw {
|
||||
primitive_type: u64::MAX,
|
||||
..draw_b
|
||||
};
|
||||
let codes = [RtRefusal::Refused, RtRefusal::Ours, RtRefusal::Gap].map(RtRefusal::code);
|
||||
let render = |draws: &[VertexDraw<'_, RtPlatform>],
|
||||
batch,
|
||||
operands: bool,
|
||||
no_pipeline: bool,
|
||||
ended| {
|
||||
let Ok(Some(cb)) = queue.command_buffer(on) else {
|
||||
return Err("no command buffer");
|
||||
};
|
||||
if !operands {
|
||||
cb.names_work(&Arc::new(WorkNames::new(1)));
|
||||
}
|
||||
let Ok(Some(encoder)) = cb.render_encoder(on, &pass) else {
|
||||
return Err("no render encoder");
|
||||
};
|
||||
if !no_pipeline {
|
||||
assert_eq!(
|
||||
encoder.encode(
|
||||
on,
|
||||
RenderCmd::SetRenderPipelineState {
|
||||
pipeline_state: Some(&state),
|
||||
},
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
encoder.encode(
|
||||
on,
|
||||
RenderCmd::SetVisibilityResultMode { mode: 2, offset: 0 }
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
if case == DrawBatchCase::Gap {
|
||||
// Triangles still draw; the line in the middle hits rt's DrawKind::LineWidth.
|
||||
encoder
|
||||
.open
|
||||
.lock()
|
||||
.borrow_mut()
|
||||
.rt
|
||||
.as_mut()
|
||||
.ok_or("no rt encoder")?
|
||||
.set_line_width(2.0);
|
||||
}
|
||||
if ended {
|
||||
assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(()));
|
||||
}
|
||||
let before = codes.map(counted);
|
||||
let answer = if batch {
|
||||
encoder.encode_draws(on, draws)
|
||||
} else {
|
||||
encode_each(&encoder, on, draws)
|
||||
};
|
||||
assert_eq!(answer, Ok(()));
|
||||
let refused = std::array::from_fn(|i| counted(codes[i]) - before[i]);
|
||||
let names = encoder.open.lock().borrow_mut().naming.names().cloned();
|
||||
if let Some(names) = &names {
|
||||
assert_eq!(names.operands, operands.then(Operands::default));
|
||||
}
|
||||
if !ended {
|
||||
assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(()));
|
||||
}
|
||||
assert_eq!(cb.commit(on), Ok(()));
|
||||
assert_eq!(cb.wait_until_completed(on), Ok(()));
|
||||
assert_eq!(cb.status(), CommandBufferStatus::COMPLETED);
|
||||
let mut pixels = [0; 64];
|
||||
target.read_pixels(&mut pixels, 16);
|
||||
// SAFETY: the Shared result buffer is mapped for eight bytes and the GPU has finished.
|
||||
let samples =
|
||||
u64::from_le_bytes(unsafe { results.contents().as_ptr::<[u8; 8]>().read() });
|
||||
Ok((
|
||||
pixels,
|
||||
samples,
|
||||
refused,
|
||||
names.map(|names| names.bound_buffers),
|
||||
))
|
||||
};
|
||||
|
||||
if case != DrawBatchCase::Existing {
|
||||
let (draws, colour, samples, refused) = match case {
|
||||
DrawBatchCase::Unbind => (
|
||||
vec![
|
||||
draw_a,
|
||||
VertexDraw {
|
||||
buffer: None,
|
||||
..draw_a
|
||||
},
|
||||
next_a,
|
||||
],
|
||||
cyan,
|
||||
32,
|
||||
[0, 1, 0],
|
||||
),
|
||||
DrawBatchCase::Gap => (
|
||||
vec![
|
||||
draw_a,
|
||||
VertexDraw {
|
||||
primitive_type: 1,
|
||||
vertex_count: 2,
|
||||
..draw_b
|
||||
},
|
||||
next_a,
|
||||
],
|
||||
cyan,
|
||||
32,
|
||||
[0, 0, 1],
|
||||
),
|
||||
DrawBatchCase::Names => (vec![draw_a, next_a, draw_b, draw_b], blue, 64, [0, 0, 0]),
|
||||
DrawBatchCase::Existing => unreachable!("handled by the cases below"),
|
||||
};
|
||||
let batch = render(&draws, true, true, false, false)?;
|
||||
assert_eq!(batch, render(&draws, false, true, false, false)?);
|
||||
let mut bound = Ids::default();
|
||||
bound.add(7);
|
||||
match case {
|
||||
DrawBatchCase::Gap => bound.add(0),
|
||||
DrawBatchCase::Names => {
|
||||
bound.add(0);
|
||||
bound.add(0);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
assert_eq!(
|
||||
batch,
|
||||
(
|
||||
std::array::from_fn(|i| colour[i % 4]),
|
||||
samples,
|
||||
refused,
|
||||
Some(bound)
|
||||
)
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for (draws, operands, no_pipeline, ended, colour, samples, refusals) in [
|
||||
(&[][..], false, false, false, red, 0, 0),
|
||||
(&[draw_a, next_a][..], false, false, false, cyan, 32, 0),
|
||||
(
|
||||
&[draw_a, next_a, draw_b][..],
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
blue,
|
||||
48,
|
||||
0,
|
||||
),
|
||||
(
|
||||
&[draw_a, next_a, draw_b][..],
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
blue,
|
||||
48,
|
||||
0,
|
||||
),
|
||||
(&[draw_a, bad_bind][..], false, false, false, green, 32, 1),
|
||||
(
|
||||
&[draw_a, bad_bind, next_a][..],
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
cyan,
|
||||
48,
|
||||
1,
|
||||
),
|
||||
(
|
||||
&[draw_a, bad_draw, bad_bind][..],
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
blue,
|
||||
32,
|
||||
2,
|
||||
),
|
||||
(&[draw_a, draw_b][..], false, true, false, red, 0, 2),
|
||||
(&[draw_a, draw_b][..], false, false, true, red, 0, 4),
|
||||
(&[][..], false, false, true, red, 0, 0),
|
||||
] {
|
||||
let batch = render(draws, true, operands, no_pipeline, ended)?;
|
||||
assert_eq!(batch, render(draws, false, operands, no_pipeline, ended)?);
|
||||
assert_eq!(
|
||||
(batch.0, batch.1, batch.2[0]),
|
||||
(std::array::from_fn(|i| colour[i % 4]), samples, refusals)
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draw_batches_sync_a_copied_vertex_buffer_on_vulkan() -> Result<(), &'static str> {
|
||||
use crate::core::host::HostPtr;
|
||||
use crate::core::num::ToUsize as _;
|
||||
use crate::core::platform::HostRange;
|
||||
use std::alloc::{Layout, alloc_zeroed, dealloc};
|
||||
|
||||
let platform = RtPlatform::new();
|
||||
let device = platform.system_default_device().ok_or("no Vulkan device")?;
|
||||
let queue = device.new_command_queue().ok_or("no command queue")?;
|
||||
let on = OnFault::Return;
|
||||
let page = device.facts().page_size;
|
||||
let layout =
|
||||
Layout::from_size_align(page.to_usize(), page.to_usize()).map_err(|_| "page layout")?;
|
||||
// SAFETY: the page layout has nonzero size.
|
||||
let memory = HostPtr::from_ptr(unsafe { alloc_zeroed(layout) });
|
||||
if memory == HostPtr::from_ptr(std::ptr::null_mut::<u8>()) {
|
||||
return Err("page allocation");
|
||||
}
|
||||
// SAFETY: the page lives until the buffer's deallocator runs.
|
||||
let bytes = unsafe { HostRange::new(memory, page) };
|
||||
let buffer = device
|
||||
.new_buffer_over_host_memory(
|
||||
on,
|
||||
bytes,
|
||||
super::super::buffer::READ_ONLY,
|
||||
// SAFETY: this frees the page once the copy and its users let it go.
|
||||
Some(Box::new(move || unsafe {
|
||||
dealloc(memory.as_ptr(), layout)
|
||||
})),
|
||||
)
|
||||
.map_err(|_| "buffer creation raised")?
|
||||
.ok_or("no copied buffer")?;
|
||||
assert!(buffer.copied().is_some());
|
||||
assert!(super::super::copied::any());
|
||||
let green = [0, 255, 0, 255];
|
||||
let data = vertices(&[green]);
|
||||
// SAFETY: the vertices fit in the mapped page, and the copy was already initialized.
|
||||
unsafe {
|
||||
memory
|
||||
.as_ptr::<u8>()
|
||||
.copy_from_nonoverlapping(data.as_ptr(), data.len())
|
||||
};
|
||||
let state = vdesc_state(&device, &function(&device, COLOR, "render_color"));
|
||||
let target = device
|
||||
.new_texture(
|
||||
on,
|
||||
&platform.texture_descriptor(&TextureDesc {
|
||||
width: 4,
|
||||
height: 4,
|
||||
usage: 5,
|
||||
..TextureDesc::default()
|
||||
}),
|
||||
)
|
||||
.map_err(|_| "texture creation raised")?
|
||||
.ok_or("no render target")?;
|
||||
let pass = pass(&target, 2);
|
||||
let commands = queue
|
||||
.command_buffer(on)
|
||||
.map_err(|_| "command buffer raised")?
|
||||
.ok_or("no command buffer")?;
|
||||
let encoder = commands
|
||||
.render_encoder(on, &pass)
|
||||
.map_err(|_| "render encoder raised")?
|
||||
.ok_or("no render encoder")?;
|
||||
assert_eq!(
|
||||
encoder.encode(
|
||||
on,
|
||||
RenderCmd::SetRenderPipelineState {
|
||||
pipeline_state: Some(&state)
|
||||
}
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
assert_eq!(
|
||||
encoder.encode_draws(
|
||||
on,
|
||||
&[VertexDraw {
|
||||
buffer: Some(&buffer),
|
||||
offset: 0,
|
||||
index: 0,
|
||||
primitive_type: TRIANGLE,
|
||||
vertex_start: 0,
|
||||
vertex_count: 3,
|
||||
}]
|
||||
),
|
||||
Ok(())
|
||||
);
|
||||
assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(()));
|
||||
assert_eq!(commands.commit(on), Ok(()));
|
||||
assert_eq!(commands.wait_until_completed(on), Ok(()));
|
||||
assert_eq!(commands.status(), CommandBufferStatus::COMPLETED);
|
||||
let mut pixels = [0; 64];
|
||||
target.read_pixels(&mut pixels, 16);
|
||||
assert_eq!(pixels, std::array::from_fn(|i| green[i % 4]));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A run of `encoding` holds the encoder: the run's own commands go through and draw, and a
|
||||
/// command another thread sends meanwhile waits for the run to end, then goes through.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,500 @@
|
||||
//! Collects a window's SDL file or text drop and forwards it to the local host bridge.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::io::{self, Write as _};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::mpsc::{self, SyncSender, TrySendError};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::geometry::{self, Rect};
|
||||
|
||||
/// Maximum number of files forwarded in a single drop.
|
||||
const MAX_DROP_PATHS: usize = 256;
|
||||
|
||||
/// Maximum joined UTF-8 text size forwarded in a single drop.
|
||||
const MAX_DROP_TEXT_BYTES: usize = 128 << 10;
|
||||
|
||||
/// Drop contents and guest-image coordinates for one completed host drop.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct DropPayload {
|
||||
/// Guest display port that received the drop.
|
||||
pub display_index: u64,
|
||||
/// Horizontal position, clamped to the guest image.
|
||||
pub norm_x: f64,
|
||||
/// Vertical position, clamped to the guest image.
|
||||
pub norm_y: f64,
|
||||
/// Whether the original position was inside the guest image.
|
||||
pub in_image: bool,
|
||||
/// Host paths in the order SDL delivered them.
|
||||
pub paths: Vec<String>,
|
||||
/// Joined text for a drop without files.
|
||||
pub text: Option<String>,
|
||||
}
|
||||
|
||||
/// Maps a window point to the guest image, using its center when geometry is unavailable.
|
||||
pub(crate) fn normalize_point(point: Option<(f64, f64)>, image: Rect) -> (f64, f64, bool) {
|
||||
let Some((x, y)) = point else {
|
||||
return (0.5, 0.5, false);
|
||||
};
|
||||
if ![x, y, image.x, image.y, image.width, image.height]
|
||||
.into_iter()
|
||||
.all(f64::is_finite)
|
||||
|| image.width <= 0.0
|
||||
|| image.height <= 0.0
|
||||
{
|
||||
return (0.5, 0.5, false);
|
||||
}
|
||||
(
|
||||
((x - image.x) / image.width).clamp(0.0, 1.0),
|
||||
((y - image.y) / image.height).clamp(0.0, 1.0),
|
||||
geometry::contains(image, (x, y)),
|
||||
)
|
||||
}
|
||||
|
||||
/// Drop state for one SDL window, active from begin or the first file, text or position.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct DropBatch {
|
||||
/// Host paths collected for this batch.
|
||||
paths: Option<Vec<String>>,
|
||||
/// Nonempty input chunks in delivery order, bounded before joining.
|
||||
texts: Option<Vec<String>>,
|
||||
/// Joined bytes consumed, saturated at the limit once a chunk is truncated.
|
||||
text_bytes: usize,
|
||||
/// Most recent finite position, in SDL window coordinates.
|
||||
last_pos: Option<(f64, f64)>,
|
||||
}
|
||||
|
||||
impl DropBatch {
|
||||
/// Starts a new batch, discarding an unfinished drop.
|
||||
pub(crate) fn begin(&mut self) {
|
||||
self.paths = Some(Vec::new());
|
||||
self.texts = None;
|
||||
self.text_bytes = 0;
|
||||
self.last_pos = None;
|
||||
}
|
||||
|
||||
/// Records the most recent usable position.
|
||||
pub(crate) fn position(&mut self, x: f64, y: f64) {
|
||||
if x.is_finite() && y.is_finite() {
|
||||
self.last_pos = Some((x, y));
|
||||
}
|
||||
}
|
||||
|
||||
/// Accepts a file even if SDL omitted begin, taking its position as a fallback.
|
||||
pub(crate) fn file(&mut self, path: String, pos: Option<(f64, f64)>) {
|
||||
if path.is_empty() {
|
||||
return;
|
||||
}
|
||||
let paths = self.paths.get_or_insert_with(Vec::new);
|
||||
if paths.len() < MAX_DROP_PATHS {
|
||||
paths.push(path);
|
||||
}
|
||||
if self.last_pos.is_none() && let Some((x, y)) = pos {
|
||||
self.position(x, y);
|
||||
}
|
||||
}
|
||||
|
||||
/// Collects UTF-8 text up to the byte limit, including separators between chunks.
|
||||
pub(crate) fn text(&mut self, chunk: String, pos: Option<(f64, f64)>) {
|
||||
if chunk.is_empty() {
|
||||
return;
|
||||
}
|
||||
if self.last_pos.is_none() && let Some((x, y)) = pos {
|
||||
self.position(x, y);
|
||||
}
|
||||
if self.text_bytes == MAX_DROP_TEXT_BYTES {
|
||||
return;
|
||||
}
|
||||
let separator = usize::from(self.texts.is_some());
|
||||
let remaining = MAX_DROP_TEXT_BYTES - self.text_bytes - separator;
|
||||
let texts = self.texts.get_or_insert_with(Vec::new);
|
||||
if chunk.len() > remaining {
|
||||
let kept = &chunk[..chunk.floor_char_boundary(remaining)];
|
||||
if !kept.is_empty() {
|
||||
texts.push(kept.to_owned());
|
||||
}
|
||||
self.text_bytes = MAX_DROP_TEXT_BYTES;
|
||||
} else {
|
||||
self.text_bytes += separator + chunk.len();
|
||||
texts.push(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
/// Finishes this batch and yields its files or text and normalized drop position.
|
||||
pub(crate) fn complete(
|
||||
&mut self,
|
||||
display_index: u64,
|
||||
image: Rect,
|
||||
pos: Option<(f64, f64)>,
|
||||
) -> Option<DropPayload> {
|
||||
let point = self.last_pos.take().or(pos);
|
||||
let paths = self.paths.take().unwrap_or_default();
|
||||
let texts = self.texts.take();
|
||||
self.text_bytes = 0;
|
||||
let text = if paths.is_empty() {
|
||||
Some(texts.filter(|chunks| !chunks.is_empty())?.join("\n"))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (norm_x, norm_y, in_image) = normalize_point(point, image);
|
||||
Some(DropPayload {
|
||||
display_index,
|
||||
norm_x,
|
||||
norm_y,
|
||||
in_image,
|
||||
paths,
|
||||
text,
|
||||
})
|
||||
}
|
||||
|
||||
/// Discards drop contents and position when the window closes.
|
||||
pub(crate) fn reset(&mut self) {
|
||||
*self = Self::default();
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends one quoted string with RFC 8259 escapes.
|
||||
fn push_json_string(json: &mut String, value: &str) {
|
||||
json.push('"');
|
||||
for ch in value.chars() {
|
||||
match ch {
|
||||
'"' => json.push_str("\\\""),
|
||||
'\\' => json.push_str("\\\\"),
|
||||
'\u{8}' => json.push_str("\\b"),
|
||||
'\u{c}' => json.push_str("\\f"),
|
||||
'\n' => json.push_str("\\n"),
|
||||
'\r' => json.push_str("\\r"),
|
||||
'\t' => json.push_str("\\t"),
|
||||
'\0'..='\u{1f}' => {
|
||||
// Writing to a String is infallible.
|
||||
let _ = write!(json, "\\u{:04x}", u32::from(ch));
|
||||
}
|
||||
_ => json.push(ch),
|
||||
}
|
||||
}
|
||||
json.push('"');
|
||||
}
|
||||
|
||||
/// Encodes a file or text drop as UTF-8 JSON.
|
||||
pub(crate) fn encode_drop_json(payload: &DropPayload) -> String {
|
||||
let mut json = format!(
|
||||
r#"{{"display_index":{},"norm_x":{},"norm_y":{},"in_image":{}"#,
|
||||
payload.display_index, payload.norm_x, payload.norm_y, payload.in_image,
|
||||
);
|
||||
if !payload.paths.is_empty() {
|
||||
json.push_str(r#","paths":["#);
|
||||
for (i, path) in payload.paths.iter().enumerate() {
|
||||
if i != 0 {
|
||||
json.push(',');
|
||||
}
|
||||
push_json_string(&mut json, path);
|
||||
}
|
||||
json.push(']');
|
||||
} else if let Some(text) = &payload.text {
|
||||
json.push_str(r#","text":"#);
|
||||
push_json_string(&mut json, text);
|
||||
}
|
||||
json.push('}');
|
||||
json
|
||||
}
|
||||
|
||||
/// Parses the explicit IPv4 loopback endpoint used by the host drop bridge.
|
||||
fn parse_loopback_drop_url(raw: &str) -> Option<(SocketAddr, String)> {
|
||||
let rest = raw.strip_prefix("http://127.0.0.1:")?;
|
||||
let (port, path) = match rest.find('/') {
|
||||
Some(i) => (&rest[..i], &rest[i..]),
|
||||
None => (rest, "/v1/host-drop"),
|
||||
};
|
||||
if !port.bytes().all(|b| b.is_ascii_digit())
|
||||
|| path.bytes().any(|b| b.is_ascii_control() || b == b' ')
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let port: u16 = port.parse().ok()?;
|
||||
(port != 0).then(|| (SocketAddr::from(([127, 0, 0, 1], port)), path.to_owned()))
|
||||
}
|
||||
|
||||
/// SDL's bounded queue to the HTTP worker.
|
||||
static DROP_TX: OnceLock<SyncSender<DropPayload>> = OnceLock::new();
|
||||
|
||||
/// Starts the HTTP worker when the runtime provides a valid local URL and bearer token.
|
||||
#[cfg_attr(
|
||||
not(any(target_os = "linux", target_os = "windows")),
|
||||
expect(dead_code, reason = "only the SDL thread starts the host drop forwarder")
|
||||
)]
|
||||
pub(crate) fn install_host_drop_forwarder() {
|
||||
let Ok(url) = std::env::var("REIMS_GO_DROP_URL") else {
|
||||
return;
|
||||
};
|
||||
let Ok(token) = std::env::var("REIMS_GO_DROP_TOKEN") else {
|
||||
return;
|
||||
};
|
||||
if token.is_empty() || token.contains(['\r', '\n']) || DROP_TX.get().is_some() {
|
||||
return;
|
||||
}
|
||||
let Some((addr, path)) = parse_loopback_drop_url(&url) else {
|
||||
log::warn!(target: "reims_vgpu_window", "ignoring invalid REIMS_GO_DROP_URL");
|
||||
return;
|
||||
};
|
||||
let (tx, rx) = mpsc::sync_channel(16);
|
||||
match std::thread::Builder::new()
|
||||
.name("reims-vgpu.drop".into())
|
||||
.spawn(move || {
|
||||
for payload in rx {
|
||||
if let Err(err) = post_loopback_drop(addr, &path, &token, &payload) {
|
||||
log::warn!(target: "reims_vgpu_window", "could not forward file drop: {err}");
|
||||
}
|
||||
}
|
||||
}) {
|
||||
Ok(_) => {
|
||||
let _ = DROP_TX.set(tx);
|
||||
}
|
||||
Err(err) => log::warn!(target: "reims_vgpu_window", "could not start drop worker: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Enqueues a drop without waiting for network I/O or queue space on the UI thread.
|
||||
pub(crate) fn submit(payload: DropPayload) {
|
||||
if let Some(tx) = DROP_TX.get()
|
||||
&& let Err(TrySendError::Full(_)) = tx.try_send(payload)
|
||||
{
|
||||
log::warn!(target: "reims_vgpu_window", "file drop queue is full");
|
||||
}
|
||||
}
|
||||
|
||||
/// Posts one complete JSON payload to the authenticated IPv4 loopback bridge.
|
||||
fn post_loopback_drop(
|
||||
addr: SocketAddr,
|
||||
path: &str,
|
||||
token: &str,
|
||||
payload: &DropPayload,
|
||||
) -> io::Result<()> {
|
||||
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_millis(500))?;
|
||||
stream.set_write_timeout(Some(Duration::from_millis(2000)))?;
|
||||
let body = encode_drop_json(payload);
|
||||
write!(
|
||||
stream,
|
||||
"POST {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer {token}\r\n\
|
||||
Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
||||
body.len()
|
||||
)?;
|
||||
stream.write_all(body.as_bytes())
|
||||
}
|
||||
|
||||
/// Offline tests for window drops and the host bridge protocol.
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Read;
|
||||
use std::net::TcpListener;
|
||||
|
||||
/// Guest image offset from the window edges.
|
||||
const IMAGE: Rect = Rect { x: 10.0, y: 20.0, width: 40.0, height: 80.0 };
|
||||
|
||||
/// Coordinates use half-open image bounds and clamp outside those bounds.
|
||||
#[test]
|
||||
fn normalizes_window_points() {
|
||||
for (point, expected) in [
|
||||
((20.0, 80.0), (0.25, 0.75, true)),
|
||||
((10.0, 20.0), (0.0, 0.0, true)),
|
||||
((50.0, 100.0), (1.0, 1.0, false)),
|
||||
((0.0, 120.0), (0.0, 1.0, false)),
|
||||
] {
|
||||
assert_eq!(normalize_point(Some(point), IMAGE), expected);
|
||||
}
|
||||
let center = (0.5, 0.5, false);
|
||||
for point in [None, Some((f64::NAN, 40.0)), Some((20.0, f64::INFINITY))] {
|
||||
assert_eq!(normalize_point(point, IMAGE), center);
|
||||
}
|
||||
for bad in [0.0, -1.0, f64::NAN, f64::INFINITY] {
|
||||
for image in [Rect { width: bad, ..IMAGE }, Rect { height: bad, ..IMAGE }] {
|
||||
assert_eq!(normalize_point(Some((20.0, 80.0)), image), center);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Position events override file and completion coordinates, retaining file order.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn batch_completes_with_latest_position() {
|
||||
let mut batch = DropBatch::default();
|
||||
batch.begin();
|
||||
batch.file("first".into(), Some((50.0, 100.0)));
|
||||
batch.position(20.0, 80.0);
|
||||
batch.position(f64::NAN, 90.0);
|
||||
batch.file("second".into(), Some((40.0, 30.0)));
|
||||
let p = batch.complete(42, IMAGE, Some((30.0, 60.0))).expect("two files");
|
||||
assert_eq!(p.display_index, 42);
|
||||
assert_eq!(p.paths, ["first", "second"]);
|
||||
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
|
||||
assert!(batch.complete(42, IMAGE, None).is_none());
|
||||
}
|
||||
|
||||
/// Missing begin, invalid file coordinates, completion fallback and reset are independent.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn handles_partial_batches() {
|
||||
let mut batch = DropBatch::default();
|
||||
batch.file("".into(), Some((10.0, 20.0)));
|
||||
batch.file("first".into(), Some((1.0, f64::NAN)));
|
||||
batch.file("second".into(), Some((20.0, 80.0)));
|
||||
batch.file("third".into(), Some((40.0, 30.0)));
|
||||
let p = batch.complete(1, IMAGE, None).expect("file-only drop");
|
||||
assert_eq!(p.paths, ["first", "second", "third"]);
|
||||
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
|
||||
batch.file("abandoned".into(), Some((20.0, 80.0)));
|
||||
batch.begin();
|
||||
assert!(batch.complete(1, IMAGE, None).is_none());
|
||||
batch.file("closed".into(), Some((20.0, 80.0)));
|
||||
batch.reset();
|
||||
assert!(batch.complete(1, IMAGE, None).is_none());
|
||||
batch.position(20.0, 80.0);
|
||||
assert!(batch.complete(1, IMAGE, None).is_none());
|
||||
batch.file("next".into(), None);
|
||||
let p = batch.complete(2, IMAGE, Some((60.0, 60.0))).expect("fresh drop");
|
||||
assert_eq!((p.norm_x, p.norm_y, p.in_image), (1.0, 0.5, false));
|
||||
}
|
||||
|
||||
/// Oversized drops retain the first 256 paths in order.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn caps_paths() {
|
||||
let mut batch = DropBatch::default();
|
||||
for i in 0..260 {
|
||||
batch.file(i.to_string(), None);
|
||||
}
|
||||
let p = batch.complete(0, IMAGE, None).expect("bounded drop");
|
||||
assert_eq!(p.paths, (0..256).map(|i| i.to_string()).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
/// URL drops keep their position and subsequent batches join chunks in order.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn collects_url_and_multiline_text() {
|
||||
let mut batch = DropBatch::default();
|
||||
let url = "https://example.org/路径";
|
||||
batch.text(url.into(), Some((20.0, 80.0)));
|
||||
let p = batch.complete(1, IMAGE, None).expect("URL drop");
|
||||
assert_eq!(p.text.as_deref(), Some(url));
|
||||
assert!(p.paths.is_empty());
|
||||
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
|
||||
|
||||
batch.text("abandoned".into(), None);
|
||||
batch.begin();
|
||||
batch.text("one\ntwo".into(), None);
|
||||
batch.text(String::new(), None);
|
||||
batch.text("three".into(), None);
|
||||
let p = batch.complete(1, IMAGE, None).expect("multiline drop");
|
||||
assert_eq!(p.text.as_deref(), Some("one\ntwo\nthree"));
|
||||
}
|
||||
|
||||
/// A split UTF-8 character ends collection even when a smaller chunk would fit.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn truncates_text_at_utf8_boundary() {
|
||||
let mut batch = DropBatch::default();
|
||||
let prefix = "a".repeat(MAX_DROP_TEXT_BYTES - 6);
|
||||
batch.text(prefix.clone(), None);
|
||||
batch.text("界界".into(), None);
|
||||
batch.text("x".into(), None);
|
||||
let p = batch.complete(0, IMAGE, None).expect("bounded text drop");
|
||||
assert_eq!(p.text, Some(format!("{prefix}\n界")));
|
||||
|
||||
let prefix = "a".repeat(MAX_DROP_TEXT_BYTES - 3);
|
||||
batch.text(prefix.clone(), None);
|
||||
batch.text("界".into(), None);
|
||||
let p = batch.complete(0, IMAGE, None).expect("two bytes remaining");
|
||||
assert_eq!(p.text, Some(prefix));
|
||||
}
|
||||
|
||||
/// Files take precedence over text regardless of arrival order.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn files_take_precedence() {
|
||||
let mut batch = DropBatch::default();
|
||||
batch.text("before".into(), None);
|
||||
batch.file("path".into(), None);
|
||||
batch.text("after".into(), None);
|
||||
let p = batch.complete(0, IMAGE, None).expect("mixed drop");
|
||||
assert_eq!(p.paths, ["path"]);
|
||||
assert_eq!(p.text, None);
|
||||
assert!(batch.complete(0, IMAGE, None).is_none());
|
||||
}
|
||||
|
||||
/// Text JSON preserves Unicode and escapes quotes, backslashes and newlines.
|
||||
#[test]
|
||||
fn encodes_json_text() {
|
||||
let p = DropPayload {
|
||||
text: Some("你好 \"\\\n".into()),
|
||||
paths: Vec::new(),
|
||||
..sample()
|
||||
};
|
||||
assert_eq!(encode_drop_json(&p), concat!(
|
||||
r#"{"display_index":17,"norm_x":0.25,"norm_y":0.75,"in_image":true,"#,
|
||||
r#""text":"你好 \"\\\n"}"#,
|
||||
));
|
||||
}
|
||||
|
||||
/// An example drop containing Unicode, delimiters and control characters.
|
||||
fn sample() -> DropPayload {
|
||||
DropPayload {
|
||||
display_index: 17,
|
||||
norm_x: 0.25,
|
||||
norm_y: 0.75,
|
||||
in_image: true,
|
||||
text: None,
|
||||
paths: vec![r"D:\Downloads\测试.pdf".into(), "\"\u{8}\u{c}\n\r\t\0\u{10}".into()],
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks UTF-8 preservation and each class of RFC 8259 escape.
|
||||
#[test]
|
||||
fn encodes_json_paths() {
|
||||
assert_eq!(encode_drop_json(&sample()), concat!(
|
||||
r#"{"display_index":17,"norm_x":0.25,"norm_y":0.75,"in_image":true,"paths":["#,
|
||||
r#""D:\\Downloads\\测试.pdf","\"\b\f\n\r\t\u0000\u0010"]}"#,
|
||||
));
|
||||
}
|
||||
|
||||
/// Only the literal loopback host, a numeric nonzero port and a safe path are accepted.
|
||||
#[test]
|
||||
fn validates_loopback_urls() {
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 42));
|
||||
assert_eq!(parse_loopback_drop_url("http://127.0.0.1:42"), Some((addr, "/v1/host-drop".into())));
|
||||
assert_eq!(parse_loopback_drop_url("http://127.0.0.1:42/drop?q=1"), Some((addr, "/drop?q=1".into())));
|
||||
for raw in [
|
||||
"https://127.0.0.1:42/drop", "http://localhost:42/drop", "http://127.0.0.2:42/drop",
|
||||
"http://[::1]:42/drop", "http://127.0.0.1:/drop", "http://127.0.0.1:0/drop",
|
||||
"http://127.0.0.1:65536/drop", "http://127.0.0.1:+42/drop", "http://127.0.0.1:42@evil/drop",
|
||||
"http://127.0.0.1:42/a b", "http://127.0.0.1:42/a\rheader", "http://127.0.0.1:42/a\nheader",
|
||||
" http://127.0.0.1:42", "http://127.0.0.1:42/drop\r\n",
|
||||
] {
|
||||
assert!(parse_loopback_drop_url(raw).is_none(), "{raw:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A real loopback peer receives the authenticated request and exact UTF-8 byte count.
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn posts_the_complete_drop_to_loopback() -> io::Result<()> {
|
||||
let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))?;
|
||||
listener.set_nonblocking(true)?;
|
||||
let payload = sample();
|
||||
post_loopback_drop(listener.local_addr()?, "/custom/drop", "test-token", &payload)?;
|
||||
let (mut stream, _) = listener.accept()?;
|
||||
stream.set_nonblocking(false)?;
|
||||
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
|
||||
let mut request = String::new();
|
||||
stream.read_to_string(&mut request)?;
|
||||
let (headers, body) = request.split_once("\r\n\r\n").expect("HTTP headers");
|
||||
assert_eq!(headers.lines().next(), Some("POST /custom/drop HTTP/1.1"));
|
||||
for field in ["Host: 127.0.0.1", "Authorization: Bearer test-token",
|
||||
"Content-Type: application/json", "Connection: close"] {
|
||||
assert!(headers.lines().any(|line| line == field), "{field}");
|
||||
}
|
||||
assert!(headers.lines().any(|line| line == format!("Content-Length: {}", body.len())));
|
||||
assert_eq!(body, encode_drop_json(&payload));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,8 @@ pub mod scroll;
|
||||
// The SDL3 window: Linux's and Windows's (`native/sdl_thread.rs`), and macOS's with the
|
||||
// `macos-sdl` feature, behind `REIMS_VGPU_WINDOW_IMPL`.
|
||||
#[cfg(any(target_os = "linux", target_os = "windows", feature = "macos-sdl"))]
|
||||
mod drop;
|
||||
#[cfg(any(target_os = "linux", target_os = "windows", feature = "macos-sdl"))]
|
||||
mod sdl;
|
||||
|
||||
pub use config::{
|
||||
|
||||
@@ -185,6 +185,7 @@ fn start_video() -> bool {
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
super::super::windows::install_unicode_input_hook();
|
||||
crate::drop::install_host_drop_forwarder();
|
||||
// SAFETY: SDL's video runs.
|
||||
let kind = unsafe { SDL_RegisterEvents(1) };
|
||||
WAKE.store(kind, Ordering::Release);
|
||||
|
||||
@@ -83,6 +83,8 @@ pub(crate) struct Shell {
|
||||
density: f64,
|
||||
/// Its input.
|
||||
pub(crate) input: Input,
|
||||
/// Files and coordinates supplied by SDL for the current drop.
|
||||
drop_batch: crate::drop::DropBatch,
|
||||
/// What its OS keeps of it.
|
||||
pub(crate) os: os::State,
|
||||
/// The guest's cursor, built for SDL.
|
||||
@@ -177,6 +179,7 @@ pub(crate) fn open(window: &Arc<Window>) {
|
||||
layout: Layout::default(),
|
||||
density: 1.0,
|
||||
input: opened.input,
|
||||
drop_batch: crate::drop::DropBatch::default(),
|
||||
os: opened.state,
|
||||
cursor: CursorCache::default(),
|
||||
over_image: false,
|
||||
@@ -204,6 +207,7 @@ pub(crate) fn open(window: &Arc<Window>) {
|
||||
pub(crate) fn close(id: u64) {
|
||||
let gone = with_shell(id, |shell| {
|
||||
ended(shell);
|
||||
shell.drop_batch.reset();
|
||||
shell.closed = true;
|
||||
os::close(shell) || shell.released
|
||||
});
|
||||
@@ -312,6 +316,14 @@ fn settled(before: Option<bool>, kind: u32) -> Option<bool> {
|
||||
pub(crate) fn event(event: &SDL_Event) {
|
||||
// SAFETY: every event starts with its type, and each arm reads the variant its type names.
|
||||
let kind = unsafe { event.r#type };
|
||||
let is_drop = [
|
||||
SDL_EVENT_DROP_BEGIN.0,
|
||||
SDL_EVENT_DROP_POSITION.0,
|
||||
SDL_EVENT_DROP_FILE.0,
|
||||
SDL_EVENT_DROP_TEXT.0,
|
||||
SDL_EVENT_DROP_COMPLETE.0,
|
||||
]
|
||||
.contains(&kind);
|
||||
let sdl_id = match kind {
|
||||
k if (SDL_EVENT_WINDOW_FIRST.0..=SDL_EVENT_WINDOW_LAST.0).contains(&k) => unsafe {
|
||||
event.window.windowID.0
|
||||
@@ -324,9 +336,20 @@ pub(crate) fn event(event: &SDL_Event) {
|
||||
event.button.windowID.0
|
||||
},
|
||||
k if k == SDL_EVENT_MOUSE_WHEEL.0 => unsafe { event.wheel.windowID.0 },
|
||||
_ if is_drop => unsafe { event.drop.windowID.0 },
|
||||
_ => return,
|
||||
};
|
||||
let Some(id) = window_of(sdl_id) else {
|
||||
let target = if is_drop && sdl_id == 0 {
|
||||
OPEN.with(|open| {
|
||||
let open = open.borrow();
|
||||
let mut live = open.iter().filter(|shell| !shell.closed);
|
||||
let first = live.next()?;
|
||||
live.next().is_none().then(|| first.window.id())
|
||||
})
|
||||
} else {
|
||||
window_of(sdl_id)
|
||||
};
|
||||
let Some(id) = target else {
|
||||
return;
|
||||
};
|
||||
with_shell(id, |shell| {
|
||||
@@ -390,6 +413,54 @@ impl Shell {
|
||||
self.refresh_cursor();
|
||||
false
|
||||
}
|
||||
k if k == SDL_EVENT_DROP_BEGIN.0 => {
|
||||
self.drop_batch.begin();
|
||||
false
|
||||
}
|
||||
k if k == SDL_EVENT_DROP_POSITION.0 => {
|
||||
// SAFETY: the event type selects the drop member.
|
||||
let (x, y) = unsafe { (event.drop.x, event.drop.y) };
|
||||
self.drop_batch.position(f64::from(x), f64::from(y));
|
||||
false
|
||||
}
|
||||
k if k == SDL_EVENT_DROP_FILE.0 => {
|
||||
// SAFETY: the event type selects the drop member.
|
||||
let drop = unsafe { event.drop };
|
||||
if !drop.data.is_null() {
|
||||
// SAFETY: SDL3 owns this NUL-terminated path for the event's lifetime.
|
||||
let path = unsafe { std::ffi::CStr::from_ptr(drop.data) }
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
self.drop_batch
|
||||
.file(path, Some((f64::from(drop.x), f64::from(drop.y))));
|
||||
}
|
||||
false
|
||||
}
|
||||
k if k == SDL_EVENT_DROP_TEXT.0 => {
|
||||
// SAFETY: the event type selects the drop member.
|
||||
let drop = unsafe { event.drop };
|
||||
if !drop.data.is_null() {
|
||||
// SAFETY: SDL3 owns this NUL-terminated text for the event's lifetime.
|
||||
let text = unsafe { std::ffi::CStr::from_ptr(drop.data) }
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
self.drop_batch
|
||||
.text(text, Some((f64::from(drop.x), f64::from(drop.y))));
|
||||
}
|
||||
false
|
||||
}
|
||||
k if k == SDL_EVENT_DROP_COMPLETE.0 => {
|
||||
// SAFETY: the event type selects the drop member.
|
||||
let drop = unsafe { event.drop };
|
||||
if let Some(payload) = self.drop_batch.complete(
|
||||
self.window.port(),
|
||||
self.layout.image,
|
||||
Some((f64::from(drop.x), f64::from(drop.y))),
|
||||
) {
|
||||
crate::drop::submit(payload);
|
||||
}
|
||||
false
|
||||
}
|
||||
_ => os::input_event(self, kind, event),
|
||||
};
|
||||
self.flush();
|
||||
|
||||
@@ -529,7 +529,7 @@ use reims_vgpu_vulkan::core::platform::os::clock::MonoTime;
|
||||
#[cfg(unix)]
|
||||
use reims_vgpu_vulkan::core::platform::resource::SurfaceHandle;
|
||||
use reims_vgpu_vulkan::core::platform::resource::{Buffer as _, MemoryFor};
|
||||
use reims_vgpu_vulkan::core::platform::types::NsRange;
|
||||
use reims_vgpu_vulkan::core::platform::types::{CommandBufferStatus, NsRange};
|
||||
use reims_vgpu_vulkan::core::platform::values::{PagesPlane, TextureDesc};
|
||||
use reims_vgpu_vulkan::core::platform::{Handle, Platform};
|
||||
use reims_vgpu_vulkan::core::raise::{OnFault, Raise, RaiseResult, refusals};
|
||||
@@ -8366,6 +8366,25 @@ impl<P: Platform> Caches<P> {
|
||||
pub(crate) fn export_unattached(
|
||||
&self,
|
||||
device: &P::Device,
|
||||
) -> Result<Vec<(u64, Vec<u8>)>, &'static str> {
|
||||
self.export_unattached_with(
|
||||
device,
|
||||
|queue| queue.command_buffer(ON),
|
||||
|cb| cb.commit(ON),
|
||||
|| device.wait_idle(),
|
||||
|cb| cb.wait_until_completed(ON),
|
||||
|buffer| device.read_standalone_buffer(buffer),
|
||||
)
|
||||
}
|
||||
|
||||
fn export_unattached_with(
|
||||
&self,
|
||||
device: &P::Device,
|
||||
mut command_buffer: impl FnMut(&P::CommandQueue) -> RaiseResult<Option<P::CommandBuffer>>,
|
||||
mut commit: impl FnMut(&P::CommandBuffer) -> RaiseResult<()>,
|
||||
mut wait_idle: impl FnMut(),
|
||||
mut wait_completed: impl FnMut(&P::CommandBuffer) -> RaiseResult<()>,
|
||||
mut read_buffer: impl FnMut(&P::Buffer) -> Result<Option<Vec<u8>>, &'static str>,
|
||||
) -> Result<Vec<(u64, Vec<u8>)>, &'static str> {
|
||||
let need_mem: Vec<P::Buffer> = {
|
||||
let state = self.lock();
|
||||
@@ -8373,17 +8392,14 @@ impl<P: Platform> Caches<P> {
|
||||
.by_block
|
||||
.values()
|
||||
.filter(|c| {
|
||||
c.pages.is_none()
|
||||
&& !c.device.memory_made()
|
||||
&& c.shapes.iter().any(|s| s.dirty)
|
||||
c.pages.is_none() && !c.device.memory_made() && c.shapes.iter().any(|s| s.dirty)
|
||||
})
|
||||
.map(|c| c.device.clone_ref())
|
||||
.collect()
|
||||
};
|
||||
self.make_memory(need_mem, MemoryFor::WriteBack);
|
||||
|
||||
let mut flushed_any = false;
|
||||
{
|
||||
let (dirty_blocks, queue) = {
|
||||
let mut state = self.lock();
|
||||
let dirty_blocks: Vec<u64> = state
|
||||
.by_block
|
||||
@@ -8391,45 +8407,85 @@ impl<P: Platform> Caches<P> {
|
||||
.filter(|(_, c)| c.pages.is_none() && c.shapes.iter().any(|s| s.dirty))
|
||||
.map(|(&b, _)| b)
|
||||
.collect();
|
||||
if !dirty_blocks.is_empty() {
|
||||
let queue = if dirty_blocks.is_empty() {
|
||||
None
|
||||
} else {
|
||||
if !state
|
||||
.make_transfer(device)
|
||||
.map_err(|_| "snapshot_save: surface cache transfer init failed")?
|
||||
{
|
||||
return Err("snapshot_save: surface cache transfer queue unavailable");
|
||||
}
|
||||
state
|
||||
.transfer
|
||||
.as_ref()
|
||||
.map(|transfer| transfer.queue.clone_ref())
|
||||
};
|
||||
(dirty_blocks, queue)
|
||||
};
|
||||
if let Some(queue) = queue {
|
||||
let mut submitted = Vec::new();
|
||||
let flushed = (|| {
|
||||
for block in dirty_blocks {
|
||||
let cb_opt = {
|
||||
let transfer = state
|
||||
.transfer
|
||||
.as_mut()
|
||||
.ok_or("snapshot_save: surface cache transfer missing")?;
|
||||
transfer
|
||||
.queue
|
||||
.command_buffer(ON)
|
||||
.map_err(|_| "snapshot_save: surface cache command buffer failed")?
|
||||
};
|
||||
let Some(cb) = cb_opt else {
|
||||
return Err("snapshot_save: surface cache command buffer unavailable");
|
||||
};
|
||||
let Some(cache) = state.by_block.get_mut(&block) else {
|
||||
let cb = command_buffer(&queue)
|
||||
.map_err(|_| "snapshot_save: surface cache command buffer failed")?
|
||||
.ok_or("snapshot_save: surface cache command buffer unavailable")?;
|
||||
let mut state = self.lock();
|
||||
let Some(cache) = state.by_block.get_mut(&block).filter(|cache| {
|
||||
cache.pages.is_none() && cache.shapes.iter().any(|s| s.dirty)
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
if !cache.copy_through(MemoryFor::WriteBack) {
|
||||
return Err("snapshot_save: deferred surface cache allocation failed");
|
||||
}
|
||||
let back = shapes::write_back::<P>(&cb, &cache.device, &cache.shapes, |s| {
|
||||
s.dirty
|
||||
})
|
||||
.map_err(|_| "snapshot_save: surface cache shape write_back failed")?;
|
||||
cache.wrote_shapes(&back);
|
||||
state.owed_commits.push(cb);
|
||||
flushed_any = true;
|
||||
let back =
|
||||
shapes::write_back::<P>(&cb, &cache.device, &cache.shapes, |s| s.dirty)
|
||||
.map_err(|_| "snapshot_save: surface cache shape write_back failed")?;
|
||||
if back.is_empty() {
|
||||
return Err("snapshot_save: surface cache blit encoder unavailable");
|
||||
}
|
||||
// Retirement frees the queue slot even while we keep the handle for status.
|
||||
let commit_failed = "snapshot_save: surface cache command buffer commit failed";
|
||||
state.unlocked(|| commit(&cb)).map_err(|_| commit_failed)?;
|
||||
let status = cb.status();
|
||||
if status.raw() < CommandBufferStatus::COMMITTED.raw()
|
||||
|| status == CommandBufferStatus::ERROR
|
||||
{
|
||||
return Err(commit_failed);
|
||||
}
|
||||
drop(state);
|
||||
submitted.push((block, back, cb));
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
let mut wait_failed = false;
|
||||
if !submitted.is_empty() {
|
||||
wait_idle();
|
||||
for (_, _, cb) in &submitted {
|
||||
if wait_completed(cb).is_err() {
|
||||
wait_failed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
flushed?;
|
||||
if wait_failed
|
||||
|| submitted
|
||||
.iter()
|
||||
.any(|(_, _, cb)| cb.status() != CommandBufferStatus::COMPLETED)
|
||||
{
|
||||
return Err(
|
||||
"snapshot_save: surface cache command buffer did not complete successfully",
|
||||
);
|
||||
}
|
||||
let mut state = self.lock();
|
||||
let state = &mut *state;
|
||||
for (block, back, _) in &submitted {
|
||||
if let Some(cache) = state.by_block.get_mut(block) {
|
||||
cache.wrote_shapes(back);
|
||||
cache.shapes.written_back(back, &mut state.counts.shapes);
|
||||
}
|
||||
}
|
||||
}
|
||||
if flushed_any {
|
||||
device.wait_idle();
|
||||
}
|
||||
|
||||
let mut to_read: Vec<(u64, P::Buffer)> = {
|
||||
@@ -8445,7 +8501,7 @@ impl<P: Platform> Caches<P> {
|
||||
|
||||
let mut out = Vec::with_capacity(to_read.len());
|
||||
for (block, buf) in to_read {
|
||||
match device.read_standalone_buffer(&buf)? {
|
||||
match read_buffer(&buf)? {
|
||||
Some(bytes) => out.push((block, bytes)),
|
||||
None => return Err("snapshot_save: unattached surface cache buffer unreadable"),
|
||||
}
|
||||
@@ -16385,6 +16441,325 @@ pub(super) mod tests {
|
||||
r.pages_flagged(block, 0, &[], length, flags)
|
||||
}
|
||||
|
||||
const SNAPSHOT_CACHE_LENGTH: u64 = 0x1000;
|
||||
|
||||
fn snapshot_rig(blocks: u64) -> Rig {
|
||||
let r = rig(8);
|
||||
r.dec.set_deferred_budget(blocks * SNAPSHOT_CACHE_LENGTH);
|
||||
r.dec.caches().shaped = true;
|
||||
r
|
||||
}
|
||||
|
||||
fn dirty_unattached_cache(r: &mut Rig, block: u64) -> reims_vgpu_vulkan::core::platform::ObjId {
|
||||
assert_eq!(defer(r, block, SNAPSHOT_CACHE_LENGTH), RGFX_STATUS_OK);
|
||||
let key = ShapeKey {
|
||||
plane: 0,
|
||||
offset: 128,
|
||||
bytes_per_row: 128,
|
||||
width: 16,
|
||||
height: 2,
|
||||
texel_bytes: 4,
|
||||
storage: false,
|
||||
};
|
||||
let desc = r.p.texture_descriptor(&TextureDesc {
|
||||
pixel_format: 80,
|
||||
width: key.width,
|
||||
height: key.height,
|
||||
..TextureDesc::default()
|
||||
});
|
||||
let image = r.device.new_texture(ON, &desc).unwrap().unwrap();
|
||||
let id = image.id();
|
||||
let mut state = r.dec.caches();
|
||||
let cache = state.by_block.get_mut(&block).unwrap();
|
||||
assert!(cache.pages.is_none());
|
||||
assert!(!cache.device.memory_made());
|
||||
let (reference, _) = cache.shapes.insert(key, image, false, 0);
|
||||
assert!(cache.shapes.mark_dirty(reference.id()));
|
||||
id
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_exports_more_dirty_unattached_caches_than_the_transfer_queue_holds() {
|
||||
use reims_vgpu_vulkan::core::platform::types::MtlSize;
|
||||
|
||||
const BLOCKS: u64 = 80;
|
||||
const CAPACITY: usize = 64;
|
||||
let mut r = snapshot_rig(BLOCKS + 1);
|
||||
let mut textures = HashMap::default();
|
||||
let mut expected = Vec::new();
|
||||
for i in 0..BLOCKS {
|
||||
let block = BLOCK + i * 0x2000;
|
||||
let texture = dirty_unattached_cache(&mut r, block);
|
||||
let texels = [[i as u8; 64], [255 - i as u8; 64]];
|
||||
let mut bytes = vec![0; SNAPSHOT_CACHE_LENGTH.to_usize()];
|
||||
for (row, texels) in bytes[128..].chunks_mut(128).zip(&texels) {
|
||||
row[..64].copy_from_slice(texels);
|
||||
}
|
||||
textures.insert(texture, texels);
|
||||
expected.push((block, bytes));
|
||||
}
|
||||
assert_eq!(
|
||||
defer(&mut r, BLOCK + BLOCKS * 0x2000, SNAPSHOT_CACHE_LENGTH),
|
||||
RGFX_STATUS_OK
|
||||
);
|
||||
|
||||
let mark = r.p.call_log().mark();
|
||||
let world = r.p.world();
|
||||
let mut acquired = 0;
|
||||
let retired = Cell::new(0);
|
||||
let caches = &r.dec.surface_caches;
|
||||
let exported = caches.export_unattached_with(
|
||||
&r.device,
|
||||
|queue| {
|
||||
assert!(
|
||||
caches.try_lock().is_some(),
|
||||
"queue acquisition holds the cache lock"
|
||||
);
|
||||
let in_flight = world.committed().len();
|
||||
assert_eq!(
|
||||
world.live("MTLCommandBuffer").len(),
|
||||
in_flight + retired.get(),
|
||||
"a previous buffer is uncommitted"
|
||||
);
|
||||
if in_flight == CAPACITY {
|
||||
retired.set(retired.get() + world.complete_all(CompleteOn::Caller));
|
||||
}
|
||||
assert!(world.committed().len() < CAPACITY);
|
||||
acquired += 1;
|
||||
queue.command_buffer(ON)
|
||||
},
|
||||
|cb| cb.commit(ON),
|
||||
|| {
|
||||
assert_eq!(caches.try_lock().unwrap().counts.shapes.written_back, 0);
|
||||
retired.set(retired.get() + world.complete_all(CompleteOn::Caller));
|
||||
},
|
||||
|cb| cb.wait_until_completed(ON),
|
||||
|buffer| {
|
||||
assert!(world.live("MTLCommandBuffer").is_empty());
|
||||
// The fake logs blits without executing them. Reproduce each logged GPU copy.
|
||||
let calls = r.p.call_log().since(mark);
|
||||
let mut copies = calls.iter().filter(|call| {
|
||||
call.sel.starts_with("copyFromTexture:")
|
||||
&& call.args[5].as_obj() == Some(buffer.id())
|
||||
});
|
||||
let copy = copies.next().expect("a copy into this cache");
|
||||
assert!(copies.next().is_none());
|
||||
assert_eq!(copy.args[4], Arg::val(&MtlSize::new(16, 2, 1)));
|
||||
let source = &textures[©.args[0].as_obj().unwrap()];
|
||||
let offset = copy.args[6].as_u64().unwrap().to_usize();
|
||||
let pitch = copy.args[7].as_u64().unwrap().to_usize();
|
||||
let mut bytes = vec![0; buffer.length().to_usize()];
|
||||
for (row, texels) in source.iter().enumerate() {
|
||||
let at = offset + row * pitch;
|
||||
bytes[at..at + 64].copy_from_slice(texels);
|
||||
}
|
||||
Ok(Some(bytes))
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(acquired, BLOCKS);
|
||||
assert_eq!(retired.get(), BLOCKS.to_usize());
|
||||
assert_eq!(exported.unwrap(), expected);
|
||||
let state = r.dec.caches();
|
||||
assert_eq!(state.counts.shapes.written_back, BLOCKS);
|
||||
assert!(
|
||||
state
|
||||
.by_block
|
||||
.values()
|
||||
.all(|cache| cache.shapes.iter().all(|s| !s.dirty))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_drops_uncommitted_unattached_writebacks_on_error() {
|
||||
use reims_vgpu_vulkan::core::testkit::Step;
|
||||
use reims_vgpu_vulkan::core::testkit::impls::resource::MAKE_MEMORY;
|
||||
|
||||
for (selector, steps, error) in [
|
||||
(
|
||||
"commandBuffer",
|
||||
vec![Step::Nil],
|
||||
"snapshot_save: surface cache command buffer unavailable",
|
||||
),
|
||||
(
|
||||
MAKE_MEMORY,
|
||||
vec![Step::value(false); 2],
|
||||
"snapshot_save: deferred surface cache allocation failed",
|
||||
),
|
||||
(
|
||||
"blitCommandEncoder",
|
||||
vec![Step::Nil],
|
||||
"snapshot_save: surface cache blit encoder unavailable",
|
||||
),
|
||||
(
|
||||
"endEncoding",
|
||||
vec![Step::unrecognized("endEncoding")],
|
||||
"snapshot_save: surface cache shape write_back failed",
|
||||
),
|
||||
(
|
||||
"commit",
|
||||
vec![Step::unrecognized("commit")],
|
||||
"snapshot_save: surface cache command buffer commit failed",
|
||||
),
|
||||
] {
|
||||
let mut r = snapshot_rig(1);
|
||||
dirty_unattached_cache(&mut r, BLOCK);
|
||||
for step in steps {
|
||||
r.p.script().push(selector, step);
|
||||
}
|
||||
let caches = &r.dec.surface_caches;
|
||||
assert_eq!(caches.export_unattached(&r.device), Err(error));
|
||||
assert!(r.p.world().live("MTLCommandBuffer").is_empty());
|
||||
assert!(
|
||||
r.dec.caches().by_block[&BLOCK]
|
||||
.shapes
|
||||
.iter()
|
||||
.all(|s| s.dirty)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_stops_before_readback_if_a_later_writeback_fails() {
|
||||
let mut r = snapshot_rig(2);
|
||||
dirty_unattached_cache(&mut r, BLOCK);
|
||||
dirty_unattached_cache(&mut r, BLOCK + 0x2000);
|
||||
r.p.faults()
|
||||
.at("MTLCommandQueue", "commandBuffer", 1, Fault::Nil);
|
||||
|
||||
let caches = &r.dec.surface_caches;
|
||||
let world = r.p.world();
|
||||
let mut retired = 0;
|
||||
let exported = caches.export_unattached_with(
|
||||
&r.device,
|
||||
|queue| queue.command_buffer(ON),
|
||||
|cb| cb.commit(ON),
|
||||
|| retired += world.complete_all(CompleteOn::Caller),
|
||||
|cb| cb.wait_until_completed(ON),
|
||||
|_| panic!("a failed writeback must stop the snapshot before readback"),
|
||||
);
|
||||
assert_eq!(
|
||||
exported,
|
||||
Err("snapshot_save: surface cache command buffer unavailable")
|
||||
);
|
||||
assert_eq!(retired, 1);
|
||||
assert!(world.live("MTLCommandBuffer").is_empty());
|
||||
let state = r.dec.caches();
|
||||
assert_eq!(state.counts.shapes.written_back, 0);
|
||||
assert_eq!(
|
||||
state
|
||||
.by_block
|
||||
.values()
|
||||
.filter(|c| c.shapes.iter().any(|s| s.dirty))
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_preserves_dirty_shapes_if_writeback_commit_is_silently_refused() {
|
||||
let mut r = snapshot_rig(1);
|
||||
dirty_unattached_cache(&mut r, BLOCK);
|
||||
|
||||
let exported = r.dec.surface_caches.export_unattached_with(
|
||||
&r.device,
|
||||
|queue| queue.command_buffer(ON),
|
||||
|_| Ok(()),
|
||||
|| panic!("a refused commit leaves no submitted work to wait for"),
|
||||
|_| panic!("a refused commit leaves no submitted work to wait for"),
|
||||
|_| panic!("a refused commit must stop the snapshot before readback"),
|
||||
);
|
||||
assert_eq!(
|
||||
exported,
|
||||
Err("snapshot_save: surface cache command buffer commit failed")
|
||||
);
|
||||
assert!(r.p.world().live("MTLCommandBuffer").is_empty());
|
||||
let state = r.dec.caches();
|
||||
assert_eq!(state.counts.shapes.written_back, 0);
|
||||
assert!(state.by_block[&BLOCK].shapes.iter().all(|s| s.dirty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_preserves_dirty_shapes_if_a_submitted_writeback_fails() {
|
||||
let mut r = snapshot_rig(2);
|
||||
dirty_unattached_cache(&mut r, BLOCK);
|
||||
dirty_unattached_cache(&mut r, BLOCK + 0x2000);
|
||||
|
||||
let world = r.p.world();
|
||||
let exported = r.dec.surface_caches.export_unattached_with(
|
||||
&r.device,
|
||||
|queue| queue.command_buffer(ON),
|
||||
|cb| cb.commit(ON),
|
||||
|| {
|
||||
let [first, second] = world.committed().try_into().unwrap();
|
||||
assert!(world.complete(
|
||||
first,
|
||||
CommandBufferStatus::COMPLETED,
|
||||
None,
|
||||
CompleteOn::Caller
|
||||
));
|
||||
assert!(world.complete(
|
||||
second,
|
||||
CommandBufferStatus::ERROR,
|
||||
None,
|
||||
CompleteOn::Caller
|
||||
));
|
||||
},
|
||||
|cb| cb.wait_until_completed(ON),
|
||||
|_| panic!("a failed writeback must stop the snapshot before readback"),
|
||||
);
|
||||
assert_eq!(
|
||||
exported,
|
||||
Err("snapshot_save: surface cache command buffer did not complete successfully")
|
||||
);
|
||||
assert!(world.live("MTLCommandBuffer").is_empty());
|
||||
let state = r.dec.caches();
|
||||
assert_eq!(state.counts.shapes.written_back, 0);
|
||||
assert!(
|
||||
state
|
||||
.by_block
|
||||
.values()
|
||||
.all(|cache| cache.shapes.iter().all(|s| s.dirty))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_waits_for_each_submitted_writeback_status_after_wait_idle() {
|
||||
let mut r = snapshot_rig(1);
|
||||
dirty_unattached_cache(&mut r, BLOCK);
|
||||
|
||||
let world = r.p.world();
|
||||
let mut waited_completed = 0;
|
||||
let exported = r.dec.surface_caches.export_unattached_with(
|
||||
&r.device,
|
||||
|queue| queue.command_buffer(ON),
|
||||
|cb| cb.commit(ON),
|
||||
|| {
|
||||
// Simulate wait_idle returning before the completion worker has
|
||||
// published the command buffer's final COMPLETED status.
|
||||
assert_eq!(world.committed().len(), 1);
|
||||
},
|
||||
|cb| {
|
||||
waited_completed += 1;
|
||||
assert_eq!(cb.status(), CommandBufferStatus::SCHEDULED);
|
||||
assert_eq!(world.complete_all(CompleteOn::Caller), 1);
|
||||
cb.wait_until_completed(ON)
|
||||
},
|
||||
|buffer| {
|
||||
assert!(world.live("MTLCommandBuffer").is_empty());
|
||||
Ok(Some(vec![0xAB; buffer.length().to_usize()]))
|
||||
},
|
||||
);
|
||||
assert_eq!(waited_completed, 1);
|
||||
assert_eq!(
|
||||
exported,
|
||||
Ok(vec![(BLOCK, vec![0xAB; SNAPSHOT_CACHE_LENGTH.to_usize()])])
|
||||
);
|
||||
let state = r.dec.caches();
|
||||
assert_eq!(state.counts.shapes.written_back, 1);
|
||||
assert!(state.by_block[&BLOCK].shapes.iter().all(|s| !s.dirty));
|
||||
}
|
||||
|
||||
/// A `SURFACE_PAGES` naming the pages of the deferred block at `block`, `runs` as
|
||||
/// [`Rig::pages`]'s, from context `context`; its answer.
|
||||
fn attach(r: &mut Rig, block: u64, context: u32, runs: &[(u64, u64)], length: u64) -> u32 {
|
||||
|
||||
@@ -23,9 +23,9 @@
|
||||
* moved the cursor yet: the latest is where the host's pointer is.
|
||||
*
|
||||
* Where the point lies, and the rectangles the host is told:
|
||||
* - on x86-64, each framebuffer holds its display's rectangle as WindowServer placed it
|
||||
* (getBoundingRect), and a move of the cursor on any display tells the host each display's
|
||||
* that changed (tellBounds);
|
||||
* - on x86-64, each framebuffer holds its display's virtual desktop rectangle as WindowServer
|
||||
* placed it (getBoundingRect), and a move of the cursor on any display tells the host each
|
||||
* virtual rectangle that changed (tellBounds);
|
||||
* - on arm64, WindowServer tells the displays nothing of where it placed them, so the kext
|
||||
* learns it from its own posts: a crossing posts at the display's pixel of the rectangle held
|
||||
* for it, and again beside the other displays where the cursor did not reach it, at most
|
||||
@@ -185,7 +185,7 @@ void ReimsGraphics::movePointer(thread_call_param_t self, thread_call_param_t)
|
||||
IOSimpleLockUnlock(me->interruptLock);
|
||||
if (!me->hasStarted())
|
||||
return;
|
||||
// The display's mode and its rectangle in the global space.
|
||||
// The display's scanout size and its virtual desktop rectangle.
|
||||
ReimsGraphics *fb = me->copyDisplay(me->drivenIndex(at.display));
|
||||
if (!fb)
|
||||
return;
|
||||
@@ -221,7 +221,7 @@ void ReimsGraphics::movePointer(thread_call_param_t self, thread_call_param_t)
|
||||
move == RgfxPointerMove::moved ? "moves" : "is dragged", globalX, globalY, posted);
|
||||
}
|
||||
|
||||
// Each framebuffer holds its display's rectangle as WindowServer placed it (getBoundingRect).
|
||||
// The virtual rectangles used for both IOHIDSystem posts and DISPLAY_BOUNDS.
|
||||
void ReimsGraphics::displayPlaces(RgfxGlobalRect *rects, bool *placed)
|
||||
{
|
||||
ReimsGraphics *fbs[RGFX_DISPLAYS_MAX];
|
||||
@@ -232,7 +232,7 @@ void ReimsGraphics::displayPlaces(RgfxGlobalRect *rects, bool *placed)
|
||||
fbs[i]->getBoundingRect(&bounds);
|
||||
if (!bounds || display >= RGFX_DISPLAYS_MAX)
|
||||
continue;
|
||||
rects[display] = {bounds->minx, bounds->miny, bounds->maxx, bounds->maxy};
|
||||
rects[display] = rgfxFramebufferDesktopBounds(bounds);
|
||||
placed[display] = true;
|
||||
}
|
||||
releaseDisplays(fbs, n);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// RgfxDisplayBounds: which displays' rectangles the kext tells the host in DISPLAY_BOUNDS
|
||||
// (design.md, "Multiple displays", "A drag across displays"). On x86-64 each framebuffer holds its
|
||||
// display's rectangle in WindowServer's global space as WindowServer placed it (IOFBSetBounds,
|
||||
// which IOFramebuffer::getBoundingRect reads; RgfxPointerOver.hpp), and on arm64 the kext holds
|
||||
// display's virtual desktop rectangle as WindowServer placed it (IOFBSetBounds, which
|
||||
// IOFramebuffer::getBoundingRect reads; RgfxPointerOver.hpp), and on arm64 the kext holds
|
||||
// each one a landing of its own moves of the cursor confirmed (RgfxDisplayPlaces.hpp); the host
|
||||
// carries its captured pointer past one display's edge onto the display whose rectangle meets it
|
||||
// there. Each move of the cursor, on any display, tells the host every display's rectangle that
|
||||
@@ -21,6 +21,15 @@
|
||||
#include "RgfxPointerOver.hpp"
|
||||
#include "reims_graphics_wire.h"
|
||||
|
||||
// IOFramebuffer's getBoundingRect returns its physical and virtual rectangles in order.
|
||||
// IOFBSetBounds supplies both, or IOFramebuffer uses the sole rectangle for both.
|
||||
template <class Bounds>
|
||||
inline RgfxGlobalRect rgfxFramebufferDesktopBounds(const Bounds *bounds)
|
||||
{
|
||||
const Bounds &rect = bounds[1];
|
||||
return {rect.minx, rect.miny, rect.maxx, rect.maxy};
|
||||
}
|
||||
|
||||
// The rectangle the host was last told of each display, by id, where it was told one.
|
||||
struct RgfxBoundsTold {
|
||||
RgfxGlobalRect rects[RGFX_DISPLAYS_MAX];
|
||||
|
||||
@@ -4,16 +4,12 @@
|
||||
// the display its cursor is on, so the kext moves the cursor onto that display, at that point,
|
||||
// before the tablet's next position comes (ReimsGraphicsPointer.cpp).
|
||||
//
|
||||
// The point is in WindowServer's global space, in which it placed each display: on x86-64 each
|
||||
// framebuffer holds its display's rectangle there as WindowServer gave it (IOFBSetBounds, which
|
||||
// IOFramebuffer::getBoundingRect reads), the space the cursor's moves arrive in
|
||||
// (IOFramebuffer::extSetCursorPosition); on arm64 the kext learns each one from its own moves
|
||||
// (RgfxDisplayPlaces.hpp). The display's pixel lies in that rectangle as the pixel
|
||||
// lies in the display's mode, scaled from the mode's pixels to the rectangle's size. Measured on
|
||||
// x86-64 macOS 11.7.11, 15.8.2 and 26.7.2 with two 1920 x 1080 displays side by side: each
|
||||
// framebuffer's rectangle is the display's CGDisplayBounds, and IOHIDSystem's mouse-moved posted
|
||||
// at a point of display 1's rectangle puts the cursor there (lane ptrcross, potluck jobs
|
||||
// m3-max-34583 to 34585).
|
||||
// IOHIDSystem's post takes a point in WindowServer's virtual desktop. On x86-64 the framebuffer
|
||||
// holds the virtual rectangle WindowServer gave it (IOFBSetBounds); on arm64 the kext learns
|
||||
// each rectangle from its own moves (RgfxDisplayPlaces.hpp). Scale the scanout pixels into that
|
||||
// rectangle. Measured on x86-64 macOS 11.7.11, 15.8.2 and 26.7.2 with two 1920 x 1080 displays
|
||||
// side by side: a mouse-moved posted at a point in display 1's CGDisplayBounds puts the cursor
|
||||
// there (lane ptrcross, potluck jobs m3-max-34583 to 34585).
|
||||
//
|
||||
// The move is a mouse-moved where no button is held, and the drag of the button held where one is,
|
||||
// as IOHIDSystem's own moves are (the left button's before the right's, the right's before any
|
||||
|
||||
@@ -19,10 +19,38 @@ void check(bool ok, const char *what)
|
||||
std::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
void mixedScaleDesktop()
|
||||
{
|
||||
// IOFramebuffer keeps the physical and virtual desktop rectangles, in that order.
|
||||
const RgfxGlobalRect framebuffers[2][2] = {
|
||||
{{0, 0, 3840, 2160}, {0, 0, 1920, 1080}},
|
||||
{{3840, 0, 6400, 1440}, {1920, 0, 4480, 1440}},
|
||||
};
|
||||
const RgfxGlobalRect left = rgfxFramebufferDesktopBounds(framebuffers[0]);
|
||||
const RgfxGlobalRect right = rgfxFramebufferDesktopBounds(framebuffers[1]);
|
||||
int32_t x = 0, y = 0;
|
||||
check(rgfxPointerGlobal(right, 2560, 1440, 2, 653, &x, &y) && x == 1922 && y == 653,
|
||||
"crossing onto the native display uses its virtual origin");
|
||||
check(rgfxPointerGlobal(left, 3840, 2160, 3834, 943, &x, &y) && x == 1917 && y == 471,
|
||||
"crossing back scales scanout pixels into the HiDPI desktop rectangle");
|
||||
|
||||
// Both displays were native before the switch. Their physical rectangles stay the same.
|
||||
RgfxBoundsTold told = {};
|
||||
rgfxBoundsWereTold(&told, 0, framebuffers[0][0]);
|
||||
rgfxBoundsWereTold(&told, 1, framebuffers[1][0]);
|
||||
check(rgfxBoundsToTell(told, 0, left) && rgfxBoundsToTell(told, 1, right),
|
||||
"a HiDPI switch reports the resized display and the moved neighbor");
|
||||
const RgfxDisplayBounds command = rgfxBoundsCommand(1, right);
|
||||
check(command.min_x == 1920 && command.max_x == 4480 && command.max_y == 1440,
|
||||
"DISPLAY_BOUNDS uses the same desktop rectangle as the pointer post");
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
mixedScaleDesktop();
|
||||
|
||||
// The wire's command: 40 bytes, the display then the rectangle past the 16-byte header.
|
||||
check(sizeof(RgfxDisplayBounds) == 40 && RGFX_CMD_DISPLAY_BOUNDS == 9, "the wire's");
|
||||
check(offsetof(RgfxDisplayBounds, display) == 16 && offsetof(RgfxDisplayBounds, min_x) == 20 &&
|
||||
|
||||
Binary file not shown.
@@ -34,4 +34,4 @@ Arch = "arm64e"
|
||||
MinKernel = "23.0.0"
|
||||
MaxKernel = ""
|
||||
Comment = "Installs the reims-graphics Metal bundle and admits it"
|
||||
sha256 = "deb1696453b7d754547abc24e3fa30e5affea059bd19d2d732bee243054a300e"
|
||||
sha256 = "969de78746515a49078709af17268af29ee398262dd45911e897c8ce2e806792"
|
||||
@@ -331,7 +331,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
|
||||
"guest/kext/src/ReimsGraphics.cpp" = "7ea4b22d26781eb7f673968cf77e33b65cd09042f4a949f600d27d1f9024ebec"
|
||||
"guest/kext/src/ReimsGraphics.hpp" = "e4162466ced71dd89ca50a38dcdf26c874765aab471bd96375fcb99f0766f20d"
|
||||
"guest/kext/src/ReimsGraphicsMobile.cpp" = "b73a2e5f5b061453817c5d0b18211a2d0782f5971f02d90b0fb7f930365086de"
|
||||
"guest/kext/src/ReimsGraphicsPointer.cpp" = "255f049c3a5244a148d80fd25ef3388001ba180c58901e3620451c3158908f0e"
|
||||
"guest/kext/src/ReimsGraphicsPointer.cpp" = "7b3482545b8e5e459327ab31648e32d83fd8317587b453b4133a5974fa44e35d"
|
||||
"guest/kext/src/RgfxAccelTypes.hpp" = "c65e032a617cda503b2534c68bec87947d7856accda676f35a1affa145998259"
|
||||
"guest/kext/src/RgfxAccelerator.cpp" = "319e1148d2644e922ed2c30859019392764c9e64328594c1f593c5c4fe890030"
|
||||
"guest/kext/src/RgfxAccelerator.hpp" = "2711b9225040feae3e45bb8057a60b30f5d17d83d953eadc82c2db91e83e28c5"
|
||||
@@ -359,7 +359,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
|
||||
"guest/kext/src/RgfxDeviceControl.cpp" = "53c7c6a722ef4d7edeb5756eb04091d4a56f397dc5aef83c3637b1c0f129b934"
|
||||
"guest/kext/src/RgfxDeviceControl.hpp" = "c1357b80ee2141e1e2fd57213f3c9361cb497b8c6490a0b6aff8c64649be48c6"
|
||||
"guest/kext/src/RgfxDeviceName.hpp" = "b242e0ccdce31c3c454bc3a4d64b13c30e574b25379a0833973dcecbbb1146d3"
|
||||
"guest/kext/src/RgfxDisplayBounds.hpp" = "c1e8fe52f89bcb25ee178f4e0ea4ac53396109fd934348408692d21d1931ecf7"
|
||||
"guest/kext/src/RgfxDisplayBounds.hpp" = "7aafbc6d1c2bb28e50c973f77d21c1aa00b322fb5fc934d4b1238b50f3aa89db"
|
||||
"guest/kext/src/RgfxDisplayIdentity.hpp" = "ce4328b8e255f942aea0f0dc097e2e80eb4a8d7e126ea0f342fd116252357731"
|
||||
"guest/kext/src/RgfxDisplayModes.hpp" = "62026ac6fa3febe5ce403fbfe026760f0434b70cc47e5d74c191fa5509ae12cd"
|
||||
"guest/kext/src/RgfxDisplayPipeUserClient.cpp" = "460c7d61a305d7d145b3318bb4fbe940c0d2d48d63afbbfeb6f273cd929aa3af"
|
||||
@@ -397,7 +397,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
|
||||
"guest/kext/src/RgfxPointerDevice.cpp" = "a4f88cc9b272259c3a85325b2295feea6a22221f52035fc5130d72f52cb88891"
|
||||
"guest/kext/src/RgfxPointerDevice.hpp" = "a393c90bed65528495868778e4130851e98aeafcb11401aef05d2d41d5b90d3f"
|
||||
"guest/kext/src/RgfxPointerMotion.hpp" = "d5cbe1a09db996980319d0b907782675fa82b5a03fd84a51f7c7d12c5dada926"
|
||||
"guest/kext/src/RgfxPointerOver.hpp" = "c2c38dbd101b1f59400bb159bd8cb44ed8c937bf25b93e9d62a03d6c2fd9ae50"
|
||||
"guest/kext/src/RgfxPointerOver.hpp" = "757946b2332ba278201f4c2f44ec1ee2bb21ca10b017a7c7933f696d8ee8f10c"
|
||||
"guest/kext/src/RgfxPointerReporting.cpp" = "c9f33023f3acea2e638353e8943c65f28f8befa984989ae88e7abc24858b961e"
|
||||
"guest/kext/src/RgfxPoolBlocks.hpp" = "a657b67922b04b75ccef6f12e10d775867f4037e50b89a8cf0d4972af43747fe"
|
||||
"guest/kext/src/RgfxQueueLimits.hpp" = "13f8ecd60e8d19f438b8ddc1cf3a0273fba1028bc049110776b637fa2097173c"
|
||||
@@ -466,5 +466,5 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
|
||||
"ReimsGraphics.kext/Contents/Info.plist" = "9683153587659c4bd4d5c52167eff1f3d2ae51dae575f60c15a27d89240f46c5"
|
||||
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "33a086b90fa116b3cf0c6bb826c27f8a55cd83f15522ee794e20186d469bdbc7"
|
||||
"RgfxGate.kext/Contents/Info.plist" = "7b78d915fab4d36e6cdb3f40aa2a6c1e7224f30158ee879af23451d2e6969992"
|
||||
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "deb1696453b7d754547abc24e3fa30e5affea059bd19d2d732bee243054a300e"
|
||||
"set.toml" = "a4da2409f25dd7bf12260de752c38c474b60d4b2d993810a44de0f4b07cb6dfd"
|
||||
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "969de78746515a49078709af17268af29ee398262dd45911e897c8ce2e806792"
|
||||
"set.toml" = "934935a19dea7d19f09c411552120e3290f2f534bf12d97c8b4900e140aa4140"
|
||||
Binary file not shown.
Binary file not shown.
@@ -24,7 +24,7 @@ Arch = "x86_64"
|
||||
MinKernel = "20.0.0"
|
||||
MaxKernel = ""
|
||||
Comment = "The reims-graphics display, accelerator and device control"
|
||||
sha256 = "d0277f202173dcecc35bce8aa2ec84cd9d53759a0fd34c26e913bcd65a191d50"
|
||||
sha256 = "2f15b6a13b44e98d4af81240c44720c0004f3c7d5c9dfecfde3b39f069930349"
|
||||
|
||||
[[kext]]
|
||||
BundlePath = "RgfxGate.kext"
|
||||
@@ -34,4 +34,4 @@ Arch = "x86_64"
|
||||
MinKernel = "20.0.0"
|
||||
MaxKernel = ""
|
||||
Comment = "Installs the reims-graphics Metal bundle and admits it"
|
||||
sha256 = "90d8327eb2243b820dd90ce29e4be79a80516f3e6341137b76e9b575ea3d10eb"
|
||||
sha256 = "534ab7e2f0b39ce9f6403b8988e89419889893b68ea91687b5aaeff38f5a9be6"
|
||||
@@ -331,7 +331,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
|
||||
"guest/kext/src/ReimsGraphics.cpp" = "7ea4b22d26781eb7f673968cf77e33b65cd09042f4a949f600d27d1f9024ebec"
|
||||
"guest/kext/src/ReimsGraphics.hpp" = "e4162466ced71dd89ca50a38dcdf26c874765aab471bd96375fcb99f0766f20d"
|
||||
"guest/kext/src/ReimsGraphicsMobile.cpp" = "b73a2e5f5b061453817c5d0b18211a2d0782f5971f02d90b0fb7f930365086de"
|
||||
"guest/kext/src/ReimsGraphicsPointer.cpp" = "255f049c3a5244a148d80fd25ef3388001ba180c58901e3620451c3158908f0e"
|
||||
"guest/kext/src/ReimsGraphicsPointer.cpp" = "7b3482545b8e5e459327ab31648e32d83fd8317587b453b4133a5974fa44e35d"
|
||||
"guest/kext/src/RgfxAccelTypes.hpp" = "c65e032a617cda503b2534c68bec87947d7856accda676f35a1affa145998259"
|
||||
"guest/kext/src/RgfxAccelerator.cpp" = "319e1148d2644e922ed2c30859019392764c9e64328594c1f593c5c4fe890030"
|
||||
"guest/kext/src/RgfxAccelerator.hpp" = "2711b9225040feae3e45bb8057a60b30f5d17d83d953eadc82c2db91e83e28c5"
|
||||
@@ -359,7 +359,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
|
||||
"guest/kext/src/RgfxDeviceControl.cpp" = "53c7c6a722ef4d7edeb5756eb04091d4a56f397dc5aef83c3637b1c0f129b934"
|
||||
"guest/kext/src/RgfxDeviceControl.hpp" = "c1357b80ee2141e1e2fd57213f3c9361cb497b8c6490a0b6aff8c64649be48c6"
|
||||
"guest/kext/src/RgfxDeviceName.hpp" = "b242e0ccdce31c3c454bc3a4d64b13c30e574b25379a0833973dcecbbb1146d3"
|
||||
"guest/kext/src/RgfxDisplayBounds.hpp" = "c1e8fe52f89bcb25ee178f4e0ea4ac53396109fd934348408692d21d1931ecf7"
|
||||
"guest/kext/src/RgfxDisplayBounds.hpp" = "7aafbc6d1c2bb28e50c973f77d21c1aa00b322fb5fc934d4b1238b50f3aa89db"
|
||||
"guest/kext/src/RgfxDisplayIdentity.hpp" = "ce4328b8e255f942aea0f0dc097e2e80eb4a8d7e126ea0f342fd116252357731"
|
||||
"guest/kext/src/RgfxDisplayModes.hpp" = "62026ac6fa3febe5ce403fbfe026760f0434b70cc47e5d74c191fa5509ae12cd"
|
||||
"guest/kext/src/RgfxDisplayPipeUserClient.cpp" = "460c7d61a305d7d145b3318bb4fbe940c0d2d48d63afbbfeb6f273cd929aa3af"
|
||||
@@ -397,7 +397,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
|
||||
"guest/kext/src/RgfxPointerDevice.cpp" = "a4f88cc9b272259c3a85325b2295feea6a22221f52035fc5130d72f52cb88891"
|
||||
"guest/kext/src/RgfxPointerDevice.hpp" = "a393c90bed65528495868778e4130851e98aeafcb11401aef05d2d41d5b90d3f"
|
||||
"guest/kext/src/RgfxPointerMotion.hpp" = "d5cbe1a09db996980319d0b907782675fa82b5a03fd84a51f7c7d12c5dada926"
|
||||
"guest/kext/src/RgfxPointerOver.hpp" = "c2c38dbd101b1f59400bb159bd8cb44ed8c937bf25b93e9d62a03d6c2fd9ae50"
|
||||
"guest/kext/src/RgfxPointerOver.hpp" = "757946b2332ba278201f4c2f44ec1ee2bb21ca10b017a7c7933f696d8ee8f10c"
|
||||
"guest/kext/src/RgfxPointerReporting.cpp" = "c9f33023f3acea2e638353e8943c65f28f8befa984989ae88e7abc24858b961e"
|
||||
"guest/kext/src/RgfxPoolBlocks.hpp" = "a657b67922b04b75ccef6f12e10d775867f4037e50b89a8cf0d4972af43747fe"
|
||||
"guest/kext/src/RgfxQueueLimits.hpp" = "13f8ecd60e8d19f438b8ddc1cf3a0273fba1028bc049110776b637fa2097173c"
|
||||
@@ -464,7 +464,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
|
||||
"Graft.kext/Contents/Info.plist" = "fa8533d5ec06430f3ede502e6f9e739e9c8c3f6b6909c46d854effe6028cbc7f"
|
||||
"Graft.kext/Contents/MacOS/Graft" = "04a1d44c0c80c20a71f3a662c46b56a1732b8134f095fb2ac57ec790f72baf72"
|
||||
"ReimsGraphics.kext/Contents/Info.plist" = "ae0dafd3b6c36c24d1c92467d8203d76360eb6e4f6ad5c496167a21033b2c209"
|
||||
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "d0277f202173dcecc35bce8aa2ec84cd9d53759a0fd34c26e913bcd65a191d50"
|
||||
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "2f15b6a13b44e98d4af81240c44720c0004f3c7d5c9dfecfde3b39f069930349"
|
||||
"RgfxGate.kext/Contents/Info.plist" = "7b78d915fab4d36e6cdb3f40aa2a6c1e7224f30158ee879af23451d2e6969992"
|
||||
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "90d8327eb2243b820dd90ce29e4be79a80516f3e6341137b76e9b575ea3d10eb"
|
||||
"set.toml" = "49182c19c3d961b251901e19a09016df684f1f102527a0d3274697eaaf3dbab5"
|
||||
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "534ab7e2f0b39ce9f6403b8988e89419889893b68ea91687b5aaeff38f5a9be6"
|
||||
"set.toml" = "c2f6659892f049da4bc81ec2854915cdb5cd1c4de8b15728582264b64f166131"
|
||||
@@ -7,6 +7,8 @@
|
||||
"win10-compat",
|
||||
"win10-startup-ipis",
|
||||
"win32-coroutine-fiber",
|
||||
"win32-unicode-input"
|
||||
"win32-unicode-input",
|
||||
"window-file-drop",
|
||||
"window-text-drop"
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user