veloren_voxygen/render/renderer/
mod.rs

1mod binding;
2pub(super) mod drawer;
3// Consts and bind groups for post-process and clouds
4mod locals;
5mod pipeline_creation;
6mod rain_occlusion_map;
7mod screenshot;
8mod shaders;
9mod shadow_map;
10
11use locals::Locals;
12use pipeline_creation::{
13    IngameAndShadowPipelines, InterfacePipelines, PipelineCreation, Pipelines, ShadowPipelines,
14};
15use shaders::Shaders;
16use shadow_map::{ShadowMap, ShadowMapRenderer};
17
18use self::{pipeline_creation::RainOcclusionPipelines, rain_occlusion_map::RainOcclusionMap};
19
20use super::{
21    AddressMode, FilterMode, OtherModes, PipelineModes, PresentMode, RenderError, RenderMode,
22    ShadowMapMode, ShadowMode, Vertex,
23    buffer::Buffer,
24    consts::Consts,
25    instances::Instances,
26    mesh::Mesh,
27    model::{DynamicModel, Model},
28    pipelines::{
29        GlobalsBindGroup, GlobalsLayouts, ShadowTexturesBindGroup, blit, bloom, clouds, debug,
30        figure, postprocess, rain_occlusion, rope, shadow, sprite, terrain, ui,
31    },
32    texture::Texture,
33};
34use common::assets::{self, AssetExt, AssetHandle, ReloadWatcher};
35use common_base::span;
36use core::convert::TryFrom;
37use std::sync::Arc;
38use tracing::{error, info, warn};
39use vek::*;
40
41const QUAD_INDEX_BUFFER_U16_START_VERT_LEN: u16 = 3000;
42const QUAD_INDEX_BUFFER_U32_START_VERT_LEN: u32 = 3000;
43
44/// A type that stores all the layouts associated with this renderer that never
45/// change when the RenderMode is modified.
46struct ImmutableLayouts {
47    global: GlobalsLayouts,
48
49    debug: debug::DebugLayout,
50    figure: figure::FigureLayout,
51    shadow: shadow::ShadowLayout,
52    rain_occlusion: rain_occlusion::RainOcclusionLayout,
53    sprite: sprite::SpriteLayout,
54    terrain: terrain::TerrainLayout,
55    rope: rope::RopeLayout,
56    clouds: clouds::CloudsLayout,
57    bloom: bloom::BloomLayout,
58    ui: ui::UiLayout,
59    premultiply_alpha: ui::PremultiplyAlphaLayout,
60    blit: blit::BlitLayout,
61}
62
63/// A type that stores all the layouts associated with this renderer.
64struct Layouts {
65    immutable: Arc<ImmutableLayouts>,
66
67    postprocess: Arc<postprocess::PostProcessLayout>,
68}
69
70impl core::ops::Deref for Layouts {
71    type Target = ImmutableLayouts;
72
73    fn deref(&self) -> &Self::Target { &self.immutable }
74}
75
76/// Render target views
77struct Views {
78    // NOTE: unused for now, maybe... we will want it for something
79    _win_depth: wgpu::TextureView,
80
81    tgt_color: wgpu::TextureView,
82    tgt_mat: wgpu::TextureView,
83    tgt_depth: wgpu::TextureView,
84
85    bloom_tgts: Option<[wgpu::TextureView; bloom::NUM_SIZES]>,
86    // TODO: rename
87    tgt_color_pp: wgpu::TextureView,
88}
89
90/// Shadow rendering textures, layouts, pipelines, and bind groups
91struct Shadow {
92    rain_map: RainOcclusionMap,
93    map: ShadowMap,
94    bind: ShadowTexturesBindGroup,
95}
96
97/// Represent two states of the renderer:
98/// 1. Only interface pipelines created
99/// 2. All of the pipelines have been created
100#[expect(clippy::large_enum_variant)] // They are both pretty large
101enum State {
102    // NOTE: this is used as a transient placeholder for moving things out of State temporarily
103    Nothing,
104    Interface {
105        pipelines: InterfacePipelines,
106        shadow_views: Option<(Texture, Texture)>,
107        rain_occlusion_view: Option<Texture>,
108        // In progress creation of the remaining pipelines in the background
109        creating: PipelineCreation<IngameAndShadowPipelines>,
110    },
111    Complete {
112        pipelines: Pipelines,
113        shadow: Shadow,
114        recreating: Option<(
115            PipelineModes,
116            PipelineCreation<
117                Result<
118                    (
119                        Pipelines,
120                        ShadowPipelines,
121                        RainOcclusionPipelines,
122                        Arc<postprocess::PostProcessLayout>,
123                    ),
124                    RenderError,
125                >,
126            >,
127        )>,
128    },
129}
130
131/// A type that encapsulates rendering state. `Renderer` is central to Voxygen's
132/// rendering subsystem and contains any state necessary to interact with the
133/// GPU, along with pipeline state objects (PSOs) needed to renderer different
134/// kinds of models to the screen.
135pub struct Renderer {
136    device: Arc<wgpu::Device>,
137    queue: wgpu::Queue,
138    surface: wgpu::Surface,
139    surface_config: wgpu::SurfaceConfiguration,
140
141    sampler: wgpu::Sampler,
142    depth_sampler: wgpu::Sampler,
143
144    state: State,
145    // Some if there is a pending need to recreate the pipelines (e.g. RenderMode change or shader
146    // hotloading)
147    recreation_pending: Option<PipelineModes>,
148
149    layouts: Layouts,
150    // Note: we keep these here since their bind groups need to be updated if we resize the
151    // color/depth textures
152    locals: Locals,
153    views: Views,
154    noise_tex: Texture,
155
156    quad_index_buffer_u16: Buffer<u16>,
157    quad_index_buffer_u32: Buffer<u32>,
158
159    shaders: AssetHandle<Shaders>,
160    shaders_watcher: ReloadWatcher,
161
162    pipeline_modes: PipelineModes,
163    other_modes: OtherModes,
164    resolution: Vec2<u32>,
165
166    // If this is Some then a screenshot will be taken and passed to the handler here
167    take_screenshot: Option<screenshot::ScreenshotFn>,
168
169    profiler: wgpu_profiler::GpuProfiler,
170    profile_times: Vec<wgpu_profiler::GpuTimerScopeResult>,
171    profiler_features_enabled: bool,
172
173    ui_premultiply_uploads: ui::BatchedUploads,
174
175    #[cfg(feature = "egui-ui")]
176    egui_renderpass: egui_wgpu_backend::RenderPass,
177
178    // This checks is added because windows resizes the window to 0,0 when
179    // minimizing and this causes a bunch of validation errors
180    is_minimized: bool,
181
182    // To remember the backend info after initialization for debug purposes
183    graphics_backend: String,
184
185    /// The texture format used for the intermediate rendering passes
186    intermediate_format: wgpu::TextureFormat,
187
188    /// Supported present modes.
189    present_modes: Vec<PresentMode>,
190    /// Cached max texture size.
191    max_texture_size: u32,
192}
193
194impl Renderer {
195    /// Create a new `Renderer` from a variety of backend-specific components
196    /// and the window targets.
197    pub fn new(
198        window: &winit::window::Window,
199        mode: RenderMode,
200        runtime: &tokio::runtime::Runtime,
201    ) -> Result<Self, RenderError> {
202        let (pipeline_modes, mut other_modes) = mode.split();
203        // Enable seamless cubemaps globally, where available--they are essentially a
204        // strict improvement on regular cube maps.
205        //
206        // Note that since we only have to enable this once globally, there is no point
207        // in doing this on rerender.
208        // Self::enable_seamless_cube_maps(&mut device);
209
210        // TODO: fix panic on wayland with opengl?
211        // TODO: fix backend defaulting to opengl on wayland.
212        let backends = std::env::var("WGPU_BACKEND")
213            .ok()
214            .and_then(|backend| match backend.to_lowercase().as_str() {
215                "vulkan" | "vk" => Some(wgpu::Backends::VULKAN),
216                "metal" => Some(wgpu::Backends::METAL),
217                "dx12" => Some(wgpu::Backends::DX12),
218                "primary" => Some(wgpu::Backends::PRIMARY),
219                "opengl" | "gl" => Some(wgpu::Backends::GL),
220                "dx11" => Some(wgpu::Backends::DX11),
221                "secondary" => Some(wgpu::Backends::SECONDARY),
222                "all" => Some(wgpu::Backends::all()),
223                _ => None,
224            })
225            .unwrap_or(wgpu::Backends::PRIMARY | wgpu::Backends::SECONDARY);
226
227        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
228            backends,
229            dx12_shader_compiler: wgpu::Dx12Compiler::Fxc,
230            gles_minor_version: wgpu::Gles3MinorVersion::Automatic,
231            // TODO: Look into what we want here.
232            flags: wgpu::InstanceFlags::from_build_config().with_env(),
233        });
234
235        let dims = window.inner_size();
236
237        // This is unsafe because the window handle must be valid, if you find a way to
238        // have an invalid winit::Window then you have bigger issues
239        #[expect(unsafe_code)]
240        let surface =
241            unsafe { instance.create_surface(window) }.expect("Failed to create a surface");
242
243        let adapters = instance
244            .enumerate_adapters(backends)
245            .enumerate()
246            .collect::<Vec<_>>();
247
248        for (i, adapter) in adapters.iter() {
249            let info = adapter.get_info();
250            info!(
251                ?info.name,
252                ?info.vendor,
253                ?info.backend,
254                ?info.device,
255                ?info.device_type,
256                "graphics device #{}", i,
257            );
258        }
259
260        let adapter = match std::env::var("WGPU_ADAPTER").ok() {
261            Some(filter) if !filter.is_empty() => adapters.into_iter().find_map(|(i, adapter)| {
262                let info = adapter.get_info();
263
264                let full_name = format!("#{} {} {:?}", i, info.name, info.device_type,);
265
266                full_name.contains(&filter).then_some(adapter)
267            }),
268            Some(_) | None => {
269                runtime.block_on(instance.request_adapter(&wgpu::RequestAdapterOptionsBase {
270                    power_preference: wgpu::PowerPreference::HighPerformance,
271                    compatible_surface: Some(&surface),
272                    force_fallback_adapter: false,
273                }))
274            },
275        }
276        .ok_or(RenderError::CouldNotFindAdapter)?;
277
278        let info = adapter.get_info();
279        info!(
280            ?info.name,
281            ?info.vendor,
282            ?info.backend,
283            ?info.device,
284            ?info.device_type,
285            "selected graphics device"
286        );
287        let graphics_backend = format!("{:?}", &info.backend);
288
289        let limits = wgpu::Limits {
290            max_push_constant_size: 64,
291            ..Default::default()
292        };
293
294        let trace_env = std::env::var_os("WGPU_TRACE_DIR");
295        let trace_path = trace_env.as_ref().map(|v| {
296            let path = std::path::Path::new(v);
297            // We don't want to continue if we can't actually collect the api trace
298            assert!(
299                path.exists(),
300                "WGPU_TRACE_DIR is set to the path \"{}\" which doesn't exist",
301                path.display()
302            );
303            assert!(
304                path.is_dir(),
305                "WGPU_TRACE_DIR is set to the path \"{}\" which is not a directory",
306                path.display()
307            );
308            assert!(
309                path.read_dir()
310                    .expect("Could not read the directory that is specified by WGPU_TRACE_DIR")
311                    .next()
312                    .is_none(),
313                "WGPU_TRACE_DIR is set to the path \"{}\" which already contains other files",
314                path.display()
315            );
316
317            path
318        });
319
320        let (device, queue) = runtime.block_on(adapter.request_device(
321            &wgpu::DeviceDescriptor {
322                // TODO
323                label: None,
324                features: wgpu::Features::DEPTH_CLIP_CONTROL
325                    | wgpu::Features::ADDRESS_MODE_CLAMP_TO_BORDER
326                    | wgpu::Features::PUSH_CONSTANTS
327                    | (adapter.features() & wgpu_profiler::GpuProfiler::ALL_WGPU_TIMER_FEATURES),
328                limits,
329            },
330            trace_path,
331        ))?;
332
333        // Set error handler for wgpu errors
334        // This is better for use than their default because it includes the error in
335        // the panic message
336        device.on_uncaptured_error(Box::new(move |error| {
337            error!("{}", &error);
338            panic!(
339                "wgpu error (handling all wgpu errors as fatal):\n{:?}\n{:?}",
340                &error, &info,
341            );
342        }));
343
344        let profiler_features_enabled = device
345            .features()
346            .intersects(wgpu_profiler::GpuProfiler::ALL_WGPU_TIMER_FEATURES);
347        if !profiler_features_enabled {
348            info!(
349                "The features for GPU profiling (timestamp queries) are not available on this \
350                 adapter"
351            );
352        }
353
354        let max_texture_size = device.limits().max_texture_dimension_2d;
355
356        let surface_capabilities = surface.get_capabilities(&adapter);
357        let format = surface_capabilities.formats[0];
358        info!("Using {:?} as the surface format", format);
359
360        let present_mode = other_modes.present_mode.into();
361        let surface_config = wgpu::SurfaceConfiguration {
362            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
363            format,
364            width: dims.width,
365            height: dims.height,
366            present_mode: if surface_capabilities.present_modes.contains(&present_mode) {
367                present_mode
368            } else {
369                *surface_capabilities
370                    .present_modes
371                    .iter()
372                    .find(|mode| PresentMode::try_from(**mode).is_ok())
373                    .expect("There should never be no supported present modes")
374            },
375            alpha_mode: wgpu::CompositeAlphaMode::Opaque,
376            view_formats: Vec::new(),
377        };
378
379        let supported_internal_formats = [wgpu::TextureFormat::Rgba16Float, format];
380        let intermediate_format = supported_internal_formats
381            .into_iter()
382            .find(|format| {
383                use wgpu::TextureUsages as Usages;
384                use wgpu::TextureFormatFeatureFlags as Flags;
385                use super::AaMode;
386
387                let features = adapter
388                    .get_texture_format_features(*format);
389
390                let usage_ok = features
391                    .allowed_usages
392                    .contains(Usages::RENDER_ATTACHMENT | Usages::COPY_SRC | Usages::TEXTURE_BINDING);
393
394                let msaa_flags = match pipeline_modes.aa {
395                    AaMode::None | AaMode::Fxaa | AaMode::Hqx | AaMode::FxUpscale | AaMode::Bilinear => Flags::empty(),
396                    AaMode::MsaaX4 => Flags::MULTISAMPLE_X4,
397                    AaMode::MsaaX8 => Flags::MULTISAMPLE_X8,
398                    AaMode::MsaaX16 => Flags::MULTISAMPLE_X8, // TODO?
399                };
400
401                let flags_ok = features.flags.contains(Flags::FILTERABLE | msaa_flags);
402
403                usage_ok && flags_ok
404            })
405            // This should be unreachable as the surface format should always support the
406            // needed capabilities
407            .expect("No supported intermediate format");
408        info!("Using {:?} as the intermediate format", intermediate_format);
409
410        surface.configure(&device, &surface_config);
411
412        let shadow_views = ShadowMap::create_shadow_views(
413            &device,
414            (dims.width, dims.height),
415            &ShadowMapMode::try_from(pipeline_modes.shadow).unwrap_or_default(),
416            max_texture_size,
417        )
418        .map_err(|err| {
419            warn!("Could not create shadow map views: {:?}", err);
420        })
421        .ok();
422
423        let rain_occlusion_view = RainOcclusionMap::create_view(
424            &device,
425            &pipeline_modes.rain_occlusion,
426            max_texture_size,
427        )
428        .map_err(|err| {
429            warn!("Could not create rain occlusion map views: {:?}", err);
430        })
431        .ok();
432
433        let shaders = Shaders::load_expect("");
434        let shaders_watcher = shaders.reload_watcher();
435
436        let layouts = {
437            let global = GlobalsLayouts::new(&device);
438
439            let debug = debug::DebugLayout::new(&device);
440            let figure = figure::FigureLayout::new(&device);
441            let shadow = shadow::ShadowLayout::new(&device);
442            let rain_occlusion = rain_occlusion::RainOcclusionLayout::new(&device);
443            let sprite = sprite::SpriteLayout::new(&device);
444            let terrain = terrain::TerrainLayout::new(&device);
445            let rope = rope::RopeLayout::new(&device);
446            let clouds = clouds::CloudsLayout::new(&device);
447            let bloom = bloom::BloomLayout::new(&device);
448            let postprocess = Arc::new(postprocess::PostProcessLayout::new(
449                &device,
450                &pipeline_modes,
451            ));
452            let ui = ui::UiLayout::new(&device);
453            let premultiply_alpha = ui::PremultiplyAlphaLayout::new(&device);
454            let blit = blit::BlitLayout::new(&device);
455
456            let immutable = Arc::new(ImmutableLayouts {
457                global,
458
459                debug,
460                figure,
461                shadow,
462                rain_occlusion,
463                sprite,
464                terrain,
465                rope,
466                clouds,
467                bloom,
468                ui,
469                premultiply_alpha,
470                blit,
471            });
472
473            Layouts {
474                immutable,
475                postprocess,
476            }
477        };
478
479        // Arcify the device
480        let device = Arc::new(device);
481
482        let (interface_pipelines, creating) = pipeline_creation::initial_create_pipelines(
483            Arc::clone(&device),
484            Layouts {
485                immutable: Arc::clone(&layouts.immutable),
486                postprocess: Arc::clone(&layouts.postprocess),
487            },
488            shaders.cloned(),
489            pipeline_modes.clone(),
490            surface_config.clone(), // Note: cheap clone
491            shadow_views.is_some(),
492            intermediate_format,
493        )?;
494
495        let state = State::Interface {
496            pipelines: interface_pipelines,
497            shadow_views,
498            rain_occlusion_view,
499            creating,
500        };
501
502        let (views, bloom_sizes) = Self::create_rt_views(
503            &device,
504            (dims.width, dims.height),
505            &pipeline_modes,
506            &other_modes,
507            intermediate_format,
508        );
509
510        let create_sampler = |filter| {
511            device.create_sampler(&wgpu::SamplerDescriptor {
512                label: None,
513                address_mode_u: AddressMode::ClampToEdge,
514                address_mode_v: AddressMode::ClampToEdge,
515                address_mode_w: AddressMode::ClampToEdge,
516                mag_filter: filter,
517                min_filter: filter,
518                mipmap_filter: FilterMode::Nearest,
519                compare: None,
520                ..Default::default()
521            })
522        };
523
524        let sampler = create_sampler(FilterMode::Linear);
525        let depth_sampler = create_sampler(FilterMode::Nearest);
526
527        let noise_tex = Texture::new(
528            &device,
529            &queue,
530            &assets::Image::load_expect("voxygen.texture.noise").read().0,
531            Some(FilterMode::Linear),
532            Some(AddressMode::Repeat),
533        )?;
534
535        let clouds_locals =
536            Self::create_consts_inner(&device, &queue, &[clouds::Locals::default()]);
537        let postprocess_locals =
538            Self::create_consts_inner(&device, &queue, &[postprocess::Locals::default()]);
539
540        let locals = Locals::new(
541            &device,
542            &layouts,
543            clouds_locals,
544            postprocess_locals,
545            &views.tgt_color,
546            &views.tgt_mat,
547            &views.tgt_depth,
548            views.bloom_tgts.as_ref().map(|tgts| locals::BloomParams {
549                locals: bloom_sizes.map(|size| {
550                    Self::create_consts_inner(&device, &queue, &[bloom::Locals::new(size)])
551                }),
552                src_views: [&views.tgt_color_pp, &tgts[1], &tgts[2], &tgts[3], &tgts[4]],
553                final_tgt_view: &tgts[0],
554            }),
555            &views.tgt_color_pp,
556            &sampler,
557            &depth_sampler,
558        );
559
560        let quad_index_buffer_u16 =
561            create_quad_index_buffer_u16(&device, QUAD_INDEX_BUFFER_U16_START_VERT_LEN as usize);
562        let quad_index_buffer_u32 =
563            create_quad_index_buffer_u32(&device, QUAD_INDEX_BUFFER_U32_START_VERT_LEN as usize);
564        other_modes.profiler_enabled &= profiler_features_enabled;
565        let profiler = wgpu_profiler::GpuProfiler::new(wgpu_profiler::GpuProfilerSettings {
566            enable_timer_scopes: other_modes.profiler_enabled,
567            enable_debug_groups: other_modes.profiler_enabled,
568            max_num_pending_frames: 4,
569        })
570        .expect("Error creating profiler");
571
572        #[cfg(feature = "egui-ui")]
573        let egui_renderpass = egui_wgpu_backend::RenderPass::new(&device, format, 1);
574
575        let present_modes = surface
576            .get_capabilities(&adapter)
577            .present_modes
578            .into_iter()
579            .filter_map(|present_mode| PresentMode::try_from(present_mode).ok())
580            .collect();
581
582        Ok(Self {
583            device,
584            queue,
585            surface,
586            surface_config,
587
588            state,
589            recreation_pending: None,
590
591            layouts,
592            locals,
593            views,
594
595            sampler,
596            depth_sampler,
597            noise_tex,
598
599            quad_index_buffer_u16,
600            quad_index_buffer_u32,
601
602            shaders,
603            shaders_watcher,
604
605            pipeline_modes,
606            other_modes,
607            resolution: Vec2::new(dims.width, dims.height),
608
609            take_screenshot: None,
610
611            profiler,
612            profile_times: Vec::new(),
613            profiler_features_enabled,
614
615            ui_premultiply_uploads: Default::default(),
616
617            #[cfg(feature = "egui-ui")]
618            egui_renderpass,
619
620            is_minimized: false,
621
622            graphics_backend,
623
624            intermediate_format,
625
626            present_modes,
627            max_texture_size,
628        })
629    }
630
631    /// Get the graphics backend being used
632    pub fn graphics_backend(&self) -> &str { &self.graphics_backend }
633
634    /// Check the status of the intial pipeline creation
635    /// Returns `None` if complete
636    /// Returns `Some((total, complete))` if in progress
637    pub fn pipeline_creation_status(&self) -> Option<(usize, usize)> {
638        if let State::Interface { creating, .. } = &self.state {
639            Some(creating.status())
640        } else {
641            None
642        }
643    }
644
645    /// Check the status the pipeline recreation
646    /// Returns `None` if pipelines are currently not being recreated
647    /// Returns `Some((total, complete))` if in progress
648    pub fn pipeline_recreation_status(&self) -> Option<(usize, usize)> {
649        if let State::Complete { recreating, .. } = &self.state {
650            recreating.as_ref().map(|(_, c)| c.status())
651        } else {
652            None
653        }
654    }
655
656    /// Change the render mode.
657    pub fn set_render_mode(&mut self, mode: RenderMode) -> Result<(), RenderError> {
658        let (pipeline_modes, other_modes) = mode.split();
659
660        if self.other_modes != other_modes {
661            self.other_modes = other_modes;
662
663            // Update present mode in swap chain descriptor if it is supported.
664            if self.present_modes.contains(&self.other_modes.present_mode) {
665                self.surface_config.present_mode = self.other_modes.present_mode.into()
666            }
667
668            // Only enable profiling if the wgpu features are enabled
669            self.other_modes.profiler_enabled &= self.profiler_features_enabled;
670            // Enable/disable profiler
671            if !self.other_modes.profiler_enabled {
672                // Clear the times if disabled
673                core::mem::take(&mut self.profile_times);
674            }
675            self.profiler
676                .change_settings(wgpu_profiler::GpuProfilerSettings {
677                    enable_timer_scopes: self.other_modes.profiler_enabled,
678                    enable_debug_groups: self.other_modes.profiler_enabled,
679                    max_num_pending_frames: 4,
680                })
681                .expect("Error creating profiler");
682
683            // Recreate render target
684            self.on_resize(self.resolution);
685        }
686
687        // We can't cancel the pending recreation even if the new settings are equal
688        // to the current ones becuase the recreation could be triggered by something
689        // else like shader hotloading
690        if self.pipeline_modes != pipeline_modes
691            || self
692                .recreation_pending
693                .as_ref()
694                .is_some_and(|modes| modes != &pipeline_modes)
695        {
696            // Recreate pipelines with new modes
697            self.recreate_pipelines(pipeline_modes);
698        }
699
700        Ok(())
701    }
702
703    /// Get the pipelines mode.
704    pub fn pipeline_modes(&self) -> &PipelineModes { &self.pipeline_modes }
705
706    /// Get the supported present modes.
707    pub fn present_modes(&self) -> &[PresentMode] { &self.present_modes }
708
709    /// Get the current profiling times
710    /// Nested timings immediately follow their parent
711    /// Returns Vec<(how nested this timing is, label, length in seconds)>
712    pub fn timings(&self) -> Vec<(u8, &str, f64)> {
713        use wgpu_profiler::GpuTimerScopeResult;
714        fn recursive_collect<'a>(
715            vec: &mut Vec<(u8, &'a str, f64)>,
716            result: &'a GpuTimerScopeResult,
717            nest_level: u8,
718        ) {
719            vec.push((
720                nest_level,
721                &result.label,
722                result.time.end - result.time.start,
723            ));
724            result
725                .nested_scopes
726                .iter()
727                .for_each(|child| recursive_collect(vec, child, nest_level + 1));
728        }
729        let mut vec = Vec::new();
730        self.profile_times
731            .iter()
732            .for_each(|child| recursive_collect(&mut vec, child, 0));
733        vec
734    }
735
736    /// Resize internal render targets to match window render target dimensions.
737    pub fn on_resize(&mut self, dims: Vec2<u32>) {
738        // Avoid panics when creating texture with w,h of 0,0.
739        if dims.x != 0 && dims.y != 0 {
740            self.is_minimized = false;
741            // Resize swap chain
742            self.resolution = dims;
743            self.surface_config.width = dims.x;
744            self.surface_config.height = dims.y;
745            self.surface.configure(&self.device, &self.surface_config);
746
747            // Resize other render targets
748            let (views, bloom_sizes) = Self::create_rt_views(
749                &self.device,
750                (dims.x, dims.y),
751                &self.pipeline_modes,
752                &self.other_modes,
753                self.intermediate_format,
754            );
755            self.views = views;
756
757            let bloom_params = self
758                .views
759                .bloom_tgts
760                .as_ref()
761                .map(|tgts| locals::BloomParams {
762                    locals: bloom_sizes.map(|size| {
763                        Self::create_consts_inner(&self.device, &self.queue, &[bloom::Locals::new(
764                            size,
765                        )])
766                    }),
767                    src_views: [
768                        &self.views.tgt_color_pp,
769                        &tgts[1],
770                        &tgts[2],
771                        &tgts[3],
772                        &tgts[4],
773                    ],
774                    final_tgt_view: &tgts[0],
775                });
776
777            self.locals.rebind(
778                &self.device,
779                &self.layouts,
780                &self.views.tgt_color,
781                &self.views.tgt_mat,
782                &self.views.tgt_depth,
783                bloom_params,
784                &self.views.tgt_color_pp,
785                &self.sampler,
786                &self.depth_sampler,
787            );
788
789            // Get mutable reference to shadow views out of the current state
790            let shadow_views = match &mut self.state {
791                State::Interface {
792                    shadow_views,
793                    rain_occlusion_view,
794                    ..
795                } => shadow_views
796                    .as_mut()
797                    .map(|s| (&mut s.0, &mut s.1))
798                    .zip(rain_occlusion_view.as_mut()),
799                State::Complete {
800                    shadow:
801                        Shadow {
802                            map: ShadowMap::Enabled(shadow_map),
803                            rain_map: RainOcclusionMap::Enabled(rain_occlusion_map),
804                            ..
805                        },
806                    ..
807                } => Some((
808                    (&mut shadow_map.point_depth, &mut shadow_map.directed_depth),
809                    &mut rain_occlusion_map.depth,
810                )),
811                State::Complete { .. } => None,
812                State::Nothing => None, // Should never hit this
813            };
814
815            let mut update_shadow_bind = false;
816            let (shadow_views, rain_views) = shadow_views.unzip();
817
818            if let (Some((point_depth, directed_depth)), ShadowMode::Map(mode)) =
819                (shadow_views, self.pipeline_modes.shadow)
820            {
821                match ShadowMap::create_shadow_views(
822                    &self.device,
823                    (dims.x, dims.y),
824                    &mode,
825                    self.max_texture_size,
826                ) {
827                    Ok((new_point_depth, new_directed_depth)) => {
828                        *point_depth = new_point_depth;
829                        *directed_depth = new_directed_depth;
830
831                        update_shadow_bind = true;
832                    },
833                    Err(err) => {
834                        warn!("Could not create shadow map views: {:?}", err);
835                    },
836                }
837            }
838            if let Some(rain_depth) = rain_views {
839                match RainOcclusionMap::create_view(
840                    &self.device,
841                    &self.pipeline_modes.rain_occlusion,
842                    self.max_texture_size,
843                ) {
844                    Ok(new_rain_depth) => {
845                        *rain_depth = new_rain_depth;
846
847                        update_shadow_bind = true;
848                    },
849                    Err(err) => {
850                        warn!("Could not create rain occlusion map view: {:?}", err);
851                    },
852                }
853            }
854            if update_shadow_bind {
855                // Recreate the shadow bind group if needed
856                if let State::Complete {
857                    shadow:
858                        Shadow {
859                            bind,
860                            map: ShadowMap::Enabled(shadow_map),
861                            rain_map: RainOcclusionMap::Enabled(rain_occlusion_map),
862                            ..
863                        },
864                    ..
865                } = &mut self.state
866                {
867                    *bind = self.layouts.global.bind_shadow_textures(
868                        &self.device,
869                        &shadow_map.point_depth,
870                        &shadow_map.directed_depth,
871                        &rain_occlusion_map.depth,
872                    );
873                }
874            }
875        } else {
876            self.is_minimized = true;
877        }
878    }
879
880    pub fn maintain(&self) {
881        if self.is_minimized {
882            self.queue.submit(std::iter::empty());
883        }
884
885        self.device.poll(wgpu::Maintain::Poll);
886    }
887
888    /// Create render target views
889    fn create_rt_views(
890        device: &wgpu::Device,
891        size: (u32, u32),
892        pipeline_modes: &PipelineModes,
893        other_modes: &OtherModes,
894        format: wgpu::TextureFormat,
895    ) -> (Views, [Vec2<f32>; bloom::NUM_SIZES]) {
896        let upscaled = Vec2::<u32>::from(size)
897            .map(|e| (e as f32 * other_modes.upscale_mode.factor) as u32)
898            .into_tuple();
899        let (width, height) = upscaled;
900        let sample_count = pipeline_modes.aa.samples();
901        let levels = 1;
902
903        let color_view = |width, height, format| {
904            let tex = device.create_texture(&wgpu::TextureDescriptor {
905                label: None,
906                size: wgpu::Extent3d {
907                    width,
908                    height,
909                    depth_or_array_layers: 1,
910                },
911                mip_level_count: levels,
912                sample_count,
913                dimension: wgpu::TextureDimension::D2,
914                format,
915                usage: wgpu::TextureUsages::TEXTURE_BINDING
916                    | wgpu::TextureUsages::RENDER_ATTACHMENT,
917                view_formats: &[],
918            });
919
920            tex.create_view(&wgpu::TextureViewDescriptor {
921                label: None,
922                format: Some(format),
923                dimension: Some(wgpu::TextureViewDimension::D2),
924                // TODO: why is this not Color?
925                aspect: wgpu::TextureAspect::All,
926                base_mip_level: 0,
927                mip_level_count: None,
928                base_array_layer: 0,
929                array_layer_count: None,
930            })
931        };
932
933        let tgt_color_view = color_view(width, height, format);
934        let tgt_color_pp_view = color_view(width, height, format);
935
936        let tgt_mat_view = color_view(width, height, wgpu::TextureFormat::Rgba8Uint);
937
938        let mut size_shift = 0;
939        // TODO: skip creating bloom stuff when it is disabled
940        let bloom_sizes = [(); bloom::NUM_SIZES].map(|()| {
941            // .max(1) to ensure we don't create zero sized textures
942            let size = Vec2::new(width, height).map(|e| (e >> size_shift).max(1));
943            size_shift += 1;
944            size
945        });
946
947        let bloom_tgt_views = pipeline_modes
948            .bloom
949            .is_on()
950            .then(|| bloom_sizes.map(|size| color_view(size.x, size.y, format)));
951
952        let tgt_depth_tex = device.create_texture(&wgpu::TextureDescriptor {
953            label: None,
954            size: wgpu::Extent3d {
955                width,
956                height,
957                depth_or_array_layers: 1,
958            },
959            mip_level_count: levels,
960            sample_count,
961            dimension: wgpu::TextureDimension::D2,
962            format: wgpu::TextureFormat::Depth32Float,
963            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
964            view_formats: &[],
965        });
966        let tgt_depth_view = tgt_depth_tex.create_view(&wgpu::TextureViewDescriptor {
967            label: None,
968            format: Some(wgpu::TextureFormat::Depth32Float),
969            dimension: Some(wgpu::TextureViewDimension::D2),
970            aspect: wgpu::TextureAspect::DepthOnly,
971            base_mip_level: 0,
972            mip_level_count: None,
973            base_array_layer: 0,
974            array_layer_count: None,
975        });
976
977        let win_depth_tex = device.create_texture(&wgpu::TextureDescriptor {
978            label: None,
979            size: wgpu::Extent3d {
980                width: size.0,
981                height: size.1,
982                depth_or_array_layers: 1,
983            },
984            mip_level_count: levels,
985            sample_count,
986            dimension: wgpu::TextureDimension::D2,
987            format: wgpu::TextureFormat::Depth32Float,
988            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
989            view_formats: &[],
990        });
991        // TODO: Consider no depth buffer for the final draw to the window?
992        let win_depth_view = win_depth_tex.create_view(&wgpu::TextureViewDescriptor {
993            label: None,
994            format: Some(wgpu::TextureFormat::Depth32Float),
995            dimension: Some(wgpu::TextureViewDimension::D2),
996            aspect: wgpu::TextureAspect::DepthOnly,
997            base_mip_level: 0,
998            mip_level_count: None,
999            base_array_layer: 0,
1000            array_layer_count: None,
1001        });
1002
1003        (
1004            Views {
1005                tgt_color: tgt_color_view,
1006                tgt_mat: tgt_mat_view,
1007                tgt_depth: tgt_depth_view,
1008                bloom_tgts: bloom_tgt_views,
1009                tgt_color_pp: tgt_color_pp_view,
1010                _win_depth: win_depth_view,
1011            },
1012            bloom_sizes.map(|s| s.map(|e| e as f32)),
1013        )
1014    }
1015
1016    /// Get the resolution of the render target.
1017    pub fn resolution(&self) -> Vec2<u32> { self.resolution }
1018
1019    /// Get the resolution of the shadow render target.
1020    pub fn get_shadow_resolution(&self) -> (Vec2<u32>, Vec2<u32>) {
1021        match &self.state {
1022            State::Interface { shadow_views, .. } => shadow_views.as_ref().map(|s| (&s.0, &s.1)),
1023            State::Complete {
1024                shadow:
1025                    Shadow {
1026                        map: ShadowMap::Enabled(shadow_map),
1027                        ..
1028                    },
1029                ..
1030            } => Some((&shadow_map.point_depth, &shadow_map.directed_depth)),
1031            State::Complete { .. } | State::Nothing => None,
1032        }
1033        .map(|(point, directed)| (point.get_dimensions().xy(), directed.get_dimensions().xy()))
1034        .unwrap_or_else(|| (Vec2::new(1, 1), Vec2::new(1, 1)))
1035    }
1036
1037    /// Start recording the frame
1038    /// When the returned `Drawer` is dropped the recorded draw calls will be
1039    /// submitted to the queue
1040    /// If there is an intermittent issue with the swap chain then Ok(None) will
1041    /// be returned
1042    pub fn start_recording_frame<'a>(
1043        &'a mut self,
1044        globals: &'a GlobalsBindGroup,
1045    ) -> Result<Option<drawer::Drawer<'a>>, RenderError> {
1046        span!(
1047            _guard,
1048            "start_recording_frame",
1049            "Renderer::start_recording_frame"
1050        );
1051
1052        if self.is_minimized {
1053            return Ok(None);
1054        }
1055
1056        // Try to get the latest profiling results
1057        if self.other_modes.profiler_enabled {
1058            // Note: this lags a few frames behind
1059            let timestamp_period = self.queue.get_timestamp_period();
1060            if let Some(profile_times) = self.profiler.process_finished_frame(timestamp_period) {
1061                self.profile_times = profile_times;
1062            }
1063        }
1064
1065        // Handle polling background pipeline creation/recreation
1066        // Temporarily set to nothing and then replace in the statement below
1067        let state = core::mem::replace(&mut self.state, State::Nothing);
1068        // Indicator for if pipeline recreation finished and we need to recreate bind
1069        // groups / render targets (handling defered so that State will be valid
1070        // when calling Self::on_resize)
1071        let mut trigger_on_resize = false;
1072        // If still creating initial pipelines, check if complete
1073        self.state = if let State::Interface {
1074            pipelines: interface,
1075            shadow_views,
1076            rain_occlusion_view,
1077            creating,
1078        } = state
1079        {
1080            match creating.try_complete() {
1081                Ok(pipelines) => {
1082                    let IngameAndShadowPipelines {
1083                        ingame,
1084                        shadow,
1085                        rain_occlusion,
1086                    } = pipelines;
1087
1088                    let pipelines = Pipelines::consolidate(interface, ingame);
1089
1090                    let shadow_map = ShadowMap::new(
1091                        &self.device,
1092                        &self.queue,
1093                        shadow.point,
1094                        shadow.directed,
1095                        shadow.figure,
1096                        shadow.debug,
1097                        shadow_views,
1098                    );
1099
1100                    let rain_occlusion_map = RainOcclusionMap::new(
1101                        &self.device,
1102                        &self.queue,
1103                        rain_occlusion.terrain,
1104                        rain_occlusion.figure,
1105                        rain_occlusion_view,
1106                    );
1107
1108                    let shadow_bind = {
1109                        let (point, directed) = shadow_map.textures();
1110                        self.layouts.global.bind_shadow_textures(
1111                            &self.device,
1112                            point,
1113                            directed,
1114                            rain_occlusion_map.texture(),
1115                        )
1116                    };
1117
1118                    let shadow = Shadow {
1119                        rain_map: rain_occlusion_map,
1120                        map: shadow_map,
1121                        bind: shadow_bind,
1122                    };
1123
1124                    State::Complete {
1125                        pipelines,
1126                        shadow,
1127                        recreating: None,
1128                    }
1129                },
1130                // Not complete
1131                Err(creating) => State::Interface {
1132                    pipelines: interface,
1133                    shadow_views,
1134                    rain_occlusion_view,
1135                    creating,
1136                },
1137            }
1138        // If recreating the pipelines, check if that is complete
1139        } else if let State::Complete {
1140            pipelines,
1141            mut shadow,
1142            recreating: Some((new_pipeline_modes, pipeline_creation)),
1143        } = state
1144        {
1145            match pipeline_creation.try_complete() {
1146                Ok(Ok((
1147                    pipelines,
1148                    shadow_pipelines,
1149                    rain_occlusion_pipelines,
1150                    postprocess_layout,
1151                ))) => {
1152                    if let (
1153                        Some(point_pipeline),
1154                        Some(terrain_directed_pipeline),
1155                        Some(figure_directed_pipeline),
1156                        Some(debug_directed_pipeline),
1157                        ShadowMap::Enabled(shadow_map),
1158                    ) = (
1159                        shadow_pipelines.point,
1160                        shadow_pipelines.directed,
1161                        shadow_pipelines.figure,
1162                        shadow_pipelines.debug,
1163                        &mut shadow.map,
1164                    ) {
1165                        shadow_map.point_pipeline = point_pipeline;
1166                        shadow_map.terrain_directed_pipeline = terrain_directed_pipeline;
1167                        shadow_map.figure_directed_pipeline = figure_directed_pipeline;
1168                        shadow_map.debug_directed_pipeline = debug_directed_pipeline;
1169                    }
1170
1171                    if let (
1172                        Some(terrain_directed_pipeline),
1173                        Some(figure_directed_pipeline),
1174                        RainOcclusionMap::Enabled(rain_occlusion_map),
1175                    ) = (
1176                        rain_occlusion_pipelines.terrain,
1177                        rain_occlusion_pipelines.figure,
1178                        &mut shadow.rain_map,
1179                    ) {
1180                        rain_occlusion_map.terrain_pipeline = terrain_directed_pipeline;
1181                        rain_occlusion_map.figure_pipeline = figure_directed_pipeline;
1182                    }
1183
1184                    self.pipeline_modes = new_pipeline_modes;
1185                    self.layouts.postprocess = postprocess_layout;
1186                    // TODO: we have the potential to skip recreating bindings / render targets on
1187                    // pipeline recreation trigged by shader reloading (would need to ensure new
1188                    // postprocess_layout is not created...)
1189                    trigger_on_resize = true;
1190
1191                    State::Complete {
1192                        pipelines,
1193                        shadow,
1194                        recreating: None,
1195                    }
1196                },
1197                Ok(Err(e)) => {
1198                    error!(?e, "Could not recreate shaders from assets due to an error");
1199                    State::Complete {
1200                        pipelines,
1201                        shadow,
1202                        recreating: None,
1203                    }
1204                },
1205                // Not complete
1206                Err(pipeline_creation) => State::Complete {
1207                    pipelines,
1208                    shadow,
1209                    recreating: Some((new_pipeline_modes, pipeline_creation)),
1210                },
1211            }
1212        } else {
1213            state
1214        };
1215
1216        // Call on_resize to recreate render targets and their bind groups if the
1217        // pipelines were recreated with a new postprocess layout and or changes in the
1218        // render modes
1219        if trigger_on_resize {
1220            self.on_resize(self.resolution);
1221        }
1222
1223        // If the shaders files were changed attempt to recreate the shaders
1224        if self.shaders_watcher.reloaded() {
1225            self.recreate_pipelines(self.pipeline_modes.clone());
1226        }
1227
1228        // Or if we have a recreation pending
1229        if matches!(&self.state, State::Complete {
1230            recreating: None,
1231            ..
1232        }) {
1233            if let Some(new_pipeline_modes) = self.recreation_pending.take() {
1234                self.recreate_pipelines(new_pipeline_modes);
1235            }
1236        }
1237
1238        let texture = match self.surface.get_current_texture() {
1239            Ok(texture) => texture,
1240            // If lost recreate the swap chain
1241            Err(err @ wgpu::SurfaceError::Lost) => {
1242                warn!("{}. Recreating swap chain. A frame will be missed", err);
1243                self.on_resize(self.resolution);
1244                return Ok(None);
1245            },
1246            Err(wgpu::SurfaceError::Timeout) => {
1247                // This will probably be resolved on the next frame
1248                // NOTE: we don't log this because it happens very frequently with
1249                // PresentMode::Fifo and unlimited FPS on certain machines
1250                return Ok(None);
1251            },
1252            Err(err @ wgpu::SurfaceError::Outdated) => {
1253                warn!("{}. Recreating the swapchain", err);
1254                self.surface.configure(&self.device, &self.surface_config);
1255                return Ok(None);
1256            },
1257            Err(err @ wgpu::SurfaceError::OutOfMemory) => return Err(err.into()),
1258        };
1259        let encoder = self
1260            .device
1261            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
1262                label: Some("A render encoder"),
1263            });
1264
1265        Ok(Some(drawer::Drawer::new(encoder, self, texture, globals)))
1266    }
1267
1268    /// Recreate the pipelines
1269    fn recreate_pipelines(&mut self, pipeline_modes: PipelineModes) {
1270        match &mut self.state {
1271            State::Complete { recreating, .. } if recreating.is_some() => {
1272                // Defer recreation so that we are not building multiple sets of pipelines in
1273                // the background at once
1274                self.recreation_pending = Some(pipeline_modes);
1275            },
1276            State::Complete {
1277                recreating, shadow, ..
1278            } => {
1279                *recreating = Some((
1280                    pipeline_modes.clone(),
1281                    pipeline_creation::recreate_pipelines(
1282                        Arc::clone(&self.device),
1283                        Arc::clone(&self.layouts.immutable),
1284                        self.shaders.cloned(),
1285                        pipeline_modes,
1286                        // NOTE: if present_mode starts to be used to configure pipelines then it
1287                        // needs to become a part of the pipeline modes
1288                        // (note here since the present mode is accessible
1289                        // through the swap chain descriptor)
1290                        self.surface_config.clone(), // Note: cheap clone
1291                        shadow.map.is_enabled(),
1292                        self.intermediate_format,
1293                    ),
1294                ));
1295            },
1296            State::Interface { .. } => {
1297                // Defer recreation so that we are not building multiple sets of pipelines in
1298                // the background at once
1299                self.recreation_pending = Some(pipeline_modes);
1300            },
1301            State::Nothing => {},
1302        }
1303    }
1304
1305    /// Create a new set of constants with the provided values.
1306    pub fn create_consts<T: Copy + bytemuck::Pod>(&mut self, vals: &[T]) -> Consts<T> {
1307        Self::create_consts_inner(&self.device, &self.queue, vals)
1308    }
1309
1310    pub fn create_consts_inner<T: Copy + bytemuck::Pod>(
1311        device: &wgpu::Device,
1312        queue: &wgpu::Queue,
1313        vals: &[T],
1314    ) -> Consts<T> {
1315        let mut consts = Consts::new(device, vals.len());
1316        consts.update(queue, vals, 0);
1317        consts
1318    }
1319
1320    /// Update a set of constants with the provided values.
1321    pub fn update_consts<T: Copy + bytemuck::Pod>(&self, consts: &mut Consts<T>, vals: &[T]) {
1322        consts.update(&self.queue, vals, 0)
1323    }
1324
1325    pub fn update_clouds_locals(&mut self, new_val: clouds::Locals) {
1326        self.locals.clouds.update(&self.queue, &[new_val], 0)
1327    }
1328
1329    pub fn update_postprocess_locals(&mut self, new_val: postprocess::Locals) {
1330        self.locals.postprocess.update(&self.queue, &[new_val], 0)
1331    }
1332
1333    /// Create a new set of instances with the provided values.
1334    pub fn create_instances<T: Copy + bytemuck::Pod>(&mut self, vals: &[T]) -> Instances<T> {
1335        let mut instances = Instances::new(&self.device, vals.len());
1336        instances.update(&self.queue, vals, 0);
1337        instances
1338    }
1339
1340    /// Ensure that the quad index buffer is large enough for a quad vertex
1341    /// buffer with this many vertices
1342    pub(super) fn ensure_sufficient_index_length<V: Vertex>(
1343        &mut self,
1344        // Length of the vert buffer with 4 verts per quad
1345        vert_length: usize,
1346    ) {
1347        let quad_index_length = vert_length / 4 * 6;
1348
1349        match V::QUADS_INDEX {
1350            Some(wgpu::IndexFormat::Uint16) => {
1351                // Make sure the global quad index buffer is large enough
1352                if self.quad_index_buffer_u16.len() < quad_index_length {
1353                    // Make sure we aren't over the max
1354                    if vert_length > u16::MAX as usize {
1355                        panic!(
1356                            "Vertex type: {} needs to use a larger index type, length: {}",
1357                            core::any::type_name::<V>(),
1358                            vert_length
1359                        );
1360                    }
1361                    self.quad_index_buffer_u16 =
1362                        create_quad_index_buffer_u16(&self.device, vert_length);
1363                }
1364            },
1365            Some(wgpu::IndexFormat::Uint32) => {
1366                // Make sure the global quad index buffer is large enough
1367                if self.quad_index_buffer_u32.len() < quad_index_length {
1368                    // Make sure we aren't over the max
1369                    if vert_length > u32::MAX as usize {
1370                        panic!(
1371                            "More than u32::MAX({}) verts({}) for type({}) using an index buffer!",
1372                            u32::MAX,
1373                            vert_length,
1374                            core::any::type_name::<V>()
1375                        );
1376                    }
1377                    self.quad_index_buffer_u32 =
1378                        create_quad_index_buffer_u32(&self.device, vert_length);
1379                }
1380            },
1381            None => {},
1382        }
1383    }
1384
1385    pub fn create_sprite_verts(&mut self, mesh: Mesh<sprite::Vertex>) -> sprite::SpriteVerts {
1386        self.ensure_sufficient_index_length::<sprite::Vertex>(sprite::VERT_PAGE_SIZE as usize);
1387        sprite::create_verts_buffer(&self.device, mesh)
1388    }
1389
1390    /// Create a new model from the provided mesh.
1391    /// If the provided mesh is empty this returns None
1392    pub fn create_model<V: Vertex>(&mut self, mesh: &Mesh<V>) -> Option<Model<V>> {
1393        self.ensure_sufficient_index_length::<V>(mesh.vertices().len());
1394        Model::new(&self.device, mesh)
1395    }
1396
1397    /// Create a new dynamic model with the specified size.
1398    pub fn create_dynamic_model<V: Vertex>(&mut self, size: usize) -> DynamicModel<V> {
1399        self.ensure_sufficient_index_length::<V>(size);
1400        DynamicModel::new(&self.device, size)
1401    }
1402
1403    /// Update a dynamic model with a mesh and a offset.
1404    pub fn update_model<V: Vertex>(&self, model: &DynamicModel<V>, mesh: &Mesh<V>, offset: usize) {
1405        model.update(&self.queue, mesh, offset)
1406    }
1407
1408    /// Return the maximum supported texture size.
1409    pub fn max_texture_size(&self) -> u32 { self.max_texture_size }
1410
1411    /// Create a new immutable texture from the provided image.
1412    /// # Panics
1413    /// If the provided data doesn't completely fill the texture this function
1414    /// will panic.
1415    pub fn create_texture_with_data_raw(
1416        &mut self,
1417        texture_info: &wgpu::TextureDescriptor,
1418        view_info: &wgpu::TextureViewDescriptor,
1419        sampler_info: &wgpu::SamplerDescriptor,
1420        data: &[u8],
1421    ) -> Texture {
1422        let tex = Texture::new_raw(&self.device, texture_info, view_info, sampler_info);
1423
1424        let size = texture_info.size;
1425        let block_size = texture_info.format.block_size(None).unwrap();
1426        assert_eq!(
1427            size.width as usize
1428                * size.height as usize
1429                * size.depth_or_array_layers as usize
1430                * block_size as usize,
1431            data.len(),
1432            "Provided data length {} does not fill the provided texture size {:?}",
1433            data.len(),
1434            size,
1435        );
1436
1437        tex.update(
1438            &self.queue,
1439            [0; 2],
1440            [texture_info.size.width, texture_info.size.height],
1441            data,
1442        );
1443
1444        tex
1445    }
1446
1447    /// Create a new raw texture.
1448    pub fn create_texture_raw(
1449        &mut self,
1450        texture_info: &wgpu::TextureDescriptor,
1451        view_info: &wgpu::TextureViewDescriptor,
1452        sampler_info: &wgpu::SamplerDescriptor,
1453    ) -> Texture {
1454        let texture = Texture::new_raw(&self.device, texture_info, view_info, sampler_info);
1455        texture.clear(&self.queue); // Needs to be fully initialized for partial writes to work on Dx12 AMD
1456        texture
1457    }
1458
1459    /// Create a new texture from the provided image.
1460    pub fn create_texture(
1461        &mut self,
1462        image: &image::DynamicImage,
1463        filter_method: Option<FilterMode>,
1464        address_mode: Option<AddressMode>,
1465    ) -> Result<Texture, RenderError> {
1466        Texture::new(
1467            &self.device,
1468            &self.queue,
1469            image,
1470            filter_method,
1471            address_mode,
1472        )
1473    }
1474
1475    /// Create a new dynamic texture with the specified dimensions.
1476    ///
1477    /// Currently only supports Rgba8Srgb.
1478    pub fn create_dynamic_texture(&mut self, dims: Vec2<u32>) -> Texture {
1479        Texture::new_dynamic(&self.device, &self.queue, dims.x, dims.y)
1480    }
1481
1482    /// Update a texture with the provided offset, size, and data.
1483    pub fn update_texture<T: bytemuck::Pod>(
1484        &mut self,
1485        texture: &Texture,
1486        offset: [u32; 2],
1487        size: [u32; 2],
1488        data: &[T],
1489    ) {
1490        texture.update(&self.queue, offset, size, bytemuck::cast_slice(data))
1491    }
1492
1493    /// See docs on [`ui::BatchedUploads::submit`].
1494    pub fn ui_premultiply_upload(
1495        &mut self,
1496        target_texture: &Arc<Texture>,
1497        batch: ui::UploadBatchId,
1498        image: &image::RgbaImage,
1499        offset: Vec2<u16>,
1500    ) -> ui::UploadBatchId {
1501        let upload = ui::PremultiplyUpload::prepare(
1502            &self.device,
1503            &self.queue,
1504            &self.layouts.premultiply_alpha,
1505            image,
1506            offset,
1507        );
1508        self.ui_premultiply_uploads
1509            .submit(target_texture, batch, upload)
1510    }
1511
1512    /// Queue to obtain a screenshot on the next frame render
1513    pub fn create_screenshot(
1514        &mut self,
1515        screenshot_handler: impl FnOnce(Result<image::RgbImage, String>) + Send + 'static,
1516    ) {
1517        // Queue screenshot
1518        self.take_screenshot = Some(Box::new(screenshot_handler));
1519        // Take profiler snapshot
1520        if self.other_modes.profiler_enabled {
1521            let file_name = format!(
1522                "frame-trace_{}.json",
1523                std::time::SystemTime::now()
1524                    .duration_since(std::time::SystemTime::UNIX_EPOCH)
1525                    .map(|d| d.as_millis())
1526                    .unwrap_or(0)
1527            );
1528
1529            if let Err(err) = wgpu_profiler::chrometrace::write_chrometrace(
1530                std::path::Path::new(&file_name),
1531                &self.profile_times,
1532            ) {
1533                error!(?err, "Failed to save GPU timing snapshot");
1534            } else {
1535                info!("Saved GPU timing snapshot as: {}", file_name);
1536            }
1537        }
1538    }
1539
1540    // Consider reenabling at some time
1541    //
1542    // /// Queue the rendering of the player silhouette in the upcoming frame.
1543    // pub fn render_player_shadow(
1544    //     &mut self,
1545    //     _model: &figure::FigureModel,
1546    //     _col_lights: &Texture<ColLightFmt>,
1547    //     _global: &GlobalModel,
1548    //     _bones: &Consts<figure::BoneData>,
1549    //     _lod: &lod_terrain::LodData,
1550    //     _locals: &Consts<shadow::Locals>,
1551    // ) { // FIXME: Consider reenabling at some point. /* let (point_shadow_maps,
1552    //   directed_shadow_maps) = if let Some(shadow_map) = &mut self.shadow_map { (
1553    //   ( shadow_map.point_res.clone(), shadow_map.point_sampler.clone(), ), (
1554    //   shadow_map.directed_res.clone(), shadow_map.directed_sampler.clone(), ), )
1555    //   } else { ( (self.noise_tex.srv.clone(), self.noise_tex.sampler.clone()),
1556    //   (self.noise_tex.srv.clone(), self.noise_tex.sampler.clone()), ) }; let
1557    //   model = &model.opaque;
1558
1559    //     self.encoder.draw(
1560    //         &gfx::Slice {
1561    //             start: model.vertex_range().start,
1562    //             end: model.vertex_range().end,
1563    //             base_vertex: 0,
1564    //             instances: None,
1565    //             buffer: gfx::IndexBuffer::Auto,
1566    //         },
1567    //         &self.player_shadow_pipeline.pso,
1568    //         &figure::pipe::Data {
1569    //             vbuf: model.vbuf.clone(),
1570    //             col_lights: (col_lights.srv.clone(), col_lights.sampler.clone()),
1571    //             locals: locals.buf.clone(),
1572    //             globals: global.globals.buf.clone(),
1573    //             bones: bones.buf.clone(),
1574    //             lights: global.lights.buf.clone(),
1575    //             shadows: global.shadows.buf.clone(),
1576    //             light_shadows: global.shadow_mats.buf.clone(),
1577    //             point_shadow_maps,
1578    //             directed_shadow_maps,
1579    //             noise: (self.noise_tex.srv.clone(),
1580    // self.noise_tex.sampler.clone()),             alt: (lod.alt.srv.clone(),
1581    // lod.alt.sampler.clone()),             horizon: (lod.horizon.srv.clone(),
1582    // lod.horizon.sampler.clone()),             tgt_color:
1583    // self.tgt_color_view.clone(),             tgt_depth:
1584    // (self.tgt_depth_view.clone()/* , (0, 0) */),         },
1585    //     ); */
1586    // }
1587}
1588
1589fn create_quad_index_buffer_u16(device: &wgpu::Device, vert_length: usize) -> Buffer<u16> {
1590    assert!(vert_length <= u16::MAX as usize);
1591    let indices = [0, 1, 2, 2, 1, 3]
1592        .iter()
1593        .cycle()
1594        .copied()
1595        .take(vert_length / 4 * 6)
1596        .enumerate()
1597        .map(|(i, b)| (i / 6 * 4 + b) as u16)
1598        .collect::<Vec<_>>();
1599
1600    Buffer::new(device, wgpu::BufferUsages::INDEX, &indices)
1601}
1602
1603fn create_quad_index_buffer_u32(device: &wgpu::Device, vert_length: usize) -> Buffer<u32> {
1604    assert!(vert_length <= u32::MAX as usize);
1605    let indices = [0, 1, 2, 2, 1, 3]
1606        .iter()
1607        .cycle()
1608        .copied()
1609        .take(vert_length / 4 * 6)
1610        .enumerate()
1611        .map(|(i, b)| (i / 6 * 4 + b) as u32)
1612        .collect::<Vec<_>>();
1613
1614    Buffer::new(device, wgpu::BufferUsages::INDEX, &indices)
1615}
1616
1617/// Terrain-related buffers segment themselves by depth to allow us to do
1618/// primitive occlusion culling based on whether the camera is underground or
1619/// not. This struct specifies the buffer offsets at which various layers start
1620/// and end.
1621///
1622/// 'Deep' structures appear within the range `0..deep_end`.
1623///
1624/// 'Shallow' structures appear within the range `deep_end..underground_end`.
1625///
1626/// 'Surface' structures appear within the range `underground_end..`.
1627pub struct AltIndices {
1628    pub deep_end: usize,
1629    pub underground_end: usize,
1630}
1631
1632/// The mode with which culling based on the camera position relative to the
1633/// terrain is performed.
1634#[derive(Copy, Clone, Default)]
1635pub enum CullingMode {
1636    /// We need to render all elements of the given structure
1637    #[default]
1638    None,
1639    /// We only need to render surface and shallow (i.e: in the overlapping
1640    /// region) elements of the structure
1641    Surface,
1642    /// We only need to render shallow (i.e: in the overlapping region) and deep
1643    /// elements of the structure
1644    Underground,
1645}