Skip to content

Commit

Permalink
Windows working with new wgpu pr
Browse files Browse the repository at this point in the history
  • Loading branch information
DDRBoxman committed Oct 9, 2023
1 parent e9cca96 commit 676be0b
Show file tree
Hide file tree
Showing 8 changed files with 51 additions and 160 deletions.
28 changes: 4 additions & 24 deletions Cappy3ds/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use raw_window_handle::{
RawDisplayHandle, RawWindowHandle, WindowsDisplayHandle,
};
use std::ffi;
use wgpu_hal;


mod render;

Expand All @@ -19,31 +19,11 @@ pub extern "C" fn hello_world() {

#[no_mangle]
#[cfg(target_os = "windows")]
pub extern "C" fn send_visual(panel: *mut ffi::c_void, callback: extern "C" fn( *mut ffi::c_void, *mut ffi::c_void) -> i32) {
use wgpu::Surface;

let mut res = State::new_from_visual();
pub extern "C" fn send_swap_chain_panel(swap_chain_panel: *mut ffi::c_void) {
let mut res = State::new_from_swap_chain_panel(swap_chain_panel);
let mut v = executor::block_on(res);

unsafe {
v.surface
.as_hal_mut::<wgpu_hal::dx12::Api, _, _>(|surface| {
match surface {
Some(surface) => {
match &surface.swap_chain {
Some(chain) => {
callback(panel, chain.raw.as_mut_ptr() as *mut ffi::c_void);
}
None => todo!(),
}

},
None => todo!(),
}
})
};

v.render();
v.render();
}

#[no_mangle]
Expand Down
4 changes: 2 additions & 2 deletions Cappy3ds/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ use futures::executor;
pub use render::render::State;

fn main() {
let mut res = State::new_from_visual();
let mut v = executor::block_on(res);
// let mut res = State::new_from_visual();
// let mut v = executor::block_on(res);
}
159 changes: 32 additions & 127 deletions Cappy3ds/src/render/render.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use wgpu::{Instance, Surface};

pub struct State {
pub surface: wgpu::Surface,
device: wgpu::Device,
Expand All @@ -12,130 +14,16 @@ pub struct State {
}

impl State {
pub async fn new_from_visual() -> Self {
let width = 400;
let height = 400;

// The instance is a handle to our GPU
// Backends::all => Vulkan + Metal + DX12 + Browser WebGPU
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::all(),
dx12_shader_compiler: Default::default(),
});
pub async fn new_from_swap_chain_panel(swap_chain_panel: *mut std::ffi::c_void) -> Self {
let instance = Self::create_instance();

// # Safety
//
// The surface needs to live as long as the window that created it.
// State owns the window so this should be safe.
let surface = unsafe { instance.create_surface_from_surface_handle(std::ptr::null_mut()) };

let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::default(),
compatible_surface: Some(&surface),
force_fallback_adapter: false,
})
.await
.unwrap();

let (device, queue) = adapter
.request_device(
&wgpu::DeviceDescriptor {
features: wgpu::Features::empty(),
limits: wgpu::Limits::default(),
label: None,
},
None, // Trace path
)
.await
.unwrap();

let surface_caps = surface.get_capabilities(&adapter);
// Shader code in this tutorial assumes an sRGB surface texture. Using a different
// one will result all the colors coming out darker. If you want to support non
// sRGB surfaces, you'll need to account for that when drawing to the frame.
let surface_format = surface_caps
.formats
.iter()
.copied()
.find(|f| f.is_srgb())
.unwrap_or(surface_caps.formats[0]);

let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface_format,
width: width,
height: height,
present_mode: surface_caps.present_modes[0],
alpha_mode: surface_caps.alpha_modes[0],
view_formats: vec![],
};
let surface = unsafe { instance.create_surface_from_swap_chain_panel(swap_chain_panel) };

surface.configure(&device, &config);

let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
});

let render_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"),
bind_group_layouts: &[],
push_constant_ranges: &[],
});

let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "vs_main", // 1.
buffers: &[], // 2.
},
fragment: Some(wgpu::FragmentState {
// 3.
module: &shader,
entry_point: "fs_main",
targets: &[Some(wgpu::ColorTargetState {
// 4.
format: config.format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
}),

primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList, // 1.
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw, // 2.
cull_mode: Some(wgpu::Face::Back),
// Setting this to anything other than Fill requires Features::NON_FILL_POLYGON_MODE
polygon_mode: wgpu::PolygonMode::Fill,
// Requires Features::DEPTH_CLIP_CONTROL
unclipped_depth: false,
// Requires Features::CONSERVATIVE_RASTERIZATION
conservative: false,
},

depth_stencil: None, // 1.
multisample: wgpu::MultisampleState {
count: 1, // 2.
mask: !0, // 3.
alpha_to_coverage_enabled: false, // 4.
},
multiview: None, // 5.
});

Self {
//window,
surface,
device,
queue,
config,
// size,
render_pipeline,
}
Self::new_with_surface(instance, surface).await
}

// Creating some of the wgpu types requires async code
Expand All @@ -144,24 +32,37 @@ impl State {
>(
window: &W,
) -> Self {
// let size = window.inner_size();
let instance = Self::create_instance();

// # Safety
//
// The surface needs to live as long as the window that created it.
// State owns the window so this should be safe.
let surface = unsafe { instance.create_surface(&window) }.unwrap();

let width = 400;
let height = 400;
Self::new_with_surface(instance, surface).await
}

fn create_instance() -> wgpu::Instance{
// The instance is a handle to our GPU
// Backends::all => Vulkan + Metal + DX12 + Browser WebGPU
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::all(),
dx12_shader_compiler: Default::default(),
gles_minor_version: wgpu::Gles3MinorVersion::default(),
});

// # Safety
//
// The surface needs to live as long as the window that created it.
// State owns the window so this should be safe.
let surface = unsafe { instance.create_surface(&window) }.unwrap();
return instance;
}

async fn new_with_surface(instance: Instance, surface: Surface) -> Self {
// let size = window.inner_size();

let width = 400;
let height = 400;



let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::default(),
Expand Down Expand Up @@ -193,6 +94,7 @@ impl State {
.copied()
.find(|f| f.is_srgb())
.unwrap_or(surface_caps.formats[0]);

let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface_format,
Expand All @@ -202,6 +104,7 @@ impl State {
alpha_mode: surface_caps.alpha_modes[0],
view_formats: vec![],
};

surface.configure(&device, &config);

let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
Expand Down Expand Up @@ -306,11 +209,13 @@ impl State {
b: 0.3,
a: 1.0,
}),
store: true,
store: wgpu::StoreOp::Store,
},
}),
],
depth_stencil_attachment: None,
occlusion_query_set: None,
timestamp_writes: None,
});

// NEW!
Expand Down
4 changes: 2 additions & 2 deletions win/Cappy3ds.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34031.279
# Visual Studio 15
VisualStudioVersion = 15.0.28307.2092
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cappy3ds", "Cappy3ds.csproj", "{7197E3C4-DB4C-4CBD-A517-206C6E0D081F}"
EndProject
Expand Down
10 changes: 8 additions & 2 deletions win/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Foundation.Collections;
using WinRT;
using static Cappy3ds.MainWindow;



Expand Down Expand Up @@ -49,8 +51,12 @@ public MainWindow()
unsafe
{


CsBindgen.NativeMethods.send_visual((void*)((IWinRTObject)swapChainPanel1).NativeObject.GetRef(), &Sum);

// var nativePanel = swapChainPanel1.As<ISwapChainPanelNative>();

IntPtr objectAddress = Marshal.GetComInterfaceForObject(swapChainPanel1, typeof(ISwapChainPanelNative));

CsBindgen.NativeMethods.send_swap_chain_panel((void*)objectAddress);
}

// renderView.setup();
Expand Down
4 changes: 2 additions & 2 deletions win/NativeMethods.g.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ internal static unsafe partial class NativeMethods
[DllImport(__DllName, EntryPoint = "hello_world", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void hello_world();

[DllImport(__DllName, EntryPoint = "send_visual", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void send_visual(void* panel, delegate* unmanaged[Cdecl]<void*, void*, int> callback);
[DllImport(__DllName, EntryPoint = "send_swap_chain_panel", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void send_swap_chain_panel(void* swap_chain_panel);

[DllImport(__DllName, EntryPoint = "send_window", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
public static extern void send_window(void* app_kit_nsview);
Expand Down
2 changes: 1 addition & 1 deletion win/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"profiles": {
"Cappy3ds (Package)": {
"commandName": "MsixPackage",
"nativeDebugging": false
"nativeDebugging": true
},
"Cappy3ds (Unpackaged)": {
"commandName": "Project"
Expand Down
Binary file removed win/libcappy3ds.dll
Binary file not shown.

0 comments on commit 676be0b

Please sign in to comment.