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
|
use std::{borrow::Cow, sync::Arc};
use wgpu::*;
use winit::{dpi::PhysicalSize, event_loop::OwnedDisplayHandle, window::Window};
mod font;
mod texture;
use font::CharAtlas;
pub enum AcquireSurfaceTextureResult {
Ok(SurfaceTexture),
ShouldSkip,
Lost,
}
pub struct Renderer {
device: Device,
queue: Queue,
surface: Surface<'static>,
surface_format: TextureFormat,
view_format: TextureFormat,
present_mode: PresentMode,
pipeline: RenderPipeline,
char_atlas: CharAtlas,
fixed_bind_group: BindGroup,
}
impl Renderer {
pub async fn new(
display: Box<OwnedDisplayHandle>,
window: Arc<Window>,
) -> Result<Self, String> {
let size = window.inner_size();
let scale_factor = window.scale_factor() as f32;
let instance = Instance::new(InstanceDescriptor::new_with_display_handle(display));
let surface = instance.create_surface(window).map_err(|e| e.to_string())?;
let adapter = instance
.request_adapter(&RequestAdapterOptions {
compatible_surface: Some(&surface),
..Default::default()
})
.await
.map_err(|e| e.to_string())?;
let (device, queue) = adapter
.request_device(&DeviceDescriptor::default())
.await
.map_err(|e| e.to_string())?;
let surface_cap = surface.get_capabilities(&adapter);
if surface_cap.formats.is_empty() {
return Err("no surface format found".to_string());
}
let (surface_format, view_format) = decide_surface_and_view_format(&adapter, &surface_cap);
let present_mode = decide_presentation_mode(&surface_cap);
let shader = device.create_shader_module(ShaderModuleDescriptor {
label: None,
source: ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
});
let fixed_bind_group_layout = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
label: None,
entries: &[
BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::FRAGMENT,
ty: BindingType::Sampler(SamplerBindingType::Filtering),
count: None,
},
BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::FRAGMENT,
ty: BindingType::Texture {
sample_type: TextureSampleType::Float { filterable: true },
view_dimension: TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
],
});
let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[Some(&fixed_bind_group_layout)],
immediate_size: 0,
});
let pipeline = device.create_render_pipeline(&RenderPipelineDescriptor {
label: None,
layout: Some(&pipeline_layout),
vertex: VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(FragmentState {
module: &shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(ColorTargetState {
format: view_format,
blend: Some(BlendState::ALPHA_BLENDING),
write_mask: ColorWrites::ALL,
})],
}),
primitive: PrimitiveState {
topology: PrimitiveTopology::TriangleStrip,
cull_mode: None,
..Default::default()
},
depth_stencil: None,
multisample: MultisampleState::default(),
multiview_mask: None,
cache: None,
});
// NOTE: 本ゲームではlinearなサンプラしか用意しないので、ここで1個だけ作成すれば良い。
let sampler = device.create_sampler(&SamplerDescriptor {
label: None,
address_mode_u: AddressMode::ClampToEdge,
address_mode_v: AddressMode::ClampToEdge,
address_mode_w: AddressMode::ClampToEdge,
mag_filter: FilterMode::Linear,
min_filter: FilterMode::Linear,
mipmap_filter: MipmapFilterMode::Linear,
..Default::default()
});
// NOTE: 文字テクスチャアトラスは使い回すので、ここで1個だけ作成すれば良い。
let char_atlas = CharAtlas::new(scale_factor, &device);
let fixed_bind_group = device.create_bind_group(&BindGroupDescriptor {
label: None,
layout: &fixed_bind_group_layout,
entries: &[
BindGroupEntry {
binding: 0,
resource: BindingResource::Sampler(&sampler),
},
BindGroupEntry {
binding: 1,
resource: BindingResource::TextureView(&char_atlas.texture.view),
},
],
});
let v = Self {
device,
queue,
surface,
surface_format,
view_format,
present_mode,
pipeline,
char_atlas,
fixed_bind_group,
};
v.configure_surface(size);
Ok(v)
}
pub fn get_current_texture(&self, window: &Window) -> AcquireSurfaceTextureResult {
match self.surface.get_current_texture() {
CurrentSurfaceTexture::Success(v) => AcquireSurfaceTextureResult::Ok(v),
CurrentSurfaceTexture::Suboptimal(v) => {
// NOTE: 取得したテクスチャが生存した状態でサーフェスを再設定すると
// `PreviousOutputExists`エラーになるので、
// 破棄した上で再設定し、描画をスキップする。
drop(v);
self.configure_surface(window.inner_size());
AcquireSurfaceTextureResult::ShouldSkip
}
CurrentSurfaceTexture::Occluded => AcquireSurfaceTextureResult::ShouldSkip,
CurrentSurfaceTexture::Timeout => AcquireSurfaceTextureResult::ShouldSkip,
CurrentSurfaceTexture::Outdated => {
self.configure_surface(window.inner_size());
AcquireSurfaceTextureResult::ShouldSkip
}
CurrentSurfaceTexture::Lost => AcquireSurfaceTextureResult::Lost,
// TODO: 一応対応する。
CurrentSurfaceTexture::Validation => unreachable!(),
}
}
pub fn render(&mut self, window: &Window, current_texture: SurfaceTexture) {
let surface_texture_view = current_texture.texture.create_view(&TextureViewDescriptor {
format: Some(self.view_format),
..Default::default()
});
let mut encoder = self.device.create_command_encoder(&Default::default());
let mut render_pass = encoder.begin_render_pass(&RenderPassDescriptor {
label: None,
color_attachments: &[Some(RenderPassColorAttachment {
view: &surface_texture_view,
depth_slice: None,
resolve_target: None,
ops: Operations {
load: LoadOp::Clear(Color::BLACK),
store: StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
render_pass.set_pipeline(&self.pipeline);
render_pass.set_bind_group(0, &self.fixed_bind_group, &[]);
// TODO: 描画
drop(render_pass);
self.queue.submit([encoder.finish()]);
window.pre_present_notify();
self.queue.present(current_texture);
}
/// サーフェスを設定するメソッド
///
/// * size - 現在のクライアントサイズ
///
/// クライアントサイズのリサイズがあったらこのメソッドを呼び出す。
/// 幅・高さいずれかが`0`である場合は何もしない。
pub fn configure_surface(&self, size: PhysicalSize<u32>) {
if size.width == 0 || size.height == 0 {
return;
}
let surface_config = SurfaceConfiguration {
usage: TextureUsages::RENDER_ATTACHMENT,
format: self.surface_format,
color_space: SurfaceColorSpace::Auto,
view_formats: if self.surface_format != self.view_format {
vec![self.view_format]
} else {
vec![]
},
alpha_mode: CompositeAlphaMode::Auto,
width: size.width,
height: size.height,
desired_maximum_frame_latency: 2,
present_mode: self.present_mode,
};
self.surface.configure(&self.device, &surface_config);
}
/// Presentation modeがFIFOか確認するメソッド
///
/// FIFOである場合はsleep+spinではなく垂直同期でスレッドを待機した方が良い。
pub fn is_presentation_mode_fifo(&self) -> bool {
self.present_mode == PresentMode::Fifo
}
}
fn decide_surface_and_view_format(
adapter: &Adapter,
cap: &SurfaceCapabilities,
) -> (TextureFormat, TextureFormat) {
// sRGBがサポートされているならsRGB
if let Some(&v) = cap.formats.iter().find(|v| v.is_srgb()) {
return (v, v);
}
let can_srgb_view = adapter
.get_downlevel_capabilities()
.flags
.contains(DownlevelFlags::SURFACE_VIEW_FORMATS);
let format = cap.formats[0];
// sRGBがサポートされていない・かつテクスチャとビューのフォーマットが一致しなくて良いなら
// テクスチャを`formats[0]`・ビューをsRGB
//
// NOTE: ビューのフォーマットに従って色変換が行われるので、
// テクスチャの実際のフォーマットが違うだけでsRGBと同様の結果になる。
if can_srgb_view {
(format, format.add_srgb_suffix())
}
// sRGBがサポートされていない・かつテクスチャとビューのフォーマットが一致する必要があるなら
// テクスチャもビューも`formats[0]`
//
// NOTE: 色変換が行われないので中間色が暗くなる。
// シェーダで自力補正してやれば解決するが、まあ余力があったらね。
else {
(format, format)
}
}
fn decide_presentation_mode(cap: &SurfaceCapabilities) -> PresentMode {
// REVIEW: 高負荷なので素直にFIFOにして垂直同期で回す方が良いかもしれない。
if cap.present_modes.contains(&PresentMode::Mailbox) {
// 垂直同期を待つフレーム上書きモード
PresentMode::Mailbox
} else if cap.present_modes.contains(&PresentMode::Immediate) {
// 垂直同期を待たないフレーム上書きモード
PresentMode::Immediate
} else {
// 垂直同期を待つフレーム保守モード
//
// NOTE: 殆どすべての環境でサポートされていることを期待して良い。
// https://wgpu.rs/doc/wgpu/enum.PresentMode.html
PresentMode::Fifo
}
}
|