Compare commits

..

9 Commits

Author SHA1 Message Date
413839ccb8 oops, it’s not a signal 2025-11-16 14:33:09 +03:00
7b22551bee add some real UI 2025-11-15 19:14:12 +03:00
16ea643f90 clang-format 2025-11-15 18:48:22 +03:00
be2df57702 reduce requirements of the Viewport 2025-11-15 18:37:45 +03:00
d92d75a4d1 split pointer and object operations 2025-11-15 18:22:02 +03:00
4e4c4493f9 minimal Qt6 UI 2025-11-15 01:27:07 +03:00
10d74f1318 move configure() responsibility a bit 2025-11-14 23:47:35 +03:00
e12f4c77aa split lib/bin, hopefully right 2025-11-14 23:08:28 +03:00
2575dd570c add GUI wrapper skeleton 2025-11-14 20:09:10 +03:00
19 changed files with 991 additions and 244 deletions

9
.clang-format Normal file
View File

@ -0,0 +1,9 @@
BasedOnStyle: LLVM
UseTab: Always
TabWidth: 4
IndentWidth: 4
AccessModifierOffset: -4
IndentCaseLabels: false
ColumnLimit: 0
PointerAlignment: Left
PackConstructorInitializers: Never

1
.gitignore vendored
View File

@ -1 +1,2 @@
/target /target
/build

14
CMakeLists.txt Normal file
View File

@ -0,0 +1,14 @@
cmake_minimum_required(VERSION 3.18)
project(photon_light VERSION 1.0.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Qt6 REQUIRED COMPONENTS Gui Widgets)
find_program(CARGO cargo REQUIRED)
set(CARGO_TARGET_DIR "${CMAKE_BINARY_DIR}/cargo")
qt_standard_project_setup()
add_subdirectory(ui)

11
Cargo.lock generated
View File

@ -1165,6 +1165,17 @@ dependencies = [
"winit", "winit",
] ]
[[package]]
name = "photon-light-impl"
version = "0.1.0"
dependencies = [
"glam",
"photon-light",
"pollster",
"raw-window-handle",
"wgpu",
]
[[package]] [[package]]
name = "pin-project" name = "pin-project"
version = "1.1.10" version = "1.1.10"

View File

@ -1,3 +1,6 @@
[workspace]
members = ["ui"]
[package] [package]
name = "photon-light" name = "photon-light"
version = "0.1.0" version = "0.1.0"

279
src/lib.rs Normal file
View File

@ -0,0 +1,279 @@
#![feature(gen_blocks)]
use std::{convert::identity, error::Error, f32::consts::PI};
use glam::{Mat4, UVec2, Vec3, vec3};
use crate::{
camera::OrbitalCamera,
render::lines::{LookParams, Mesh, Pipeline, Vertex},
trace::{Scene, Source, Sphere},
};
mod camera;
mod ray;
mod render;
mod trace;
const OUTPUT_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Bgra8UnormSrgb;
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(C)]
pub struct SphericalPosition {
pub yaw: f32,
pub pitch: f32,
pub distance: f32,
}
#[derive(Debug, Clone, Copy)]
#[repr(C)]
pub struct RedrawArgs {
pub camera_position: SphericalPosition,
pub light_position: SphericalPosition,
pub light_radius: f32,
pub light_spread: f32,
}
pub struct Gpu {
device: wgpu::Device,
queue: wgpu::Queue,
surface: wgpu::Surface<'static>,
}
pub struct Core {
device: wgpu::Device,
queue: wgpu::Queue,
surface: wgpu::Surface<'static>,
pipeline: Pipeline,
tripod: Mesh,
}
pub fn new_tripod(device: &wgpu::Device) -> Mesh {
Mesh::new(
device,
&[
Vertex::new(vec3(0., 0., 0.), vec3(1., 0., 0.)),
Vertex::new(vec3(1., 0., 0.), vec3(1., 0., 0.)),
Vertex::new(vec3(0., 0., 0.), vec3(0., 1., 0.)),
Vertex::new(vec3(0., 1., 0.), vec3(0., 1., 0.)),
Vertex::new(vec3(0., 0., 0.), vec3(0., 0., 1.)),
Vertex::new(vec3(0., 0., 1.), vec3(0., 0., 1.)),
],
)
}
fn loop_list<T: Clone>(iter: impl IntoIterator<Item = T>) -> impl Iterator<Item = T> {
loop_list_ex(iter, identity, identity)
}
fn loop_list_ex<T: Clone, U>(
iter: impl IntoIterator<Item = T>,
mut fa: impl FnMut(T) -> U,
mut fb: impl FnMut(T) -> U,
) -> impl Iterator<Item = U> {
gen move {
let mut iter = iter.into_iter();
let Some(first) = iter.next() else { return };
yield fa(first.clone());
for item in iter {
yield fb(item.clone());
yield fa(item);
}
yield fb(first);
}
}
impl Core {
pub fn new(gpu: Gpu) -> Self {
let Gpu {
device,
queue,
surface,
} = gpu;
let pipeline = Pipeline::new(&device, OUTPUT_FORMAT);
let tripod = new_tripod(&device);
queue.submit([]); // flush buffer updates
Self {
device,
queue,
surface,
pipeline,
tripod,
}
}
fn render(&self, output: &wgpu::Texture, args: &RedrawArgs) {
let camera = OrbitalCamera {
position_yaw: args.camera_position.yaw,
position_pitch: args.camera_position.pitch,
distance: args.camera_position.distance,
};
let aspect = {
let size = output.size();
let w = size.width as f32;
let h = size.height as f32;
w / h
};
let perspective = Mat4::perspective_lh(PI / 3., aspect, 1e-2, 1e2);
self.pipeline.set_look(
&self.queue,
LookParams {
m: perspective * camera.transform(),
},
);
self.queue.submit([]); // flush buffer updates
let view = output.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 0.1,
g: 0.2,
b: 0.8,
a: 1.0,
}),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
..Default::default()
});
self.pipeline.render(&mut pass, [&self.tripod]);
let source = Source {
position_yaw: args.light_position.yaw,
position_pitch: args.light_position.pitch,
distance: args.light_position.distance,
radius: args.light_radius,
spread: args.light_spread,
};
let contour: Vec<Vertex> = loop_list(source.contour(17))
.map(|pos| Vertex {
pos,
color: vec3(1., 1., 1.),
})
.collect();
self.pipeline
.render(&mut pass, [&Mesh::new(&self.device, &contour)]);
const BASE_R: f32 = 2.;
const BASE_POS: Vec3 = vec3(0., 0., -BASE_R);
const BASE: Sphere = Sphere {
position: vec3(0., 0., -BASE_R),
radius: BASE_R,
};
fn sphere(pos: Vec3) -> Sphere {
Sphere {
position: pos,
radius: BASE_POS.distance(pos) - BASE_R,
}
}
let scene = Scene {
objects: vec![
BASE,
sphere(vec3(0., 0., 0.1)),
sphere(vec3(0.3, 0., 0.1)),
sphere(vec3(0.1, 0.3, 0.1)),
],
};
let mut prng = rand_pcg::Pcg64::new(42, 0);
let rays: Vec<Vertex> = (0..10000)
.flat_map(|_| {
let ray = source.make_ray(&mut prng);
if let Some(ray) = scene.trace_ray(ray) {
[
Vertex {
pos: ray.base - 0.02 * ray.dir,
color: vec3(1., 1., 1.),
},
Vertex {
pos: ray.base,
color: vec3(0., 1., 0.),
},
]
} else {
[
Vertex {
pos: ray.base,
color: vec3(1., 1., 1.),
},
Vertex {
pos: ray.base + 0.1 * ray.dir,
color: vec3(1., 0., 0.),
},
]
}
})
.collect();
self.pipeline
.render(&mut pass, [&Mesh::new(&self.device, &rays)]);
drop(pass);
self.queue.submit(std::iter::once(encoder.finish()));
}
/// Configures the renderer for a given target size.
pub fn configure(&mut self, pixel_size: UVec2) {
self.surface.configure(
&self.device,
&wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
format: OUTPUT_FORMAT,
width: pixel_size.x,
height: pixel_size.y,
present_mode: wgpu::PresentMode::Fifo,
alpha_mode: wgpu::CompositeAlphaMode::Auto,
view_formats: vec![],
desired_maximum_frame_latency: 2,
},
);
}
/// Redraws the entire surface.
///
/// [`Self::configure`] must be called at least once before this.
pub fn redraw(&mut self, args: &RedrawArgs) {
let output = self.surface.get_current_texture().unwrap();
self.render(&output.texture, args);
output.present();
}
}
pub async fn init_gpu_inner<E: Error + 'static>(
make_surface: impl FnOnce(&wgpu::Instance) -> Result<wgpu::Surface<'static>, E>,
) -> Result<Gpu, Box<dyn Error>> {
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
backends: wgpu::Backends::PRIMARY,
..Default::default()
});
let surface = make_surface(&instance)?;
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::default())
.await
.unwrap();
Ok(Gpu {
device,
queue,
surface,
})
}

View File

@ -1,8 +1,7 @@
#![feature(gen_blocks)] use std::{f32::consts::PI, sync::Arc};
use std::{convert::identity, error::Error, f32::consts::PI, sync::Arc}; use glam::uvec2;
use photon_light::{Core, RedrawArgs, SphericalPosition, init_gpu_inner};
use glam::{Mat4, Vec3, vec3};
use winit::{ use winit::{
application::ApplicationHandler, application::ApplicationHandler,
event::WindowEvent, event::WindowEvent,
@ -10,236 +9,48 @@ use winit::{
window::Window, window::Window,
}; };
use crate::{
camera::OrbitalCamera,
render::lines::{LookParams, Mesh, Pipeline, Vertex},
trace::{Scene, Source, Sphere},
};
mod camera;
mod ray;
mod render;
mod trace;
const TITLE: &str = "WGPU example"; const TITLE: &str = "WGPU example";
const OUTPUT_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Bgra8UnormSrgb;
struct MainWindow { struct MainWindow {
handle: Arc<Window>, window: Arc<Window>,
device: wgpu::Device, core: Core,
queue: wgpu::Queue,
surface: wgpu::Surface<'static>,
surface_configured: bool,
pipeline: Pipeline,
tripod: Mesh,
}
pub fn new_tripod(device: &wgpu::Device) -> Mesh {
Mesh::new(
device,
&[
Vertex::new(vec3(0., 0., 0.), vec3(1., 0., 0.)),
Vertex::new(vec3(1., 0., 0.), vec3(1., 0., 0.)),
Vertex::new(vec3(0., 0., 0.), vec3(0., 1., 0.)),
Vertex::new(vec3(0., 1., 0.), vec3(0., 1., 0.)),
Vertex::new(vec3(0., 0., 0.), vec3(0., 0., 1.)),
Vertex::new(vec3(0., 0., 1.), vec3(0., 0., 1.)),
],
)
}
fn loop_list<T: Clone>(iter: impl IntoIterator<Item = T>) -> impl Iterator<Item = T> {
loop_list_ex(iter, identity, identity)
}
fn loop_list_ex<T: Clone, U>(
iter: impl IntoIterator<Item = T>,
mut fa: impl FnMut(T) -> U,
mut fb: impl FnMut(T) -> U,
) -> impl Iterator<Item = U> {
gen move {
let mut iter = iter.into_iter();
let Some(first) = iter.next() else { return };
yield fa(first.clone());
for item in iter {
yield fb(item.clone());
yield fa(item);
}
yield fb(first);
}
} }
impl MainWindow { impl MainWindow {
fn new(event_loop: &ActiveEventLoop) -> Self { fn new(event_loop: &ActiveEventLoop) -> Self {
let handle = event_loop let window = event_loop
.create_window(Window::default_attributes().with_title(TITLE)) .create_window(Window::default_attributes().with_title(TITLE))
.unwrap(); .unwrap();
let handle = Arc::new(handle); let window = Arc::new(window);
let gpu = pollster::block_on(init_gpu_inner(|instance| {
let (device, queue, surface) = pollster::block_on(init_gpu(Arc::clone(&handle))).unwrap(); instance.create_surface(Arc::clone(&window))
let pipeline = Pipeline::new(&device, OUTPUT_FORMAT); }))
let tripod = new_tripod(&device); .unwrap();
queue.submit([]); // flush buffer updates let mut core = Core::new(gpu);
core.configure(uvec2(1, 1));
Self { Self { window, core }
handle,
device,
queue,
surface,
surface_configured: false,
pipeline,
tripod,
}
}
fn render(&self, output: &wgpu::Texture) {
let camera = OrbitalCamera {
position_yaw: PI / 4.,
position_pitch: 0.5f32.sqrt().atan(),
distance: 3.0,
};
let aspect = {
let size = output.size();
let w = size.width as f32;
let h = size.height as f32;
w / h
};
let perspective = Mat4::perspective_lh(PI / 3., aspect, 1e-2, 1e2);
self.pipeline.set_look(
&self.queue,
LookParams {
m: perspective * camera.transform(),
},
);
self.queue.submit([]); // flush buffer updates
let view = output.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: 0.1,
g: 0.2,
b: 0.8,
a: 1.0,
}),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
..Default::default()
});
self.pipeline.render(&mut pass, [&self.tripod]);
let source = Source {
position_yaw: 0.0,
position_pitch: PI / 3.,
distance: 1.0,
radius: 0.125,
spread: 0.125,
};
let contour: Vec<Vertex> = loop_list(source.contour(17))
.map(|pos| Vertex {
pos,
color: vec3(1., 1., 1.),
})
.collect();
self.pipeline
.render(&mut pass, [&Mesh::new(&self.device, &contour)]);
const BASE_R: f32 = 2.;
const BASE_POS: Vec3 = vec3(0., 0., -BASE_R);
const BASE: Sphere = Sphere {
position: vec3(0., 0., -BASE_R),
radius: BASE_R,
};
fn sphere(pos: Vec3) -> Sphere {
Sphere {
position: pos,
radius: BASE_POS.distance(pos) - BASE_R,
}
}
let scene = Scene {
objects: vec![
BASE,
sphere(vec3(0., 0., 0.1)),
sphere(vec3(0.3, 0., 0.1)),
sphere(vec3(0.1, 0.3, 0.1)),
],
};
let mut prng = rand_pcg::Pcg64::new(42, 0);
let rays: Vec<Vertex> = (0..10000)
.flat_map(|_| {
let ray = source.make_ray(&mut prng);
if let Some(ray) = scene.trace_ray(ray) {
[
Vertex {
pos: ray.base - 0.02 * ray.dir,
color: vec3(1., 1., 1.),
},
Vertex {
pos: ray.base,
color: vec3(0., 1., 0.),
},
]
} else {
[
Vertex {
pos: ray.base,
color: vec3(1., 1., 1.),
},
Vertex {
pos: ray.base + 0.1 * ray.dir,
color: vec3(1., 0., 0.),
},
]
}
})
.collect();
self.pipeline
.render(&mut pass, [&Mesh::new(&self.device, &rays)]);
drop(pass);
self.queue.submit(std::iter::once(encoder.finish()));
} }
fn event(&mut self, event_loop: &ActiveEventLoop, event: WindowEvent) { fn event(&mut self, event_loop: &ActiveEventLoop, event: WindowEvent) {
match event { match event {
WindowEvent::CloseRequested => event_loop.exit(), WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::Resized(physical_size) => { WindowEvent::Resized(physical_size) => self
self.surface.configure( .core
&self.device, .configure(uvec2(physical_size.width, physical_size.height)),
&wgpu::SurfaceConfiguration { WindowEvent::RedrawRequested => self.core.redraw(&RedrawArgs {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT camera_position: SphericalPosition {
| wgpu::TextureUsages::COPY_DST, yaw: PI / 4.,
format: OUTPUT_FORMAT, pitch: 0.5f32.sqrt().atan(),
width: physical_size.width, distance: 3.0,
height: physical_size.height, },
present_mode: wgpu::PresentMode::Fifo, light_position: SphericalPosition {
alpha_mode: wgpu::CompositeAlphaMode::Auto, yaw: 0.0,
view_formats: vec![], pitch: PI / 3.,
desired_maximum_frame_latency: 2, distance: 1.0,
}, },
); light_radius: 0.125,
self.surface_configured = true; light_spread: 0.125,
} }),
WindowEvent::RedrawRequested => {
if !self.surface_configured {
return;
}
let output = self.surface.get_current_texture().unwrap();
self.render(&output.texture);
output.present();
}
_ => {} _ => {}
} }
} }
@ -270,34 +81,11 @@ impl ApplicationHandler for Application {
.main_window .main_window
.as_mut() .as_mut()
.expect("window must exist to recieve events"); .expect("window must exist to recieve events");
assert_eq!(window.handle.id(), window_id); assert_eq!(window.window.id(), window_id);
window.event(event_loop, event); window.event(event_loop, event);
} }
} }
async fn init_gpu<'window>(
wnd: impl wgpu::WindowHandle + 'window,
) -> Result<(wgpu::Device, wgpu::Queue, wgpu::Surface<'window>), Box<dyn Error>> {
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
backends: wgpu::Backends::PRIMARY,
..Default::default()
});
let surface = instance.create_surface(wnd)?;
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::default())
.await
.unwrap();
Ok((device, queue, surface))
}
fn main() { fn main() {
let event_loop = EventLoop::new().unwrap(); let event_loop = EventLoop::new().unwrap();
event_loop.set_control_flow(ControlFlow::Wait); event_loop.set_control_flow(ControlFlow::Wait);

13
ui/CMakeLists.txt Normal file
View File

@ -0,0 +1,13 @@
include(impl.cmake)
qt_add_executable(photon_light
src/api.cxx
src/main.cxx
src/main_window.cxx
src/main_window.ui
src/viewport.cxx
)
target_link_libraries(photon_light PRIVATE Qt6::Gui Qt6::Widgets)
target_link_libraries(photon_light PRIVATE photon_light_impl)
target_include_directories(photon_light PRIVATE src)

15
ui/Cargo.toml Normal file
View File

@ -0,0 +1,15 @@
[package]
name = "photon-light-impl"
version = "0.1.0"
edition = "2024"
[lib]
crate-type = ["staticlib"]
[dependencies]
photon-light = {path = "../"}
glam = { version = "0.30" }
pollster = "0.4.0"
raw-window-handle = "0.6.2"
wgpu = "27.0.1"

22
ui/impl.cmake Normal file
View File

@ -0,0 +1,22 @@
set(impl_basename "${CARGO_TARGET_DIR}/release/libphoton_light_impl")
add_custom_command(
OUTPUT ${impl_basename}.a
COMMAND env CARGO_TARGET_DIR=${CARGO_TARGET_DIR} ${CARGO} build --release --package photon-light-impl
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
DEPFILE ${impl_basename}.d
USES_TERMINAL
JOB_SERVER_AWARE
DEPENDS_EXPLICIT_ONLY
)
# HACK ensure CMake *actually adds* the command above
add_custom_target(build_impl
DEPENDS ${impl_basename}.a
)
add_library(photon_light_impl STATIC IMPORTED)
set_target_properties(photon_light_impl PROPERTIES
IMPORTED_LOCATION ${impl_basename}.a
)

57
ui/src/api.cxx Normal file
View File

@ -0,0 +1,57 @@
#include "api.hxx"
#include <stdexcept>
#include <utility>
namespace ffi {
extern "C" Core* rt4_viewport_create(xcb_connection_t* connection, std::uint32_t window);
extern "C" void rt4_viewport_destroy(Core* viewport);
extern "C" void rt4_viewport_configure(Core* viewport, std::uint32_t width, std::uint32_t height);
extern "C" void rt4_viewport_redraw(Core* viewport, const RedrawArgs* args);
} // namespace ffi
BoxCore::BoxCore(BoxCore&& b)
: ptr(std::exchange(b.ptr, {})) {
}
BoxCore::~BoxCore() {
reset();
}
BoxCore& BoxCore::operator=(BoxCore&& b) {
if (&b == this)
return *this;
std::swap(ptr, b.ptr);
b.reset();
return *this;
}
BoxCore BoxCore::from_xcb(xcb_connection_t* connection, std::uint32_t window) {
if (!connection)
throw std::logic_error("attempt to use a null connection");
if (!window)
throw std::logic_error("attempt to use a null window");
BoxCore out;
out.ptr.ptr = ffi::rt4_viewport_create(connection, window);
return out;
}
void BoxCore::reset() {
auto viewport = std::exchange(ptr, {});
if (viewport)
ffi::rt4_viewport_destroy(viewport.use());
}
ffi::Core* MutCore::use() const {
if (!ptr)
throw std::logic_error("attempt to use a null Core");
return ptr;
}
void MutCore::configure(std::uint32_t width, std::uint32_t height) const {
rt4_viewport_configure(use(), width, height);
}
void MutCore::redraw(const RedrawArgs& args) const {
rt4_viewport_redraw(use(), &args);
}

59
ui/src/api.hxx Normal file
View File

@ -0,0 +1,59 @@
#pragma once
#include <cstdint>
struct xcb_connection_t;
namespace ffi {
struct Core;
struct SphericalPosition {
float yaw;
float pitch;
float distance;
};
struct RedrawArgs {
SphericalPosition camera_position;
SphericalPosition light_position;
float light_radius;
float light_spread;
};
} // namespace ffi
using ffi::RedrawArgs;
using ffi::SphericalPosition;
class MutCore {
friend class BoxCore;
public:
explicit operator bool() const { return ptr; }
void configure(std::uint32_t width, std::uint32_t height) const;
void redraw(const RedrawArgs& args) const;
private:
ffi::Core* ptr = nullptr;
ffi::Core* use() const;
};
class BoxCore {
public:
BoxCore() = default;
BoxCore(const BoxCore&) = delete;
BoxCore(BoxCore&&);
BoxCore& operator=(const BoxCore&) = delete;
BoxCore& operator=(BoxCore&&);
~BoxCore();
explicit operator bool() const { return !!ptr; }
const MutCore* operator->() const { return &ptr; }
void reset();
static BoxCore from_xcb(xcb_connection_t* connection, std::uint32_t window);
private:
MutCore ptr;
};

45
ui/src/lib.rs Normal file
View File

@ -0,0 +1,45 @@
use std::{ffi::c_void, num::NonZero, ptr::NonNull};
use glam::uvec2;
use photon_light::{Core, RedrawArgs, init_gpu_inner};
use raw_window_handle::{RawDisplayHandle, RawWindowHandle, XcbDisplayHandle, XcbWindowHandle};
unsafe fn create_viewport(
display: impl Into<RawDisplayHandle>,
window: impl Into<RawWindowHandle>,
) -> Box<Core> {
let target = wgpu::SurfaceTargetUnsafe::RawHandle {
raw_display_handle: display.into(),
raw_window_handle: window.into(),
};
let gpu = pollster::block_on(init_gpu_inner(|instance| unsafe {
instance.create_surface_unsafe(target)
}))
.unwrap();
Box::new(Core::new(gpu))
}
#[unsafe(no_mangle)]
unsafe extern "C" fn rt4_viewport_create(
connection: NonNull<c_void>,
window: NonZero<u32>,
) -> Box<Core> {
let display = XcbDisplayHandle::new(Some(connection), 0);
let window = XcbWindowHandle::new(window);
unsafe { create_viewport(display, window) }
}
#[unsafe(no_mangle)]
unsafe extern "C" fn rt4_viewport_destroy(viewport: Box<Core>) {
drop(viewport);
}
#[unsafe(no_mangle)]
unsafe extern "C" fn rt4_viewport_configure(viewport: &mut Core, width: u32, height: u32) {
viewport.configure(uvec2(width, height));
}
#[unsafe(no_mangle)]
unsafe extern "C" fn rt4_viewport_redraw(viewport: &mut Core, args: &RedrawArgs) {
viewport.redraw(args);
}

12
ui/src/main.cxx Normal file
View File

@ -0,0 +1,12 @@
#include "main_window.hxx"
#include <QApplication>
int main(int argc, char* argv[]) {
QApplication app(argc, argv);
auto w = new PhotonLight;
w->show();
return app.exec();
}

35
ui/src/main_window.cxx Normal file
View File

@ -0,0 +1,35 @@
#include "main_window.hxx"
#include "ui_main_window.h"
PhotonLight::PhotonLight(QWidget* parent)
: QMainWindow(parent),
m_ui(new Ui::MainWindow) {
m_ui->setupUi(this);
updateView();
}
PhotonLight::~PhotonLight() = default;
float deg_to_rad(float val) {
return val * float(M_PI / 180);
}
void PhotonLight::updateView() {
m_ui->viewport->setView(RedrawArgs{
.camera_position = SphericalPosition{
.yaw = deg_to_rad(m_ui->cameraYaw->value()),
.pitch = deg_to_rad(m_ui->cameraPitch->value()),
.distance = 3.0,
},
.light_position = SphericalPosition{
.yaw = deg_to_rad(m_ui->lightYaw->value()),
.pitch = deg_to_rad(m_ui->lightPitch->value()),
.distance = 1.0,
},
.light_radius = 0.125,
.light_spread = 0.125,
});
}
#include "moc_main_window.cpp"

22
ui/src/main_window.hxx Normal file
View File

@ -0,0 +1,22 @@
#pragma once
#include <QMainWindow>
#include <memory>
namespace Ui {
class MainWindow;
}
class PhotonLight : public QMainWindow {
Q_OBJECT
public:
explicit PhotonLight(QWidget* parent = nullptr);
~PhotonLight() override;
public slots:
void updateView();
private:
const std::unique_ptr<Ui::MainWindow> m_ui;
};

260
ui/src/main_window.ui Normal file
View File

@ -0,0 +1,260 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="Viewport" name="viewport" native="true"/>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>38</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
<widget class="QDockWidget" name="dockWidget">
<property name="features">
<set>QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable</set>
</property>
<attribute name="dockWidgetArea">
<number>2</number>
</attribute>
<widget class="QWidget" name="dockWidgetContents">
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QGroupBox" name="groupBox">
<property name="title">
<string>Camera</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Yaw</string>
</property>
</widget>
</item>
<item>
<widget class="QSlider" name="cameraYaw">
<property name="minimum">
<number>-180</number>
</property>
<property name="maximum">
<number>180</number>
</property>
<property name="pageStep">
<number>15</number>
</property>
<property name="value">
<number>45</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>Pitch</string>
</property>
</widget>
</item>
<item>
<widget class="QSlider" name="cameraPitch">
<property name="minimum">
<number>-90</number>
</property>
<property name="maximum">
<number>90</number>
</property>
<property name="pageStep">
<number>15</number>
</property>
<property name="value">
<number>35</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox_2">
<property name="title">
<string>Light</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QLabel" name="label_3">
<property name="text">
<string>Yaw</string>
</property>
</widget>
</item>
<item>
<widget class="QSlider" name="lightYaw">
<property name="minimum">
<number>-180</number>
</property>
<property name="maximum">
<number>180</number>
</property>
<property name="pageStep">
<number>15</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_4">
<property name="text">
<string>Pitch</string>
</property>
</widget>
</item>
<item>
<widget class="QSlider" name="lightPitch">
<property name="minimum">
<number>-90</number>
</property>
<property name="maximum">
<number>90</number>
</property>
<property name="pageStep">
<number>15</number>
</property>
<property name="value">
<number>60</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="invertedAppearance">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>385</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</widget>
</widget>
<customwidgets>
<customwidget>
<class>Viewport</class>
<extends>QWidget</extends>
<header>viewport.hxx</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>cameraYaw</sender>
<signal>valueChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>688</x>
<y>159</y>
</hint>
<hint type="destinationlabel">
<x>403</x>
<y>362</y>
</hint>
</hints>
</connection>
<connection>
<sender>cameraPitch</sender>
<signal>valueChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>688</x>
<y>215</y>
</hint>
<hint type="destinationlabel">
<x>403</x>
<y>362</y>
</hint>
</hints>
</connection>
<connection>
<sender>lightYaw</sender>
<signal>valueChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>688</x>
<y>319</y>
</hint>
<hint type="destinationlabel">
<x>403</x>
<y>362</y>
</hint>
</hints>
</connection>
<connection>
<sender>lightPitch</sender>
<signal>valueChanged(int)</signal>
<receiver>MainWindow</receiver>
<slot>updateView()</slot>
<hints>
<hint type="sourcelabel">
<x>688</x>
<y>375</y>
</hint>
<hint type="destinationlabel">
<x>403</x>
<y>362</y>
</hint>
</hints>
</connection>
</connections>
<slots>
<slot>updateView()</slot>
</slots>
</ui>

74
ui/src/viewport.cxx Normal file
View File

@ -0,0 +1,74 @@
#include "viewport.hxx"
#include <QApplication>
#include <QEvent>
#include <QGuiApplication>
Viewport::Viewport(QWidget* parent, Qt::WindowFlags f)
: QWidget(parent, f) {
setAttribute(Qt::WA_DontCreateNativeAncestors);
setAttribute(Qt::WA_NativeWindow);
setAttribute(Qt::WA_PaintOnScreen);
setAttribute(Qt::WA_NoSystemBackground);
}
Viewport::~Viewport() = default;
void Viewport::setView(RedrawArgs new_args) {
args = new_args;
update();
}
QPaintEngine* Viewport::paintEngine() const {
return nullptr;
}
bool Viewport::event(QEvent* event) {
switch (event->type()) {
case QEvent::Type::WinIdChange:
recreate();
break;
default:
break;
}
return QWidget::event(event);
}
void Viewport::paintEvent(QPaintEvent* event) {
if (!core)
recreate();
core->redraw(args);
}
void Viewport::resizeEvent(QResizeEvent* event) {
if (!core)
return;
updateSize();
QWidget::resizeEvent(event);
}
void Viewport::recreate() try {
auto* app = qobject_cast<QGuiApplication*>(QApplication::instance());
if (!app)
throw std::runtime_error("not a GUI application (WTF?)");
auto* native = app->nativeInterface<QNativeInterface::QX11Application>();
if (!native)
throw std::runtime_error("X11 interface is not available");
auto* xcb_connection = native->connection();
std::uint32_t x11_window = winId();
fprintf(stderr, "connection %p, window %#08x\n", xcb_connection, x11_window);
core.reset();
core = BoxCore::from_xcb(xcb_connection, x11_window);
updateSize();
} catch (const std::exception& e) {
fprintf(stderr, "failed to recreate the viewport: %s", e.what());
}
void Viewport::updateSize() {
const QSize device_size = size() * devicePixelRatio();
core->configure(device_size.width(), device_size.height());
}

28
ui/src/viewport.hxx Normal file
View File

@ -0,0 +1,28 @@
#pragma once
#include <QWidget>
#include "api.hxx"
class Viewport : public QWidget {
Q_OBJECT
public:
explicit Viewport(QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags());
~Viewport() override;
QPaintEngine* paintEngine() const override;
void setView(RedrawArgs new_args);
protected:
bool event(QEvent* event) override;
void paintEvent(QPaintEvent* event) override;
void resizeEvent(QResizeEvent* event) override;
private:
BoxCore core;
RedrawArgs args = {};
void recreate();
void updateSize();
};