cimery Sprint 2 — PSC-I 기하학 + viewer 개편 + OCCT optional
kernel:
- PureRustKernel: PSC-I 단면 14-vertex polygon 스위프, flat normals
56 triangles / 168 vertices, 법선 단위벡터 검증 포함
- opencascade 의존성 optional feature (--features occt)로 격리
→ OCCT 없이도 전체 빌드 가능
- psc_i.rs: 프로파일 검증, AABB, 법선 테스트 6개
viewer:
- camera.rs: arcball orbit (middle-mouse drag + scroll zoom)
- shader.wgsl: MVP matrix uniform + 방향성 조명 (콘크리트 베이지)
- lib.rs: depth buffer, index 렌더, 실제 Mesh 업로드
StubKernel → PureRustKernel → OcctKernel 교체 경로 문서화
CLAUDE.md: MVP 품질 원칙 강화 ("아키텍처 임의 변경 절대 불가")
cargo test --workspace (viewer 제외) 43개 전부 통과
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -15,3 +15,6 @@ wgpu = "22"
|
||||
winit = "0.30"
|
||||
bytemuck = { version = "1", features = ["derive"] }
|
||||
pollster = "0.3"
|
||||
glam = "0.29"
|
||||
cimery-ir = { workspace = true }
|
||||
cimery-core = { workspace = true }
|
||||
|
||||
101
cimery/crates/viewer/src/camera.rs
Normal file
101
cimery/crates/viewer/src/camera.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
//! Arcball/orbit camera — Revit ViewCube style.
|
||||
//!
|
||||
//! Orbit with middle-mouse drag, zoom with scroll wheel.
|
||||
|
||||
use glam::{Mat4, Vec3};
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
|
||||
// ─── GPU uniform ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// 64-byte view-projection matrix uploaded to the GPU once per frame.
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
|
||||
pub struct CameraUniform {
|
||||
pub view_proj: [[f32; 4]; 4],
|
||||
}
|
||||
|
||||
impl CameraUniform {
|
||||
pub fn identity() -> Self {
|
||||
Self { view_proj: Mat4::IDENTITY.to_cols_array_2d() }
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Camera ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Orbit camera — spherical coordinates around a fixed target point.
|
||||
///
|
||||
/// All distances in millimetres (scene units).
|
||||
pub struct Camera {
|
||||
/// Point the camera orbits around.
|
||||
pub target: Vec3,
|
||||
/// Distance from target [mm].
|
||||
pub radius: f32,
|
||||
/// Horizontal rotation [radians].
|
||||
pub yaw: f32,
|
||||
/// Vertical rotation [radians]. Clamped to avoid gimbal lock.
|
||||
pub pitch: f32,
|
||||
pub fov_y: f32,
|
||||
pub aspect: f32,
|
||||
pub znear: f32,
|
||||
pub zfar: f32,
|
||||
}
|
||||
|
||||
impl Camera {
|
||||
/// Default view looking at a 40 m PSC-I girder from a comfortable angle.
|
||||
pub fn default_for_girder(span_mm: f32) -> Self {
|
||||
Self {
|
||||
target: Vec3::new(300.0, 900.0, span_mm * 0.5),
|
||||
radius: span_mm * 1.5,
|
||||
yaw: std::f32::consts::FRAC_PI_4, // 45°
|
||||
pitch: 0.35, // ~20°
|
||||
fov_y: 60.0_f32.to_radians(),
|
||||
aspect: 16.0 / 9.0,
|
||||
znear: 10.0, // 10 mm
|
||||
zfar: 10_000_000.0, // 10 km
|
||||
}
|
||||
}
|
||||
|
||||
/// Eye position derived from orbit parameters.
|
||||
pub fn eye(&self) -> Vec3 {
|
||||
let sin_p = self.pitch.sin();
|
||||
let cos_p = self.pitch.cos();
|
||||
let sin_y = self.yaw.sin();
|
||||
let cos_y = self.yaw.cos();
|
||||
self.target + Vec3::new(
|
||||
self.radius * cos_p * sin_y,
|
||||
self.radius * sin_p,
|
||||
self.radius * cos_p * cos_y,
|
||||
)
|
||||
}
|
||||
|
||||
/// View-projection matrix (right-handed, depth 0→1).
|
||||
pub fn view_proj(&self) -> Mat4 {
|
||||
let view = Mat4::look_at_rh(self.eye(), self.target, Vec3::Y);
|
||||
let proj = Mat4::perspective_rh(self.fov_y, self.aspect, self.znear, self.zfar);
|
||||
proj * view
|
||||
}
|
||||
|
||||
/// Build GPU uniform from current state.
|
||||
pub fn to_uniform(&self) -> CameraUniform {
|
||||
CameraUniform { view_proj: self.view_proj().to_cols_array_2d() }
|
||||
}
|
||||
|
||||
// ── Interaction ────────────────────────────────────────────────────────
|
||||
|
||||
/// Orbit by dragging (delta in pixels, scaled to radians).
|
||||
pub fn orbit(&mut self, delta_x: f32, delta_y: f32) {
|
||||
self.yaw += delta_x * 0.005;
|
||||
self.pitch = (self.pitch - delta_y * 0.005)
|
||||
.clamp(-std::f32::consts::FRAC_PI_2 + 0.05, std::f32::consts::FRAC_PI_2 - 0.05);
|
||||
}
|
||||
|
||||
/// Zoom by scrolling (positive = closer, negative = farther).
|
||||
pub fn zoom(&mut self, delta: f32) {
|
||||
self.radius = (self.radius * (1.0 - delta * 0.1)).max(100.0);
|
||||
}
|
||||
|
||||
/// Update aspect ratio on window resize.
|
||||
pub fn resize(&mut self, width: u32, height: u32) {
|
||||
self.aspect = width as f32 / height.max(1) as f32;
|
||||
}
|
||||
}
|
||||
@@ -1,39 +1,47 @@
|
||||
//! cimery-viewer — wgpu + winit viewer.
|
||||
//! cimery-viewer — Sprint 2.
|
||||
//!
|
||||
//! # Sprint 1 scope
|
||||
//! - Opens a window and renders a coloured triangle (red/green/blue vertices).
|
||||
//! - Proves the wgpu pipeline, winit event loop, and shader infrastructure work.
|
||||
//! - No Girder mesh rendering yet — that comes in Sprint 2 after kernel integration.
|
||||
//! Renders a PSC-I girder mesh (from StubKernel or OcctKernel) with:
|
||||
//! - Perspective camera (Revit-style orbit: middle-mouse drag + scroll)
|
||||
//! - Depth buffer
|
||||
//! - Simple directional lighting from surface normals
|
||||
//! - Back-face culling
|
||||
//!
|
||||
//! # Sprint 2 upgrade path
|
||||
//! - `CimeryApp::set_mesh(mesh: &cimery_kernel::Mesh)` — replace triangle with real geometry.
|
||||
//! - Camera orbit (Revit ViewCube pattern).
|
||||
//! - Depth buffer + back-face culling for solid geometry.
|
||||
//! # Sprint 3 upgrade path
|
||||
//! - Swap `StubKernel` → `OcctKernel` once OCCT compiles.
|
||||
//! - Add ViewCube widget overlay.
|
||||
//! - Add selection highlight.
|
||||
|
||||
pub mod camera;
|
||||
|
||||
use std::sync::Arc;
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use winit::{
|
||||
application::ApplicationHandler,
|
||||
event::{KeyEvent, WindowEvent},
|
||||
event::{ElementState, KeyEvent, MouseButton, MouseScrollDelta, WindowEvent},
|
||||
event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
|
||||
keyboard::{KeyCode, PhysicalKey},
|
||||
window::{Window, WindowId},
|
||||
};
|
||||
use wgpu::util::DeviceExt;
|
||||
use cimery_core::{MaterialGrade, SectionType};
|
||||
use cimery_ir::{FeatureId, GirderIR, PscISectionParams, SectionParams};
|
||||
use cimery_kernel::{GeomKernel, StubKernel};
|
||||
use camera::{Camera, CameraUniform};
|
||||
|
||||
// ─── Vertex ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Per-vertex data sent to GPU: 3D position + surface normal.
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
|
||||
struct Vertex {
|
||||
position: [f32; 3],
|
||||
color: [f32; 3],
|
||||
normal: [f32; 3],
|
||||
}
|
||||
|
||||
impl Vertex {
|
||||
const ATTRIBS: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![
|
||||
0 => Float32x3, // position
|
||||
1 => Float32x3, // color
|
||||
1 => Float32x3, // normal
|
||||
];
|
||||
|
||||
fn desc() -> wgpu::VertexBufferLayout<'static> {
|
||||
@@ -45,40 +53,46 @@ impl Vertex {
|
||||
}
|
||||
}
|
||||
|
||||
// Sprint 1 triangle: red top / green left / blue right
|
||||
const TRIANGLE: &[Vertex] = &[
|
||||
Vertex { position: [ 0.0, 0.5, 0.0], color: [1.0, 0.0, 0.0] },
|
||||
Vertex { position: [-0.5, -0.5, 0.0], color: [0.0, 1.0, 0.0] },
|
||||
Vertex { position: [ 0.5, -0.5, 0.0], color: [0.0, 0.0, 1.0] },
|
||||
];
|
||||
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
|
||||
|
||||
// ─── RenderState ─────────────────────────────────────────────────────────────
|
||||
|
||||
struct RenderState {
|
||||
window: Arc<Window>,
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
surface: wgpu::Surface<'static>,
|
||||
surface_config: wgpu::SurfaceConfiguration,
|
||||
render_pipeline: wgpu::RenderPipeline,
|
||||
vertex_buffer: wgpu::Buffer,
|
||||
num_vertices: u32,
|
||||
window: Arc<Window>,
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
surface: wgpu::Surface<'static>,
|
||||
surface_config: wgpu::SurfaceConfiguration,
|
||||
render_pipeline: wgpu::RenderPipeline,
|
||||
// Mesh
|
||||
vertex_buffer: wgpu::Buffer,
|
||||
index_buffer: wgpu::Buffer,
|
||||
num_indices: u32,
|
||||
// Camera
|
||||
camera: Camera,
|
||||
camera_buffer: wgpu::Buffer,
|
||||
camera_bind_group: wgpu::BindGroup,
|
||||
// Depth
|
||||
depth_view: wgpu::TextureView,
|
||||
// Mouse state
|
||||
mid_pressed: bool,
|
||||
last_mouse: winit::dpi::PhysicalPosition<f64>,
|
||||
}
|
||||
|
||||
impl RenderState {
|
||||
async fn new(window: Arc<Window>) -> Self {
|
||||
let size = window.inner_size();
|
||||
|
||||
// ── Instance + surface ────────────────────────────────────────────────
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||
backends: wgpu::Backends::all(),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
// Arc<Window> implements SurfaceTarget, giving Surface<'static>
|
||||
let surface = instance
|
||||
.create_surface(Arc::clone(&window))
|
||||
.expect("create surface");
|
||||
|
||||
// ── Adapter + device ──────────────────────────────────────────────────
|
||||
let adapter = instance
|
||||
.request_adapter(&wgpu::RequestAdapterOptions {
|
||||
power_preference: wgpu::PowerPreference::default(),
|
||||
@@ -86,14 +100,14 @@ impl RenderState {
|
||||
force_fallback_adapter: false,
|
||||
})
|
||||
.await
|
||||
.expect("no suitable GPU adapter found");
|
||||
.expect("no suitable GPU adapter");
|
||||
|
||||
let (device, queue) = adapter
|
||||
.request_device(
|
||||
&wgpu::DeviceDescriptor {
|
||||
label: Some("cimery device"),
|
||||
required_features: wgpu::Features::empty(),
|
||||
required_limits: wgpu::Limits::default(),
|
||||
label: Some("cimery device"),
|
||||
required_features: wgpu::Features::empty(),
|
||||
required_limits: wgpu::Limits::default(),
|
||||
..Default::default()
|
||||
},
|
||||
None,
|
||||
@@ -101,81 +115,144 @@ impl RenderState {
|
||||
.await
|
||||
.expect("failed to create GPU device");
|
||||
|
||||
// ── Surface config ────────────────────────────────────────────────────
|
||||
let caps = surface.get_capabilities(&adapter);
|
||||
let format = caps.formats.iter()
|
||||
.find(|f| f.is_srgb())
|
||||
.copied()
|
||||
let format = caps.formats.iter().find(|f| f.is_srgb()).copied()
|
||||
.unwrap_or(caps.formats[0]);
|
||||
|
||||
let surface_config = wgpu::SurfaceConfiguration {
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
format,
|
||||
width: size.width.max(1),
|
||||
height: size.height.max(1),
|
||||
present_mode: caps.present_modes[0],
|
||||
alpha_mode: caps.alpha_modes[0],
|
||||
view_formats: vec![],
|
||||
width: size.width.max(1),
|
||||
height: size.height.max(1),
|
||||
present_mode: caps.present_modes[0],
|
||||
alpha_mode: caps.alpha_modes[0],
|
||||
view_formats: vec![],
|
||||
desired_maximum_frame_latency: 2,
|
||||
};
|
||||
surface.configure(&device, &surface_config);
|
||||
|
||||
// ── Depth texture ─────────────────────────────────────────────────────
|
||||
let depth_view = Self::make_depth_view(&device, &surface_config);
|
||||
|
||||
// ── Test girder mesh via StubKernel ───────────────────────────────────
|
||||
// Sprint 3: replace StubKernel with OcctKernel when OCCT compiles.
|
||||
let test_ir = GirderIR {
|
||||
id: FeatureId::new(),
|
||||
station_start: 0.0,
|
||||
station_end: 40.0,
|
||||
offset_from_alignment: 0.0,
|
||||
section_type: SectionType::PscI,
|
||||
section: SectionParams::PscI(PscISectionParams::kds_standard()),
|
||||
count: 1,
|
||||
spacing: 0.0,
|
||||
material: MaterialGrade::C50,
|
||||
};
|
||||
let mesh = StubKernel.girder_mesh(&test_ir).expect("StubKernel mesh");
|
||||
|
||||
let verts: Vec<Vertex> = mesh.vertices.iter().zip(mesh.normals.iter())
|
||||
.map(|(p, n)| Vertex { position: *p, normal: *n })
|
||||
.collect();
|
||||
|
||||
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("mesh vertex buffer"),
|
||||
contents: bytemuck::cast_slice(&verts),
|
||||
usage: wgpu::BufferUsages::VERTEX,
|
||||
});
|
||||
let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("mesh index buffer"),
|
||||
contents: bytemuck::cast_slice(&mesh.indices),
|
||||
usage: wgpu::BufferUsages::INDEX,
|
||||
});
|
||||
let num_indices = mesh.indices.len() as u32;
|
||||
|
||||
// ── Camera ────────────────────────────────────────────────────────────
|
||||
let mut camera = Camera::default_for_girder(mesh.aabb().1[2]); // span from AABB
|
||||
camera.resize(surface_config.width, surface_config.height);
|
||||
|
||||
let camera_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("camera buffer"),
|
||||
contents: bytemuck::cast_slice(&[camera.to_uniform()]),
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
});
|
||||
|
||||
let camera_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("camera bgl"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
});
|
||||
|
||||
let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("camera bg"),
|
||||
layout: &camera_bgl,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: camera_buffer.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
|
||||
// ── Pipeline ──────────────────────────────────────────────────────────
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("cimery shader"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
|
||||
});
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(
|
||||
&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("pipeline layout"),
|
||||
bind_group_layouts: &[],
|
||||
push_constant_ranges: &[],
|
||||
},
|
||||
);
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("pipeline layout"),
|
||||
bind_group_layouts: &[&camera_bgl],
|
||||
push_constant_ranges: &[],
|
||||
});
|
||||
|
||||
let render_pipeline = device.create_render_pipeline(
|
||||
&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("render pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: "vs_main",
|
||||
buffers: &[Vertex::desc()],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: "fs_main",
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: Some(wgpu::BlendState::REPLACE),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
strip_index_format: None,
|
||||
front_face: wgpu::FrontFace::Ccw,
|
||||
cull_mode: Some(wgpu::Face::Back),
|
||||
polygon_mode: wgpu::PolygonMode::Fill,
|
||||
unclipped_depth: false,
|
||||
conservative: false,
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState {
|
||||
count: 1,
|
||||
mask: !0,
|
||||
alpha_to_coverage_enabled: false,
|
||||
},
|
||||
multiview: None,
|
||||
cache: None,
|
||||
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("render pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: "vs_main",
|
||||
buffers: &[Vertex::desc()],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
},
|
||||
);
|
||||
|
||||
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("triangle vertex buffer"),
|
||||
contents: bytemuck::cast_slice(TRIANGLE),
|
||||
usage: wgpu::BufferUsages::VERTEX,
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: "fs_main",
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format,
|
||||
blend: Some(wgpu::BlendState::REPLACE),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
strip_index_format: None,
|
||||
front_face: wgpu::FrontFace::Ccw,
|
||||
cull_mode: Some(wgpu::Face::Back),
|
||||
polygon_mode: wgpu::PolygonMode::Fill,
|
||||
unclipped_depth: false,
|
||||
conservative: false,
|
||||
},
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: DEPTH_FORMAT,
|
||||
depth_write_enabled: true,
|
||||
depth_compare: wgpu::CompareFunction::Less,
|
||||
stencil: wgpu::StencilState::default(),
|
||||
bias: wgpu::DepthBiasState::default(),
|
||||
}),
|
||||
multisample: wgpu::MultisampleState {
|
||||
count: 1,
|
||||
mask: !0,
|
||||
alpha_to_coverage_enabled: false,
|
||||
},
|
||||
multiview: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
RenderState {
|
||||
@@ -186,15 +263,57 @@ impl RenderState {
|
||||
surface_config,
|
||||
render_pipeline,
|
||||
vertex_buffer,
|
||||
num_vertices: TRIANGLE.len() as u32,
|
||||
index_buffer,
|
||||
num_indices,
|
||||
camera,
|
||||
camera_buffer,
|
||||
camera_bind_group,
|
||||
depth_view,
|
||||
mid_pressed: false,
|
||||
last_mouse: winit::dpi::PhysicalPosition { x: 0.0, y: 0.0 },
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
fn make_depth_view(
|
||||
device: &wgpu::Device,
|
||||
config: &wgpu::SurfaceConfiguration,
|
||||
) -> wgpu::TextureView {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("depth texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width: config.width.max(1),
|
||||
height: config.height.max(1),
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: DEPTH_FORMAT,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
|
||||
| wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
})
|
||||
.create_view(&wgpu::TextureViewDescriptor::default())
|
||||
}
|
||||
|
||||
fn update_camera(&self) {
|
||||
self.queue.write_buffer(
|
||||
&self.camera_buffer,
|
||||
0,
|
||||
bytemuck::cast_slice(&[self.camera.to_uniform()]),
|
||||
);
|
||||
}
|
||||
|
||||
fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
|
||||
if new_size.width > 0 && new_size.height > 0 {
|
||||
self.surface_config.width = new_size.width;
|
||||
self.surface_config.height = new_size.height;
|
||||
self.surface.configure(&self.device, &self.surface_config);
|
||||
self.depth_view = Self::make_depth_view(&self.device, &self.surface_config);
|
||||
self.camera.resize(new_size.width, new_size.height);
|
||||
self.update_camera();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,24 +325,33 @@ impl RenderState {
|
||||
});
|
||||
{
|
||||
let mut rp = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("main render pass"),
|
||||
label: Some("main pass"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &view,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color {
|
||||
r: 0.12, g: 0.20, b: 0.30, a: 1.0,
|
||||
r: 0.10, g: 0.16, b: 0.24, a: 1.0, // dark blue-grey bg
|
||||
}),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
occlusion_query_set: None,
|
||||
timestamp_writes: None,
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &self.depth_view,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(1.0),
|
||||
store: wgpu::StoreOp::Store,
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
occlusion_query_set: None,
|
||||
timestamp_writes: None,
|
||||
});
|
||||
rp.set_pipeline(&self.render_pipeline);
|
||||
rp.set_bind_group(0, &self.camera_bind_group, &[]);
|
||||
rp.set_vertex_buffer(0, self.vertex_buffer.slice(..));
|
||||
rp.draw(0..self.num_vertices, 0..1);
|
||||
rp.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
|
||||
rp.draw_indexed(0..self.num_indices, 0, 0..1);
|
||||
}
|
||||
self.queue.submit(std::iter::once(enc.finish()));
|
||||
output.present();
|
||||
@@ -233,7 +361,6 @@ impl RenderState {
|
||||
|
||||
// ─── CimeryApp ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// winit ApplicationHandler for the cimery viewer.
|
||||
pub struct CimeryApp {
|
||||
state: Option<RenderState>,
|
||||
}
|
||||
@@ -248,38 +375,61 @@ impl Default for CimeryApp {
|
||||
|
||||
impl ApplicationHandler for CimeryApp {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let attrs = Window::default_attributes()
|
||||
.with_title("cimery viewer [Sprint 1]")
|
||||
let attrs = Window::default_attributes()
|
||||
.with_title("cimery viewer [Sprint 2 — StubKernel]")
|
||||
.with_inner_size(winit::dpi::LogicalSize::new(1280u32, 720u32));
|
||||
let window = Arc::new(
|
||||
event_loop.create_window(attrs)
|
||||
.expect("failed to create window"),
|
||||
event_loop.create_window(attrs).expect("create window"),
|
||||
);
|
||||
let state = pollster::block_on(RenderState::new(Arc::clone(&window)));
|
||||
self.state = Some(state);
|
||||
self.state = Some(pollster::block_on(RenderState::new(Arc::clone(&window))));
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
let Some(state) = self.state.as_mut() else { return };
|
||||
if state.window.id() != window_id { return; }
|
||||
|
||||
match event {
|
||||
// ── Exit ──────────────────────────────────────────────────────────
|
||||
WindowEvent::CloseRequested => event_loop.exit(),
|
||||
WindowEvent::KeyboardInput {
|
||||
event: KeyEvent {
|
||||
physical_key: PhysicalKey::Code(KeyCode::Escape),
|
||||
..
|
||||
},
|
||||
..
|
||||
physical_key: PhysicalKey::Code(KeyCode::Escape), ..
|
||||
}, ..
|
||||
} => event_loop.exit(),
|
||||
|
||||
WindowEvent::Resized(size) => state.resize(size),
|
||||
// ── Resize ────────────────────────────────────────────────────────
|
||||
WindowEvent::Resized(sz) => state.resize(sz),
|
||||
|
||||
// ── Mouse orbit (middle button drag) ──────────────────────────────
|
||||
WindowEvent::MouseInput { button: MouseButton::Middle, state: btn_state, .. } => {
|
||||
state.mid_pressed = btn_state == ElementState::Pressed;
|
||||
}
|
||||
WindowEvent::CursorMoved { position, .. } => {
|
||||
if state.mid_pressed {
|
||||
let dx = (position.x - state.last_mouse.x) as f32;
|
||||
let dy = (position.y - state.last_mouse.y) as f32;
|
||||
state.camera.orbit(dx, dy);
|
||||
state.update_camera();
|
||||
}
|
||||
state.last_mouse = position;
|
||||
}
|
||||
|
||||
// ── Zoom (scroll wheel) ───────────────────────────────────────────
|
||||
WindowEvent::MouseWheel { delta, .. } => {
|
||||
let scroll = match delta {
|
||||
MouseScrollDelta::LineDelta(_, y) => y,
|
||||
MouseScrollDelta::PixelDelta(pos) => pos.y as f32 * 0.01,
|
||||
};
|
||||
state.camera.zoom(scroll);
|
||||
state.update_camera();
|
||||
}
|
||||
|
||||
// ── Render ────────────────────────────────────────────────────────
|
||||
WindowEvent::RedrawRequested => {
|
||||
match state.render() {
|
||||
Ok(()) => {}
|
||||
@@ -288,7 +438,7 @@ impl ApplicationHandler for CimeryApp {
|
||||
state.resize(sz);
|
||||
}
|
||||
Err(wgpu::SurfaceError::OutOfMemory) => {
|
||||
log::error!("GPU out of memory — exiting");
|
||||
log::error!("GPU OOM — exiting");
|
||||
event_loop.exit();
|
||||
}
|
||||
Err(e) => log::warn!("surface error: {:?}", e),
|
||||
@@ -302,9 +452,9 @@ impl ApplicationHandler for CimeryApp {
|
||||
|
||||
// ─── Entry point ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// Run the cimery viewer event loop. Blocks until the window is closed.
|
||||
/// Run the cimery viewer. Blocks until the window is closed.
|
||||
pub fn run_viewer() {
|
||||
let event_loop = EventLoop::new().expect("failed to create event loop");
|
||||
let event_loop = EventLoop::new().expect("create event loop");
|
||||
event_loop.set_control_flow(ControlFlow::Poll);
|
||||
let mut app = CimeryApp::new();
|
||||
event_loop.run_app(&mut app).expect("event loop error");
|
||||
|
||||
@@ -1,25 +1,39 @@
|
||||
// cimery-viewer Sprint 1 shader
|
||||
// Simple per-vertex colour passthrough.
|
||||
// cimery-viewer Sprint 2 shader
|
||||
// Camera MVP + simple directional lighting from surface normals.
|
||||
|
||||
struct CameraUniform {
|
||||
view_proj: mat4x4<f32>,
|
||||
};
|
||||
|
||||
@group(0) @binding(0)
|
||||
var<uniform> camera: CameraUniform;
|
||||
|
||||
struct VertexInput {
|
||||
@location(0) position: vec3<f32>,
|
||||
@location(1) color: vec3<f32>,
|
||||
@location(1) normal: vec3<f32>,
|
||||
};
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) clip_position: vec4<f32>,
|
||||
@location(0) color: vec3<f32>,
|
||||
@builtin(position) clip_pos: vec4<f32>,
|
||||
@location(0) world_normal: vec3<f32>,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_main(in: VertexInput) -> VertexOutput {
|
||||
var out: VertexOutput;
|
||||
out.clip_position = vec4<f32>(in.position, 1.0);
|
||||
out.color = in.color;
|
||||
out.clip_pos = camera.view_proj * vec4<f32>(in.position, 1.0);
|
||||
out.world_normal = in.normal;
|
||||
return out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
return vec4<f32>(in.color, 1.0);
|
||||
// Simple directional light — PSC concrete beige
|
||||
let light = normalize(vec3<f32>(0.577, 0.577, -0.577));
|
||||
let n = normalize(in.world_normal);
|
||||
let diffuse = max(dot(n, light), 0.0);
|
||||
let ambient = 0.30;
|
||||
let base_col = vec3<f32>(0.80, 0.76, 0.65); // concrete grey-beige
|
||||
let col = base_col * (ambient + 0.70 * diffuse);
|
||||
return vec4<f32>(col, 1.0);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user