-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
740 lines (654 loc) · 26.6 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
use std::{borrow::Cow, iter::once, mem::size_of, time::Instant};
use bytemuck::cast_slice;
use bytemuck_derive::{Pod, Zeroable};
use futures::executor::block_on;
use glam::{Mat4, Quat, Vec3, Vec4};
use wgpu::{
util::{BufferInitDescriptor, DeviceExt},
Backends, BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor, BindGroupLayoutEntry,
BindingType, BufferBindingType, BufferDescriptor, BufferSize, BufferUsages, Color,
CommandEncoderDescriptor, CompareFunction, DepthBiasState, DepthStencilState, Device,
DeviceDescriptor, Extent3d, Face, Features, FragmentState, IndexFormat, InstanceDescriptor,
LoadOp, MultisampleState, Operations, PipelineLayoutDescriptor, PowerPreference, PresentMode,
PrimitiveState, RenderPassColorAttachment, RenderPassDepthStencilAttachment,
RenderPassDescriptor, RenderPipelineDescriptor, RequestAdapterOptions, ShaderModuleDescriptor,
ShaderSource, ShaderStages, StencilState, SurfaceConfiguration, Texture, TextureDescriptor,
TextureDimension, TextureFormat, TextureUsages, TextureView, TextureViewDescriptor,
VertexAttribute, VertexBufferLayout, VertexFormat, VertexState, VertexStepMode,
};
use wgpu_samples::camera::{Camera, CameraDescriptor, GpuCamera};
use winit::{
dpi::LogicalSize,
event::{DeviceEvent, ElementState, Event, MouseScrollDelta, VirtualKeyCode, WindowEvent},
event_loop::EventLoop,
platform::run_return::EventLoopExtRunReturn,
window::{CursorGrabMode, WindowBuilder},
};
const SCREEN_WIDTH: u32 = 1280;
const SCREEN_HEIGHT: u32 = 720;
const TITLE: &str = "Materials";
const VERTICES: [Vertex; 24] = [
// Front
Vertex::new(Vec3::new(-0.5, 0.5, 0.5), Vec3::new(0.0, 0.0, 1.0)), // top left
Vertex::new(Vec3::new(-0.5, -0.5, 0.5), Vec3::new(0.0, 0.0, 1.0)), // bottom left
Vertex::new(Vec3::new(0.5, -0.5, 0.5), Vec3::new(0.0, 0.0, 1.0)), // bottom right
Vertex::new(Vec3::new(0.5, 0.5, 0.5), Vec3::new(0.0, 0.0, 1.0)), // top right
// Back
Vertex::new(Vec3::new(0.5, 0.5, -0.5), Vec3::new(0.0, 0.0, -1.0)), // top left
Vertex::new(Vec3::new(0.5, -0.5, -0.5), Vec3::new(0.0, 0.0, -1.0)), // bottom left
Vertex::new(Vec3::new(-0.5, -0.5, -0.5), Vec3::new(0.0, 0.0, -1.0)), // bottom right
Vertex::new(Vec3::new(-0.5, 0.5, -0.5), Vec3::new(0.0, 0.0, -1.0)), // top right
// Left
Vertex::new(Vec3::new(-0.5, 0.5, -0.5), Vec3::new(-1.0, 0.0, 0.0)), // top left
Vertex::new(Vec3::new(-0.5, -0.5, -0.5), Vec3::new(-1.0, 0.0, 0.0)), // bottom left
Vertex::new(Vec3::new(-0.5, -0.5, 0.5), Vec3::new(-1.0, 0.0, 0.0)), // bottom right
Vertex::new(Vec3::new(-0.5, 0.5, 0.5), Vec3::new(-1.0, 0.0, 0.0)), // top right
// Right
Vertex::new(Vec3::new(0.5, 0.5, 0.5), Vec3::new(1.0, 0.0, 0.0)), // top left
Vertex::new(Vec3::new(0.5, -0.5, 0.5), Vec3::new(1.0, 0.0, 0.0)), // bottom left
Vertex::new(Vec3::new(0.5, -0.5, -0.5), Vec3::new(1.0, 0.0, 0.0)), // bottom right
Vertex::new(Vec3::new(0.5, 0.5, -0.5), Vec3::new(1.0, 0.0, 0.0)), // top right
// Top
Vertex::new(Vec3::new(-0.5, 0.5, -0.5), Vec3::new(0.0, 1.0, 0.0)), // top left
Vertex::new(Vec3::new(-0.5, 0.5, 0.5), Vec3::new(0.0, 1.0, 0.0)), // bottom left
Vertex::new(Vec3::new(0.5, 0.5, 0.5), Vec3::new(0.0, 1.0, 0.0)), // bottom right
Vertex::new(Vec3::new(0.5, 0.5, -0.5), Vec3::new(0.0, 1.0, 0.0)), // top right
// Bottom
Vertex::new(Vec3::new(-0.5, -0.5, 0.5), Vec3::new(0.0, -1.0, 0.0)), // top left
Vertex::new(Vec3::new(-0.5, -0.5, -0.5), Vec3::new(0.0, -1.0, 0.0)), // bottom left
Vertex::new(Vec3::new(0.5, -0.5, -0.5), Vec3::new(0.0, -1.0, 0.0)), // bottom right
Vertex::new(Vec3::new(0.5, -0.5, 0.5), Vec3::new(0.0, -1.0, 0.0)), // top right
];
const INDICES: [u32; 36] = [
0, 1, 3, 1, 2, 3, // front
4, 5, 7, 5, 6, 7, // back
8, 9, 11, 9, 10, 11, // left
12, 13, 15, 13, 14, 15, // right
16, 17, 19, 17, 18, 19, // top
20, 21, 23, 21, 22, 23, // bottom
];
#[derive(Debug, Default, Clone, Copy, Pod, Zeroable)]
#[repr(C)]
struct Vertex {
position: [f32; 3],
normal: [f32; 3],
}
impl Vertex {
const fn new(position: Vec3, normal: Vec3) -> Self {
Self {
position: position.to_array(),
normal: normal.to_array(),
}
}
fn layout() -> VertexBufferLayout<'static> {
VertexBufferLayout {
array_stride: size_of::<Vertex>() as u64,
step_mode: VertexStepMode::Vertex,
attributes: &[
VertexAttribute {
format: VertexFormat::Float32x3,
offset: 0,
shader_location: 0,
},
VertexAttribute {
format: VertexFormat::Float32x3,
offset: size_of::<[f32; 3]>() as u64,
shader_location: 1,
},
],
}
}
}
#[derive(Debug, Default, Clone, Copy, Pod, Zeroable)]
#[repr(C)]
struct Model {
model_matrix: [f32; 16],
normal_matrix: [f32; 16],
}
impl Model {
fn new(model_matrix: Mat4) -> Self {
let normal_matrix = model_matrix.inverse().transpose();
Self {
model_matrix: model_matrix.to_cols_array(),
normal_matrix: normal_matrix.to_cols_array(),
}
}
}
#[derive(Debug, Default, Clone, Copy, Pod, Zeroable)]
#[repr(C)]
struct Material {
ambient: [f32; 4],
diffuse: [f32; 4],
specular: [f32; 4],
shininess: f32,
_pad1: f32,
_pad2: f32,
_pad3: f32,
}
impl Material {
fn new(ambient: Vec4, diffuse: Vec4, specular: Vec4, shininess: f32) -> Self {
Self {
ambient: ambient.to_array(),
diffuse: diffuse.to_array(),
specular: specular.to_array(),
shininess,
_pad1: 0.0,
_pad2: 0.0,
_pad3: 0.0,
}
}
}
#[derive(Debug, Default, Clone, Copy, Pod, Zeroable)]
#[repr(C)]
struct Light {
ambient: [f32; 4],
diffuse: [f32; 4],
specular: [f32; 4],
position: [f32; 3],
_pad1: f32,
}
impl Light {
fn new(position: Vec3, ambient: Vec4, diffuse: Vec4, specular: Vec4) -> Self {
Self {
position: position.to_array(),
ambient: ambient.to_array(),
diffuse: diffuse.to_array(),
specular: specular.to_array(),
_pad1: 0.0,
}
}
}
fn main() {
let mut event_loop = EventLoop::new();
let logical_size = LogicalSize::new(SCREEN_WIDTH, SCREEN_HEIGHT);
let window = WindowBuilder::new()
.with_inner_size(logical_size)
.with_title(TITLE)
.with_visible(false)
.build(&event_loop)
.expect("failed to create window");
let physical_size = window.inner_size();
let instance = wgpu::Instance::new(InstanceDescriptor {
backends: Backends::PRIMARY,
..Default::default()
});
let surface = unsafe {
instance
.create_surface(&window)
.expect("failed to create surface")
};
let adapter = block_on(instance.request_adapter(&RequestAdapterOptions {
power_preference: PowerPreference::LowPower,
force_fallback_adapter: false,
compatible_surface: Some(&surface),
}))
.expect("failed to get a suitable adapter");
let (device, queue) = block_on(adapter.request_device(
&DeviceDescriptor {
label: Some("device"),
features: Features::empty(),
limits: adapter.limits(),
},
None,
))
.expect("failed to get a device");
let surface_capabilities = surface.get_capabilities(&adapter);
let surface_format = if surface_capabilities
.formats
.contains(&TextureFormat::Rgba8Unorm)
{
TextureFormat::Rgba8Unorm
} else if surface_capabilities
.formats
.contains(&TextureFormat::Bgra8Unorm)
{
TextureFormat::Bgra8Unorm
} else {
surface_capabilities.formats[0]
};
let mut surface_config = SurfaceConfiguration {
usage: TextureUsages::RENDER_ATTACHMENT,
format: surface_format,
width: physical_size.width,
height: physical_size.height,
present_mode: PresentMode::Fifo,
alpha_mode: surface_capabilities.alpha_modes[0],
view_formats: Vec::new(),
};
surface.configure(&device, &surface_config);
let (mut depth_texture, mut depth_texture_view) =
create_depth_texture(&device, physical_size.width, physical_size.height);
let scene_bind_group_layout = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
label: Some("bind_group_layout::scene"),
entries: &[
BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::VERTEX_FRAGMENT,
ty: BindingType::Buffer {
ty: BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: BufferSize::new(size_of::<GpuCamera>() as u64),
},
count: None,
},
BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::FRAGMENT,
ty: BindingType::Buffer {
ty: BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: BufferSize::new(size_of::<Light>() as u64),
},
count: None,
},
],
});
let model_bind_group_layout = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
label: Some("bind_group_layout::model"),
entries: &[BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::VERTEX,
ty: BindingType::Buffer {
ty: BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: BufferSize::new(size_of::<Model>() as u64),
},
count: None,
}],
});
let material_bind_group_layout = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
label: Some("bind_group_layout::material"),
entries: &[BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::FRAGMENT,
ty: BindingType::Buffer {
ty: BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: BufferSize::new(size_of::<Material>() as u64),
},
count: None,
}],
});
let light_cube_color_bind_group_layout =
device.create_bind_group_layout(&BindGroupLayoutDescriptor {
label: Some("bind_group_layout::light_cube_color"),
entries: &[BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::FRAGMENT,
ty: BindingType::Buffer {
ty: BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: BufferSize::new(size_of::<[f32; 4]>() as u64),
},
count: None,
}],
});
let light_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
label: Some("pipeline_layout::light"),
bind_group_layouts: &[
&scene_bind_group_layout,
&model_bind_group_layout,
&light_cube_color_bind_group_layout,
],
push_constant_ranges: &[],
});
let model_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
label: Some("pipeline_layout::model"),
bind_group_layouts: &[
&scene_bind_group_layout,
&model_bind_group_layout,
&material_bind_group_layout,
],
push_constant_ranges: &[],
});
let camera_ubo = device.create_buffer(&BufferDescriptor {
label: Some("ubo::camera"),
size: size_of::<GpuCamera>() as u64,
usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let lighting_ubo = device.create_buffer(&BufferDescriptor {
label: Some("ubo::lighting"),
size: size_of::<Light>() as u64,
usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let scene_bind_group = device.create_bind_group(&BindGroupDescriptor {
label: Some("bind_group::scene"),
layout: &scene_bind_group_layout,
entries: &[
BindGroupEntry {
binding: 0,
resource: camera_ubo.as_entire_binding(),
},
BindGroupEntry {
binding: 1,
resource: lighting_ubo.as_entire_binding(),
},
],
});
let light_shader_src = include_str!("light.wgsl");
let light_shader_module = device.create_shader_module(ShaderModuleDescriptor {
label: Some("shader_module::light"),
source: ShaderSource::Wgsl(Cow::Borrowed(light_shader_src)),
});
let light_pipeline = device.create_render_pipeline(&RenderPipelineDescriptor {
label: Some("render_pipeline::light"),
layout: Some(&light_pipeline_layout),
vertex: VertexState {
module: &light_shader_module,
entry_point: "vs_main",
buffers: &[Vertex::layout()],
},
primitive: PrimitiveState {
cull_mode: Some(Face::Back),
..Default::default()
},
depth_stencil: Some(DepthStencilState {
format: TextureFormat::Depth32Float,
depth_write_enabled: true,
depth_compare: CompareFunction::Less,
stencil: StencilState::default(),
bias: DepthBiasState::default(),
}),
multisample: MultisampleState::default(),
fragment: Some(FragmentState {
module: &light_shader_module,
entry_point: "fs_main",
targets: &[Some(surface_format.into())],
}),
multiview: None,
});
let model_shader_src = include_str!("model.wgsl");
let model_shader_module = device.create_shader_module(ShaderModuleDescriptor {
label: Some("shader_module::model"),
source: ShaderSource::Wgsl(Cow::Borrowed(model_shader_src)),
});
let model_pipeline = device.create_render_pipeline(&RenderPipelineDescriptor {
label: Some("render_pipeline::model"),
layout: Some(&model_pipeline_layout),
vertex: VertexState {
module: &model_shader_module,
entry_point: "vs_main",
buffers: &[Vertex::layout()],
},
primitive: PrimitiveState {
cull_mode: Some(Face::Back),
..Default::default()
},
depth_stencil: Some(DepthStencilState {
format: TextureFormat::Depth32Float,
depth_write_enabled: true,
depth_compare: CompareFunction::Less,
stencil: StencilState::default(),
bias: DepthBiasState::default(),
}),
multisample: MultisampleState::default(),
fragment: Some(FragmentState {
module: &model_shader_module,
entry_point: "fs_main",
targets: &[Some(surface_format.into())],
}),
multiview: None,
});
let light_cube_vbo = device.create_buffer_init(&BufferInitDescriptor {
label: Some("vbo::light_cube"),
contents: cast_slice(&VERTICES),
usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
});
let light_cube_ibo = device.create_buffer_init(&BufferInitDescriptor {
label: Some("ibo::light_cube"),
contents: cast_slice(&INDICES),
usage: BufferUsages::INDEX | BufferUsages::COPY_DST,
});
let cube_vbo = device.create_buffer_init(&BufferInitDescriptor {
label: Some("vbo::cube"),
contents: cast_slice(&VERTICES),
usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
});
let cube_ibo = device.create_buffer_init(&BufferInitDescriptor {
label: Some("ibo::cube"),
contents: cast_slice(&INDICES),
usage: BufferUsages::INDEX | BufferUsages::COPY_DST,
});
let light_position = Vec3::new(1.2, 1.0, 2.0);
let light_transform = Mat4::from_scale_rotation_translation(
Vec3::new(0.2, 0.2, 0.2),
Quat::IDENTITY,
light_position,
);
let light_cube = Model::new(light_transform);
let light_cube_ubo = device.create_buffer_init(&BufferInitDescriptor {
label: Some("ubo::light_cube"),
contents: cast_slice(&[light_cube]),
usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
});
let light_cube_bind_group = device.create_bind_group(&BindGroupDescriptor {
label: Some("bind_group::light_cube"),
layout: &model_bind_group_layout,
entries: &[BindGroupEntry {
binding: 0,
resource: light_cube_ubo.as_entire_binding(),
}],
});
let light_cube_color = Vec4::new(1.0, 1.0, 1.0, 1.0);
let light_cube_color_ubo = device.create_buffer_init(&BufferInitDescriptor {
label: Some("ubo::light_color"),
contents: cast_slice(&light_cube_color.to_array()),
usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
});
let light_cube_color_bind_group = device.create_bind_group(&BindGroupDescriptor {
label: Some("bind_group::light_cube_color"),
layout: &light_cube_color_bind_group_layout,
entries: &[BindGroupEntry {
binding: 0,
resource: light_cube_color_ubo.as_entire_binding(),
}],
});
let cube_transform = Mat4::from_translation(Vec3::new(0.0, 0.0, 0.0));
let cube = Model::new(cube_transform);
let cube_ubo = device.create_buffer_init(&BufferInitDescriptor {
label: Some("vbo::cube"),
contents: cast_slice(&[cube]),
usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
});
let cube_bind_group = device.create_bind_group(&BindGroupDescriptor {
label: Some("bind_group::cube"),
layout: &model_bind_group_layout,
entries: &[BindGroupEntry {
binding: 0,
resource: cube_ubo.as_entire_binding(),
}],
});
let cube_material = Material::new(
Vec4::new(1.0, 0.5, 0.31, 1.0),
Vec4::new(1.0, 0.5, 0.31, 1.0),
Vec4::new(0.5, 0.5, 0.5, 1.0),
32.0,
);
let cube_material_ubo = device.create_buffer_init(&BufferInitDescriptor {
label: Some("ubo::cube_material"),
contents: cast_slice(&[cube_material]),
usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
});
let cube_material_bind_group = device.create_bind_group(&BindGroupDescriptor {
label: Some("bind_group::cube_material"),
layout: &material_bind_group_layout,
entries: &[BindGroupEntry {
binding: 0,
resource: cube_material_ubo.as_entire_binding(),
}],
});
let mut light = Light::new(
light_position,
Vec4::new(0.2, 0.2, 0.2, 1.0),
Vec4::new(0.5, 0.5, 0.5, 1.0),
Vec4::new(1.0, 1.0, 1.0, 1.0),
);
let mut camera = Camera::new(&CameraDescriptor {
aspect_ratio: SCREEN_WIDTH as f32 / SCREEN_HEIGHT as f32,
..Default::default()
});
window.set_cursor_visible(false);
window
.set_cursor_grab(CursorGrabMode::Confined)
.expect("failed to grab cursor");
window.set_visible(true);
let start_time = Instant::now();
let mut last_time = start_time;
let mut mouse_in_window = false;
let mut running = true;
while running {
let current_time = Instant::now();
let dt = (current_time - last_time).as_secs_f32();
last_time = current_time;
event_loop.run_return(|event, _, control_flow| {
control_flow.set_wait();
match event {
Event::WindowEvent { window_id, event } if window.id() == window_id => {
match event {
WindowEvent::CloseRequested => running = false,
WindowEvent::Resized(size) => {
surface_config.width = size.width;
surface_config.height = size.height;
surface.configure(&device, &surface_config);
(depth_texture, depth_texture_view) = create_depth_texture(
&device,
surface_config.width,
surface_config.height,
);
}
WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
surface_config.width = new_inner_size.width;
surface_config.height = new_inner_size.height;
surface.configure(&device, &surface_config);
(depth_texture, depth_texture_view) = create_depth_texture(
&device,
surface_config.width,
surface_config.height,
);
}
WindowEvent::CursorEntered { .. } => {
mouse_in_window = true;
}
WindowEvent::MouseWheel { delta, .. } => {
if let MouseScrollDelta::LineDelta(_, y) = delta {
camera.zoom(y);
}
}
WindowEvent::KeyboardInput { input, .. } => {
if let Some(key) = input.virtual_keycode {
match key {
VirtualKeyCode::Escape
if input.state == ElementState::Pressed =>
{
running = false;
}
VirtualKeyCode::W if input.state == ElementState::Pressed => {
camera.move_forward(dt);
}
VirtualKeyCode::S if input.state == ElementState::Pressed => {
camera.move_backward(dt);
}
VirtualKeyCode::A if input.state == ElementState::Pressed => {
camera.skew_left(dt);
}
VirtualKeyCode::D if input.state == ElementState::Pressed => {
camera.skew_right(dt);
}
_ => (),
}
}
}
_ => (),
}
}
Event::DeviceEvent { event, .. } if mouse_in_window => match event {
DeviceEvent::MouseMotion { delta } => {
let (x, y) = delta;
camera.yaw_pitch(x as f32, -y as f32);
}
_ => (),
},
Event::MainEventsCleared => control_flow.set_exit(),
_ => (),
}
});
let elapsed = (current_time - start_time).as_secs_f32();
let light_color = Vec4::new(
(elapsed * 2.0).sin(),
(elapsed * 0.7).sin(),
(elapsed * 1.3).sin(),
1.0,
);
light.diffuse = (light_color * Vec4::new(0.5, 0.5, 0.5, 1.0)).to_array();
light.ambient =
(Vec4::from_array(light.diffuse) * Vec4::new(0.2, 0.2, 0.2, 1.0)).to_array();
queue.write_buffer(&camera_ubo, 0, cast_slice(&[camera.get_gpu_camera()]));
queue.write_buffer(&lighting_ubo, 0, cast_slice(&[light]));
let frame = surface
.get_current_texture()
.expect("failed to get current swapchain texture");
let output_texture_view = frame.texture.create_view(&TextureViewDescriptor::default());
let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor {
label: Some("command_encoder"),
});
{
let mut rpass = encoder.begin_render_pass(&RenderPassDescriptor {
label: Some("render_pass"),
color_attachments: &[Some(RenderPassColorAttachment {
view: &output_texture_view,
resolve_target: None,
ops: Operations {
load: LoadOp::Clear(Color::BLACK),
store: true,
},
})],
depth_stencil_attachment: Some(RenderPassDepthStencilAttachment {
view: &depth_texture_view,
depth_ops: Some(Operations {
load: LoadOp::Clear(1.0),
store: true,
}),
stencil_ops: Some(Operations {
load: LoadOp::Clear(0),
store: true,
}),
}),
});
rpass.set_bind_group(0, &scene_bind_group, &[]);
rpass.set_pipeline(&light_pipeline);
rpass.set_bind_group(1, &light_cube_bind_group, &[]);
rpass.set_bind_group(2, &light_cube_color_bind_group, &[]);
rpass.set_vertex_buffer(0, light_cube_vbo.slice(..));
rpass.set_index_buffer(light_cube_ibo.slice(..), IndexFormat::Uint32);
rpass.draw_indexed(0..INDICES.len() as u32, 0, 0..1);
rpass.set_pipeline(&model_pipeline);
rpass.set_bind_group(1, &cube_bind_group, &[]);
rpass.set_bind_group(2, &cube_material_bind_group, &[]);
rpass.set_vertex_buffer(0, cube_vbo.slice(..));
rpass.set_index_buffer(cube_ibo.slice(..), IndexFormat::Uint32);
rpass.draw_indexed(0..INDICES.len() as u32, 0, 0..1);
}
queue.submit(once(encoder.finish()));
frame.present();
}
}
fn create_depth_texture(device: &Device, width: u32, height: u32) -> (Texture, TextureView) {
let texture = device.create_texture(&TextureDescriptor {
label: Some("texture::depth"),
size: Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Depth32Float,
usage: TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let texture_view = texture.create_view(&TextureViewDescriptor::default());
(texture, texture_view)
}