Compare commits

...
Author SHA1 Message Date
Xiaochi You 6b7e7d7cad Merge pull request #1 from YinLiaoCo/feat/window-file-drop
feat(window): forward SDL3 file and text drops with normalized coords to host bridge
2026-12-03 02:08:14 +08:00
YXC0915 1a6d1626ca 📝 Record the Places texture-pool suspend baseline
The Places allocation patch changes the graphics memory layout. Give this Alpha build its own suspend compatibility family until recovery of older snapshots has been verified.
2026-12-03 01:02:03 +08:00
Xiaochi You 1ac525f616 Merge PR #2: Batch Vulkan draws and limit copied buffer sync
🐎 Batch Vulkan vertex draws and limit copied buffer sync to blit ranges
2026-12-03 00:01:49 +08:00
棠渚听潮 0824c15d61 🐎 Limit copied buffer sync to blit ranges 2026-12-02 19:33:13 +08:00
棠渚听潮 7e7b50364b 🐎 Encode Vulkan vertex draws in batches 2026-12-02 19:33:13 +08:00
YXC0915 9835066ce3 🐛 Update maintenance branch references [ci skip]
Keep automation and documentation aligned with the renamed branch.
The source pins and build steps stay the same.
2026-12-02 19:27:54 +08:00
YXC0915 8ae206e06a Use the organization QEMU fork for runtime builds 2026-12-02 18:59:09 +08:00
Shroap bfea2dc988 feat(window): forward SDL3 text and URL drops to host bridge 2026-12-02 04:00:53 +08:00
Shroap 3fdde46abd feat(window): forward SDL3 file drops with normalized coords to host bridge 2026-12-02 03:56:21 +08:00
YXC0915 cf00aac721 🐛 Supersede unfinished Alpha builds on push
Cancel an older dispatcher and request the newest runtime build.
2026-12-02 02:05:39 +08:00
YXC0915 e76060b02c 🆕 Queue an Alpha for runtime branch pushes
Dispatch the default packaging workflow with the pushed runtime SHA.
Publish the verified build through the existing Alpha release path.
2026-12-02 01:58:33 +08:00
YXC0915 9d9be66a68 🐛 Pin the Win32 user NAT socket fix
Use the QEMU maintenance merge that removes Winsock fd_set truncation in Windows user networking.
2026-12-02 01:15:32 +08:00
14 changed files with 1834 additions and 146 deletions

No files matched your search

@@ -0,0 +1,25 @@
name: Queue Runtime Alpha
on:
push:
branches: [intel-vm-suspend]
permissions:
actions: write
concurrency:
group: queue-runtime-alpha
cancel-in-progress: true
jobs:
alpha:
if: github.repository == 'reims-go/reims-vgpu'
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Queue Alpha for the pushed commit
env:
GH_TOKEN: ${{ github.token }}
run: |
gh workflow run runtime-preview.yml --repo "$GITHUB_REPOSITORY" --ref master \
-f upstream_commit="$GITHUB_SHA" -f publish=true -f supersede=true
+2 -2
View File
@@ -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
+145
View File
@@ -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]
+125 -61
View File
@@ -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]
+500
View File
@@ -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(())
}
}
+2
View File
@@ -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);
+72 -1
View File
@@ -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();
+3 -1
View File
@@ -7,6 +7,8 @@
"win10-compat",
"win10-startup-ipis",
"win32-coroutine-fiber",
"win32-unicode-input"
"win32-unicode-input",
"window-file-drop",
"window-text-drop"
]
}
Vendored
+1 -1
Submodule vendor/qemu updated: fa8e2e4b9e...e6d7cb7422.