Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,13 @@ jobs:
set -o pipefail
cargo test -p mx --test conformance -- --test-threads=1 2>&1 | tee validation.log
! grep -q "mX Vulkan validation error" validation.log
- name: openOMSI's shaders on lavapipe under the validation layer
env:
VK_INSTANCE_LAYERS: VK_LAYER_KHRONOS_validation
run: |
set -o pipefail
cargo test -p mx --test openomsi_shaders -- --nocapture 2>&1 | tee shaders.log
! grep -q "mX Vulkan validation error" shaders.log
- name: wgpu-mx through wgpu's API, and as a wgpu backend
run: cargo test -p wgpu-mx --features custom
- name: Android (Vulkan) compiles
Expand Down Expand Up @@ -101,5 +108,13 @@ jobs:
run: cargo test -p mx-types -p mx-shader --all-features
- name: Conformance tests on WARP
run: cargo test -p mx --test conformance -- --test-threads=1
# (openOMSI's shaders through DXC, as the game ships it: the Windows SDK's dxcompiler.dll
# and dxil.dll on the path, or mX falls back to FXC)
- name: openOMSI's shaders through DXC on WARP
shell: pwsh
run: |
$dxc = Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\bin\*\x64\dxcompiler.dll" | Sort-Object FullName -Descending | Select-Object -First 1
if ($dxc) { $env:PATH = "$($dxc.DirectoryName);$env:PATH"; Write-Host "DXC: $($dxc.FullName)" } else { Write-Host "no dxcompiler.dll in the Windows SDK: FXC" }
cargo test -p mx --test openomsi_shaders -- --nocapture
- name: wgpu-mx through wgpu's API, and as a wgpu backend
run: cargo test -p wgpu-mx --features custom -- --test-threads=1
10 changes: 8 additions & 2 deletions crates/mx-dx12/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,10 @@ impl CommandEncoder {
);
assert_eq!(texture.dimension(), t::TextureDimension::D2, "generate_mipmaps: 2D textures only on Direct3D 12");
let format = texture.format();
let device = Device { shared: self.rec.shared.clone() };
let device = Device {
shared: self.rec.shared.clone(),
owner: None,
};
let (pipeline, sampler) = device.mip_tools(format);
for layer in 0..texture.layers() {
for level in 1..texture.mip_level_count() {
Expand Down Expand Up @@ -641,7 +644,10 @@ impl CommandEncoder {
"GPU-driven draw arguments need STORAGE | INDIRECT usage"
);
assert!(count.usage().contains(t::BufferUsages::INDIRECT), "a GPU-driven draw count needs INDIRECT usage");
let device = Device { shared: self.rec.shared.clone() };
let device = Device {
shared: self.rec.shared.clone(),
owner: None,
};
let tool = device.indirect_tool();
let n = if draws.0.indexed { 20 } else { 16 };
let bg = device.create_bind_group(&crate::BindGroupDescriptor {
Expand Down
28 changes: 27 additions & 1 deletion crates/mx-dx12/src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,14 @@ impl Adapter {
mips: Mutex::new(crate::command::MipTools::default()),
indirect: Mutex::new(None),
});
Ok((Device { shared: shared.clone() }, Queue { shared }))
let owner = Some(Arc::new(Owner(shared.clone())));
Ok((
Device {
shared: shared.clone(),
owner: owner.clone(),
},
Queue { shared, owner },
))
}
}

Expand Down Expand Up @@ -961,10 +968,26 @@ impl Drop for Shared {
}
}

/// The program's hold on a device: every `Device` and `Queue` it was given (and their clones)
/// share one. When the last goes, the queue is waited for, which submits the pending queue
/// writes and reclaims what finished submissions and released views keep. Those keep textures
/// and buffers, and so the device's shared state: after the program's last submission nothing
/// reclaimed them, and the device was never released (#4).
pub(crate) struct Owner(pub(crate) Arc<Shared>);

impl Drop for Owner {
fn drop(&mut self) {
let _ = self.0.wait_idle();
}
}

/// The GPU. Cheap to clone; every clone is the same device.
#[derive(Clone)]
pub struct Device {
pub(crate) shared: Arc<Shared>,
/// (held for its drop; none for the device handles mX makes for itself while recording)
#[allow(dead_code)]
pub(crate) owner: Option<Arc<Owner>>,
}

impl Device {
Expand Down Expand Up @@ -1030,6 +1053,9 @@ impl Device {
#[derive(Clone)]
pub struct Queue {
pub(crate) shared: Arc<Shared>,
/// (held for its drop, as the device's)
#[allow(dead_code)]
pub(crate) owner: Option<Arc<Owner>>,
}

impl Queue {
Expand Down
25 changes: 14 additions & 11 deletions crates/mx-dx12/src/heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,10 +231,13 @@ pub(crate) struct Heap {
textures: Slots,
samplers: Slots,
buffers: Slots,
/// Textures whose heap view was released but which a submission may still read.
retired: Vec<(u64, Texture)>,
/// The resources of textures whose heap view was released but which a submission may
/// still read. The resource alone, not the `Texture`: a texture holds the device's shared
/// state, which holds this list - after the last submission nothing reclaimed it, and the
/// device and every texture retired late were never released (#4).
retired: Vec<(u64, ID3D12Resource)>,
/// Buffers likewise.
retired_buffers: Vec<(u64, Buffer)>,
retired_buffers: Vec<(u64, ID3D12Resource)>,
/// The buffers with views in the heap (by resource), with how many views and how many
/// writable ones: a command list keeps them in the state shaders reach them in (see
/// `Heap::buffer_states`).
Expand Down Expand Up @@ -270,7 +273,7 @@ impl Heap {

/// Release a buffer slot (reused after submission `after` is done) and keep the buffer
/// alive until then.
pub fn release_buffer(&mut self, slot: u32, after: u64, buffer: Buffer, writable: bool) {
pub fn release_buffer(&mut self, slot: u32, after: u64, buffer: &Buffer, writable: bool) {
self.buffers.release(slot, after);
if let Some(e) = self.heap_buffers.get_mut(&buffer.key()) {
e.1 -= 1;
Expand All @@ -280,7 +283,7 @@ impl Heap {
}
}
self.buffer_generation += 1;
self.retired_buffers.push((after, buffer));
self.retired_buffers.push((after, buffer.0.raw.clone()));
}

/// The state each buffer with heap views is in while shaders may reach it through the
Expand All @@ -306,9 +309,9 @@ impl Heap {

/// Release a texture slot (reused after submission `after` is done) and keep the texture
/// alive until then.
pub fn release_texture(&mut self, slot: u32, after: u64, texture: Texture) {
pub fn release_texture(&mut self, slot: u32, after: u64, texture: &Texture) {
self.textures.release(slot, after);
self.retired.push((after, texture));
self.retired.push((after, texture.0.raw.clone()));
}

pub fn alloc_sampler(&mut self) -> Result<u32> {
Expand All @@ -329,16 +332,16 @@ impl Heap {
}

/// Everything released before submission `completed` finished is free again. Returns the
/// textures to drop outside the lock (buffers are dropped here: dropping one takes no lock)
/// and the texture and buffer slots freed, whose descriptors still point at what they held.
pub fn reclaim(&mut self, completed: u64) -> (Vec<Texture>, Vec<u32>, Vec<u32>) {
/// textures' resources to release outside the lock and the texture and buffer slots freed,
/// whose descriptors still point at what they held.
pub fn reclaim(&mut self, completed: u64) -> (Vec<ID3D12Resource>, Vec<u32>, Vec<u32>) {
let (mut tex_slots, mut buf_slots, mut sampler_slots) = (Vec::new(), Vec::new(), Vec::new());
self.textures.reclaim(completed, &mut tex_slots);
self.samplers.reclaim(completed, &mut sampler_slots);
self.buffers.reclaim(completed, &mut buf_slots);
self.retired_buffers.retain(|(after, _)| *after > completed);
let mut done = Vec::new();
self.retired.retain_mut(|(after, t)| {
self.retired.retain(|(after, t)| {
if *after <= completed {
done.push(t.clone());
false
Expand Down
10 changes: 7 additions & 3 deletions crates/mx-dx12/src/resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ pub(crate) struct BufferViewInner {
impl Drop for BufferViewInner {
fn drop(&mut self) {
let shared = &self.buffer.0.shared;
shared.heap.lock().release_buffer(self.slot, shared.release_after(), self.buffer.clone(), self.writable);
shared.heap.lock().release_buffer(self.slot, shared.release_after(), &self.buffer, self.writable);
}
}

Expand Down Expand Up @@ -819,7 +819,7 @@ impl Drop for ViewInner {
fn drop(&mut self) {
let shared = &self.texture.0.shared;
if let Some(slot) = self.slot {
shared.heap.lock().release_texture(slot, shared.release_after(), self.texture.clone());
shared.heap.lock().release_texture(slot, shared.release_after(), &self.texture);
}
let mut cpu = shared.cpu.lock();
for d in [self.srv, self.uav].into_iter().flatten() {
Expand Down Expand Up @@ -1027,7 +1027,11 @@ impl Device {
if desc.usage.contains(t::BufferUsages::MAP_WRITE) {
buffer.map_write(0..buffer.size(), |b| b.copy_from_slice(desc.contents))?;
} else {
Queue { shared: self.shared.clone() }.write_buffer(&buffer, 0, desc.contents)?;
Queue {
shared: self.shared.clone(),
owner: None,
}
.write_buffer(&buffer, 0, desc.contents)?;
}
Ok(buffer)
}
Expand Down
27 changes: 26 additions & 1 deletion crates/mx-gl/src/caps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ pub(crate) struct Caps {
pub combined_texture_units: u32,
/// `GL_MAX_SAMPLES`.
pub max_samples: u32,
/// Multisampled textures, `glTexStorage2DMultisample` (GL 3.2, ES 3.1). Without them a
/// multisampled render target is a renderbuffer (ES 3.0), which shaders cannot sample.
pub multisample_textures: bool,
pub limits: t::Limits,
}

Expand Down Expand Up @@ -115,11 +118,14 @@ impl Caps {
copy_image: at_least((4, 3), (3, 2)) || has("GL_EXT_copy_image"),
indirect: at_least((4, 0), (3, 1)),
texture_shadow_lod: has("GL_EXT_texture_shadow_lod"),
timestamps: (!es && version >= (3, 3)) || has("GL_EXT_disjoint_timer_query"),
// (an ES driver may have the extension for elapsed time alone: ANGLE's counter
// for timestamps has no bits, every timestamp read 0)
timestamps: ((!es && version >= (3, 3)) || has("GL_EXT_disjoint_timer_query")) && timestamps_count(gl),
bc: has("GL_EXT_texture_compression_s3tc") && (has("GL_EXT_texture_compression_bptc") || has("GL_ARB_texture_compression_bptc") || at_least((4, 2), (9, 9))),
explicit_bindings: at_least((4, 2), (3, 1)),
invalidate: at_least((4, 3), (3, 0)),
max_samples: get(glow::MAX_SAMPLES),
multisample_textures: at_least((3, 2), (3, 1)),
vertex_texture_units: get(glow::MAX_VERTEX_TEXTURE_IMAGE_UNITS),
fragment_texture_units: get(glow::MAX_TEXTURE_IMAGE_UNITS),
combined_texture_units: get(glow::MAX_COMBINED_TEXTURE_IMAGE_UNITS),
Expand All @@ -128,3 +134,22 @@ impl Caps {
}
}
}

/// Whether a timestamp query gives a time on this context: one is written and read back.
///
/// # Safety
/// The context is current.
unsafe fn timestamps_count(gl: &glow::Context) -> bool {
// SAFETY: the caller's; a query made, used once and deleted here.
unsafe {
let Ok(q) = gl.create_query() else { return false };
while gl.get_error() != glow::NO_ERROR {}
gl.query_counter(q, glow::TIMESTAMP);
gl.finish();
let mut v = [0u8; 8];
gl.get_query_parameter_u64_with_offset(q, glow::QUERY_RESULT, v.as_mut_ptr() as usize);
let ok = gl.get_error() == glow::NO_ERROR && u64::from_le_bytes(v) > 0;
gl.delete_query(q);
ok
}
}
63 changes: 55 additions & 8 deletions crates/mx-gl/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -629,16 +629,58 @@ fn run(gl: &glow::Context, shared: &Shared, st: &mut State, cmd: Cmd) {
Cmd::DrawIndirect(args, offset, indexed) => {
let Pipeline::Render(p) = &st.pipeline else { panic!("draw without a pipeline") };
let p = p.clone();
assert!(shared.caps.indirect, "indirect draws need OpenGL 4.0 / OpenGL ES 3.1");
prepare_draw(gl, shared, st, &p, 0);
gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, Some(args.0.raw));
if indexed {
let (_, _, f) = st.index.clone().expect("draw_indexed_indirect without an index buffer");
gl.draw_elements_indirect_offset(p.0.topology, conv::index_type(f).0, offset as i32);
if !shared.caps.indirect {
'emulated: {
// OpenGL ES 3.0 (ANGLE over older chips) has no indirect draws: the
// arguments are read back and drawn directly (the GPU's earlier work on
// them waits; the draw is the same)
let len = if indexed { 20 } else { 16 };
let mut a = [0u32; 5];
gl.bind_buffer(glow::COPY_READ_BUFFER, Some(args.0.raw));
let ptr = gl.map_buffer_range(glow::COPY_READ_BUFFER, offset as i32, len, glow::MAP_READ_BIT);
if !ptr.is_null() {
std::ptr::copy_nonoverlapping(ptr, a.as_mut_ptr() as *mut u8, len as usize);
gl.unmap_buffer(glow::COPY_READ_BUFFER);
}
gl.bind_buffer(glow::COPY_READ_BUFFER, None);
if indexed {
let (count, instances, first, base, first_instance) = (a[0], a[1], a[2], a[3] as i32, a[4]);
let (_, ioffset, f) = st.index.clone().expect("draw_indexed_indirect without an index buffer");
let (ty, size) = conv::index_type(f);
if count == 0 || instances == 0 {
break 'emulated;
}
if base != 0 && !shared.caps.base_vertex {
log::warn!("mX: an indirect draw with a base vertex left out (OpenGL ES 3.0 has none)");
break 'emulated;
}
prepare_draw(gl, shared, st, &p, first_instance);
let at = (ioffset + first as u64 * size) as i32;
if base != 0 {
gl.draw_elements_instanced_base_vertex(p.0.topology, count as i32, ty, at, instances as i32, base);
} else {
gl.draw_elements_instanced(p.0.topology, count as i32, ty, at, instances as i32);
}
} else {
let (count, instances, first, first_instance) = (a[0], a[1], a[2], a[3]);
if count == 0 || instances == 0 {
break 'emulated;
}
prepare_draw(gl, shared, st, &p, first_instance);
gl.draw_arrays_instanced(p.0.topology, first as i32, count as i32, instances as i32);
}
}
} else {
gl.draw_arrays_indirect_offset(p.0.topology, offset as i32);
prepare_draw(gl, shared, st, &p, 0);
gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, Some(args.0.raw));
if indexed {
let (_, _, f) = st.index.clone().expect("draw_indexed_indirect without an index buffer");
gl.draw_elements_indirect_offset(p.0.topology, conv::index_type(f).0, offset as i32);
} else {
gl.draw_arrays_indirect_offset(p.0.topology, offset as i32);
}
gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, None);
}
gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, None);
}
Cmd::Dispatch(x, y, z) => {
let Pipeline::Compute(p) = &st.pipeline else { panic!("dispatch without a pipeline") };
Expand Down Expand Up @@ -960,6 +1002,10 @@ unsafe fn attach(gl: &glow::Context, target: u32, attachment: u32, v: &TextureVi
let tex = v.texture();
// SAFETY: the caller's.
unsafe {
if let Some(rb) = tex.0.rb {
gl.framebuffer_renderbuffer(target, attachment, glow::RENDERBUFFER, Some(rb));
return;
}
match tex.0.target {
glow::TEXTURE_2D | glow::TEXTURE_2D_MULTISAMPLE => gl.framebuffer_texture_2d(target, attachment, tex.0.target, Some(tex.0.raw), v.0.base_mip_level as i32),
glow::TEXTURE_CUBE_MAP => gl.framebuffer_texture_2d(target, attachment, glow::TEXTURE_CUBE_MAP_POSITIVE_X + v.0.base_array_layer, Some(tex.0.raw), v.0.base_mip_level as i32),
Expand Down Expand Up @@ -1357,6 +1403,7 @@ fn zero_range(gl: &glow::Context, shared: &Shared, tex: &Texture, mips: Range<u3
for mip in mips {
for layer in layers.clone() {
match tex.0.target {
_ if tex.0.rb.is_some() => gl.framebuffer_renderbuffer(glow::DRAW_FRAMEBUFFER, attachment, glow::RENDERBUFFER, tex.0.rb),
glow::TEXTURE_2D | glow::TEXTURE_2D_MULTISAMPLE => gl.framebuffer_texture_2d(glow::DRAW_FRAMEBUFFER, attachment, tex.0.target, Some(tex.0.raw), mip as i32),
glow::TEXTURE_CUBE_MAP => gl.framebuffer_texture_2d(glow::DRAW_FRAMEBUFFER, attachment, image_target(tex, layer), Some(tex.0.raw), mip as i32),
_ => gl.framebuffer_texture_layer(glow::DRAW_FRAMEBUFFER, attachment, Some(tex.0.raw), mip as i32, layer as i32),
Expand Down
2 changes: 2 additions & 0 deletions crates/mx-gl/src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ pub struct SubmissionIndex(pub u64);
pub(crate) enum Garbage {
Buffer(glow::Buffer),
Texture(glow::Texture),
Renderbuffer(glow::Renderbuffer),
Sampler(glow::Sampler),
Program(glow::Program),
Query(glow::Query),
Expand Down Expand Up @@ -313,6 +314,7 @@ impl Shared {
match g {
Garbage::Buffer(b) => gl.delete_buffer(b),
Garbage::Texture(t) => gl.delete_texture(t),
Garbage::Renderbuffer(r) => gl.delete_renderbuffer(r),
Garbage::Sampler(s) => gl.delete_sampler(s),
Garbage::Program(p) => gl.delete_program(p),
Garbage::Query(q) => gl.delete_query(q),
Expand Down
Loading
Loading