gl_utils/render/resource/
draw3d.rs

1use derive_more::From;
2use glium::{self, uniform};
3use strum::{EnumCount, EnumIter, FromRepr};
4use vec_map::VecMap;
5
6use math_utils as math;
7
8use crate::{color, mesh, render, shader, vertex, Mesh, Render};
9
10pub const MESH_GRID_DIMS          : u16 = 12;
11/// A default scale used when rending 3D sprites
12pub const DEFAULT_PIXELS_PER_UNIT : f32 = 64.0;
13
14/// 3d drawing resources.
15///
16/// ```text
17/// [                instance_vertices               ]
18/// ```
19pub struct Draw3d {
20  /// Vertex buffer containing per-instance vertices. Any of the below instanced
21  /// types can be rendered at one of these vertices.
22  instance_vertices : glium::VertexBuffer <vertex::Vert3dOrientationScaleColor>,
23
24  // TODO: combine abbs with basis vectors as variants of a 'primitive'
25  /// Range of per-instance vertices to draw AABB lines
26  instanced_aabb_lines     : std::ops::Range <u32>,
27  /// Range of per-instance vertices to draw AABB triangles
28  instanced_aabb_triangles : std::ops::Range <u32>,
29  instanced_billboards     : VecMap <InstancedBillboard>,
30  instanced_meshes         : InstancedMeshes,
31  pub user_buffers         : VecMap <glium::VertexBuffer <vertex::Vert3dColor>>,
32  pub user_draw            : VecMap <UserDraw>,
33}
34
35#[derive(Clone, Debug, Eq, PartialEq)]
36pub struct UserDraw {
37  pub buffer_key        : UserBufferKey,
38  /// Slice of the buffer to draw from
39  pub range             : std::ops::Range <u32>,
40  pub primitive_type    : glium::index::PrimitiveType,
41  pub shader_program_id : shader::ProgramId,
42  pub draw_pass         : DrawPass
43}
44
45#[derive(Clone, Copy, Debug, Eq, PartialEq)]
46pub struct UserBufferKey (pub u32);
47
48#[derive(Clone, Copy, Debug, Eq, PartialEq)]
49pub enum DrawPass {
50  Depth,
51  NoDepth
52}
53
54/// Wireframe meshes matched to ranges of per-instance vertices
55#[derive(Clone, Debug, Eq, PartialEq)]
56pub struct InstancedMesh {
57  /// Slice of `instanced_meshes.line_indices` corresponding to this mesh: each
58  /// instance of the mesh will draw an instance of the vertices mapped to by
59  /// the range of indices
60  pub line_indices_range : std::ops::Range <u32>,
61  /// Range of `instance_vertices` corresponding to this mesh: each of these
62  /// vertices will draw an instance of this mesh at that location
63  pub instances_range    : std::ops::Range <u32>,
64  pub shader_program_id  : shader::ProgramId,
65  pub draw_pass          : DrawPass
66}
67
68/// 3D billboards mapped to ranges of per-instance vertices
69pub struct InstancedBillboard {
70  pub texture         : glium::Texture2d,
71  /// Billboard will be drawn at this range of the `instance_vertices`
72  pub instances_range : std::ops::Range <u32>
73}
74
75/// Used to initialize per-instance vertex buffers
76#[derive(Default)]
77pub struct InstancesInit <'a> {
78  pub aabb_lines     : Option <&'a [vertex::Vert3dOrientationScaleColor]>,
79  pub aabb_triangles : Option <&'a [vertex::Vert3dOrientationScaleColor]>,
80  pub aabb_lines_and_triangles :
81    Option <&'a [vertex::Vert3dOrientationScaleColor]>,
82  pub meshes         : VecMap <&'a [vertex::Vert3dOrientationScaleColor]>,
83  pub billboards     : VecMap <&'a [vertex::Vert3dOrientationScaleColor]>
84}
85
86#[derive(Clone, Copy, Debug, Eq, PartialEq, From)]
87pub struct MeshKey (pub u32);
88
89#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, EnumCount, EnumIter,
90  FromRepr)]
91#[repr(u16)]
92pub enum MeshId {
93  Grid,
94  Hemisphere,
95  Sphere,
96  Capsule,
97  Cylinder
98}
99
100//
101//  private
102//
103
104struct InstancedMeshes {
105  /// 3D vertices for instanced drawing.
106  ///
107  /// Multiple instanced meshes are stored here, indexed by slices of
108  /// `line_indices`.
109  pub vertices     : glium::VertexBuffer <vertex::Vert3dInstanced>,
110  /// Indices for drawing instanced 3D meshes in `instanced_vertices`.
111  ///
112  /// Each separate mesh has a corresponding slice of indices in this index
113  /// buffer, with ranges stored in the `instanced_indices_lines_ranges`
114  /// field.
115  pub line_indices : glium::IndexBuffer <u32>,
116  /// Each instanced mesh defines a range of instanced line indices, a shader
117  /// program ID, and a range of instance vertices at which to draw an instance
118  pub meshes       : VecMap <InstancedMesh>,
119  // some uniforms for the capsule shader
120  pub capsule_vertex_id_offset : u32,
121  pub hemisphere_vertex_count  : u32
122}
123
124struct InstancedMeshInit {
125  pub instanced_vertex_data     : Vec <vertex::Vert3dInstanced>,
126  pub instanced_line_index_data : Vec <u32>,
127  pub line_indices_ranges       : VecMap <std::ops::Range <u32>>,
128  pub shader_program_ids        : VecMap <shader::ProgramId>,
129  pub draw_passes               : VecMap <DrawPass>,
130  pub capsule_vertex_id_offset  : u32,
131  pub hemisphere_vertex_count   : u32
132}
133
134////////////////////////////////////////////////////////////////////////////////
135//  impls
136////////////////////////////////////////////////////////////////////////////////
137
138impl Draw3d {
139  pub fn new (glium_display : &glium::Display <glutin::surface::WindowSurface>)
140    -> Self
141  {
142    let instanced_aabb_lines     = 0..0;   // empty
143    let instanced_aabb_triangles = 0..0;   // empty
144    let instanced_billboards     = VecMap::new();
145    let instanced_meshes         = InstancedMeshes::new (glium_display, vec![]);
146    let instance_vertices        = glium::VertexBuffer::dynamic (
147      glium_display,
148      // origin vertex
149      &[ vertex::Vert3dOrientationScaleColor {
150          position:    [0.0, 0.0, 0.0],
151          orientation: math::Matrix3::identity().into_col_arrays(),
152          scale:       [1.0, 1.0, 1.0],
153          color:       color::rgba_u8_to_rgba_f32 (color::DEBUG_CHARTREUSE)
154        }
155      ]
156    ).unwrap();
157    let user_buffers = VecMap::new();
158    let user_draw    = VecMap::new();
159    Draw3d {
160      instance_vertices,
161      instanced_aabb_lines,
162      instanced_aabb_triangles,
163      instanced_billboards,
164      instanced_meshes,
165      user_buffers,
166      user_draw
167    }
168  }
169
170  pub fn draw (
171    render      : &Render <render::resource::Default>,
172    glium_frame : &mut glium::Frame
173  ) {
174    let draw3d = &render.resource.draw3d;
175    // draw each viewport 3d
176    for (_, viewport) in render.viewports.iter() {
177      if let Some (camera3d) = viewport.camera3d() {
178        use glium::Surface;
179        // draw parameters: viewport
180        let draw_parameters_viewport = viewport.draw_parameters();
181        // draw parameters: depth test
182        let draw_parameters_write_depth = glium::DrawParameters {
183          depth: glium::Depth {
184            test:  glium::DepthTest::IfLess,
185            write: true,
186            .. glium::Depth::default()
187          },
188          .. draw_parameters_viewport.clone()
189        };
190        // draw parameters: polygon offset
191        let draw_parameters_polygon_offset = glium::DrawParameters {
192          polygon_offset: glium::draw_parameters::PolygonOffset {
193            factor: 1.0,
194            units: 1.0 / 1024.0,
195            fill: true,
196            .. Default::default()
197          },
198          backface_culling:
199            glium::draw_parameters::BackfaceCullingMode::CullCounterClockwise,
200          .. draw_parameters_write_depth.clone()
201        };
202        // uniforms
203        let (transform_mat_world_to_view, projection_mat_perspective) =
204          camera3d.view_mats();
205        let uniforms = uniform!{
206          uni_transform_mat_view:         transform_mat_world_to_view,
207          uni_projection_mat_perspective: projection_mat_perspective,
208          // TODO: variable pixels per unit?
209          uni_pixels_per_unit:            DEFAULT_PIXELS_PER_UNIT,
210          uni_capsule_vertex_id_offset:
211            draw3d.instanced_meshes.capsule_vertex_id_offset,
212          uni_hemisphere_vertex_count:
213            draw3d.instanced_meshes.hemisphere_vertex_count,
214          uni_color: color::rgba_u8_to_rgba_f32 (color::BLACK)
215        };
216
217        // draw aabbs lines
218        if !draw3d.instanced_aabb_lines.is_empty() {
219          let instances_range =
220            draw3d.instanced_aabb_lines.start as usize..
221            draw3d.instanced_aabb_lines.end   as usize;
222          glium_frame.draw (
223            draw3d.instance_vertices.slice (instances_range).unwrap(),
224            glium::index::IndicesSource::NoIndices {
225              primitives: glium::index::PrimitiveType::Points
226            },
227            &render.resource.shader_programs [
228              shader::ProgramId::WorldSpace3dAabbLines as usize
229            ],
230            &uniforms,
231            &draw_parameters_write_depth
232          ).unwrap();
233        }
234
235        // draw aabbs triangles
236        if !draw3d.instanced_aabb_triangles.is_empty() {
237          let instances_range =
238            draw3d.instanced_aabb_triangles.start as usize..
239            draw3d.instanced_aabb_triangles.end   as usize;
240          glium_frame.draw (
241            draw3d.instance_vertices.slice (instances_range).unwrap(),
242            glium::index::IndicesSource::NoIndices {
243              primitives: glium::index::PrimitiveType::Points
244            },
245            &render.resource.shader_programs [
246              shader::ProgramId::WorldSpace3dAabbTriangles as usize
247            ],
248            &uniforms,
249            &draw_parameters_polygon_offset
250          ).unwrap();
251        }
252
253        // draw instanced meshes with depth
254        for (_mesh_key, instanced_mesh) in draw3d.instanced_meshes.meshes.iter() {
255          if instanced_mesh.draw_pass != DrawPass::Depth {
256            continue
257          }
258          if !instanced_mesh.instances_range.is_empty() {
259            let (line_indices_range, instances_range) = (
260              instanced_mesh.line_indices_range.start as usize..
261              instanced_mesh.line_indices_range.end   as usize,
262              instanced_mesh.instances_range.start as usize..
263              instanced_mesh.instances_range.end   as usize
264            );
265            glium_frame.draw (
266              (&draw3d.instanced_meshes.vertices,
267                draw3d.instance_vertices.slice (instances_range).unwrap()
268                  .per_instance().unwrap()
269              ),
270              draw3d.instanced_meshes.line_indices.slice (line_indices_range)
271                .unwrap(),
272              &render.resource.shader_programs [instanced_mesh.shader_program_id
273                as usize],
274              &uniforms,
275              &draw_parameters_write_depth
276            ).unwrap();
277          }
278        }
279
280        // user draw calls with depth
281        for user_draw in draw3d.user_draw.values() {
282          if user_draw.draw_pass != DrawPass::Depth {
283            continue
284          }
285          let vertex_buffer = draw3d.user_buffers
286            .get (user_draw.buffer_key.index()).unwrap();
287          let vertex_range  =
288            user_draw.range.start as usize..
289            user_draw.range.end   as usize;
290          let uniforms = uniform!{
291            uni_transform_mat_view:         transform_mat_world_to_view,
292            uni_projection_mat_perspective: projection_mat_perspective,
293            // TODO: variable pixels per unit?
294            uni_pixels_per_unit:            DEFAULT_PIXELS_PER_UNIT,
295            uni_capsule_vertex_id_offset:
296              draw3d.instanced_meshes.capsule_vertex_id_offset,
297            uni_hemisphere_vertex_count:
298              draw3d.instanced_meshes.hemisphere_vertex_count
299          };
300          glium_frame.draw (
301            vertex_buffer.slice (vertex_range).unwrap(),
302            glium::index::NoIndices (user_draw.primitive_type),
303            &render.resource.shader_programs [user_draw.shader_program_id.index()],
304            &uniforms,
305            &draw_parameters_write_depth
306          ).unwrap();
307        }
308
309        // draw instanced meshes w/o depth
310        for (_mesh_key, instanced_mesh) in draw3d.instanced_meshes.meshes.iter() {
311          if instanced_mesh.draw_pass != DrawPass::NoDepth {
312            continue
313          }
314          if !instanced_mesh.instances_range.is_empty() {
315            let (line_indices_range, instances_range) = (
316              instanced_mesh.line_indices_range.start as usize..
317              instanced_mesh.line_indices_range.end   as usize,
318              instanced_mesh.instances_range.start as usize..
319              instanced_mesh.instances_range.end   as usize
320            );
321            glium_frame.draw (
322              (&draw3d.instanced_meshes.vertices,
323                draw3d.instance_vertices.slice (instances_range).unwrap()
324                  .per_instance().unwrap()
325              ),
326              draw3d.instanced_meshes.line_indices.slice (line_indices_range)
327                .unwrap(),
328              &render.resource.shader_programs [instanced_mesh.shader_program_id
329                as usize],
330              &uniforms,
331              &draw_parameters_viewport
332            ).unwrap();
333          }
334        }
335
336        // user draw calls with w/o depth
337        for user_draw in draw3d.user_draw.values() {
338          if user_draw.draw_pass != DrawPass::NoDepth {
339            continue
340          }
341          let vertex_buffer = draw3d.user_buffers
342            .get (user_draw.buffer_key.index()).unwrap();
343          let vertex_range  =
344            user_draw.range.start as usize..
345            user_draw.range.end   as usize;
346          glium_frame.draw (
347            vertex_buffer.slice (vertex_range).unwrap(),
348            glium::index::NoIndices (user_draw.primitive_type),
349            &render.resource.shader_programs [user_draw.shader_program_id.index()],
350            &uniforms,
351            &draw_parameters_viewport
352          ).unwrap();
353        }
354
355        // draw 3d billboards
356        // TODO: draw some or all billboards with depth?
357        for (_, instanced_billboard) in draw3d.instanced_billboards.iter() {
358          let instances_range =
359            instanced_billboard.instances_range.start as usize..
360            instanced_billboard.instances_range.end   as usize;
361          let uniforms = uniform!{
362            uni_transform_mat_view:         transform_mat_world_to_view,
363            uni_projection_mat_perspective: projection_mat_perspective,
364            uni_sampler2d:                  instanced_billboard.texture.sampled()
365              .magnify_filter (glium::uniforms::MagnifySamplerFilter::Nearest),
366            // TODO: variable pixels per unit?
367            uni_pixels_per_unit:            DEFAULT_PIXELS_PER_UNIT
368          };
369          glium_frame.draw (
370            draw3d.instance_vertices.slice (instances_range).unwrap(),
371            glium::index::IndicesSource::NoIndices {
372              primitives: glium::index::PrimitiveType::Points
373            },
374            &render.resource.shader_programs [
375              shader::ProgramId::WorldSpace3dSprite as usize
376            ],
377            &uniforms,
378            &draw_parameters_viewport
379          ).unwrap();
380        }
381      }
382    } // end loop over viewports
383  } // end draw
384
385  #[inline]
386  pub const fn instance_vertices (&self)
387    -> &glium::VertexBuffer <vertex::Vert3dOrientationScaleColor>
388  {
389    &self.instance_vertices
390  }
391
392  #[inline]
393  pub const fn instanced_aabb_lines (&self) -> &std::ops::Range <u32> {
394    &self.instanced_aabb_lines
395  }
396
397  #[inline]
398  pub fn set_instanced_aabb_lines (&mut self, range : std::ops::Range <u32>) {
399    debug_assert!(range.end <= self.instance_vertices.len() as u32);
400    self.instanced_aabb_lines = range;
401  }
402
403  #[inline]
404  pub const fn instanced_aabb_triangles (&self) -> &std::ops::Range <u32> {
405    &self.instanced_aabb_triangles
406  }
407
408  #[inline]
409  pub fn set_instanced_aabb_triangles (&mut self, range : std::ops::Range <u32>) {
410    debug_assert!(range.end <= self.instance_vertices.len() as u32);
411    self.instanced_aabb_triangles = range;
412  }
413
414  #[inline]
415  pub const fn instanced_meshes (&self) -> &VecMap <InstancedMesh> {
416    &self.instanced_meshes.meshes
417  }
418
419  #[inline]
420  pub fn set_instanced_mesh (&mut self,
421    mesh_key : MeshKey, mesh : InstancedMesh
422  ) {
423    let _ = self.instanced_meshes.meshes.insert (mesh_key.index(), mesh);
424  }
425
426  /// Re-builds instanced buffers to include given instanced meshes. The
427  /// provided instanced mesh keys must not overlap with any of the built-in
428  /// `MeshId`s.
429  pub fn rebuild_instanced_meshes (&mut self,
430    glium_display : &glium::Display <glutin::surface::WindowSurface>,
431    user_meshes   : Vec <(MeshKey, Mesh, DrawPass)>
432  ) {
433    self.instanced_meshes = InstancedMeshes::new (glium_display, user_meshes);
434  }
435
436  /// Creates a new vertex buffer holding per-instance 3D vertices for various
437  /// instanced meshes (grid, hemisphere, sphere, cylinder, capsule), AABBs, and
438  /// tile billboards, and sets the instanced ranges corresponding to each
439  pub fn instance_vertices_set (&mut self,
440    glium_display  : &glium::Display <glutin::surface::WindowSurface>,
441    instances_init : InstancesInit
442  ) {
443    let mut instance_vertices =
444      Vec::with_capacity (instances_init.instance_count());
445
446    self.instanced_aabb_lines     = 0..0;
447    self.instanced_aabb_triangles = 0..0;
448    for mesh in self.instanced_meshes.meshes.values_mut() {
449      mesh.instances_range = 0..0;
450    }
451    // aabbs: we allow the ranges for lines and triangles to overlap so that
452    // aabb_lines_and_triangles can be placed between the lines-only and
453    // triangles-only ranges
454    if let Some (instances) = instances_init.aabb_lines {
455      // lines only
456      let start = instance_vertices.len() as u32;
457      instance_vertices.extend_from_slice (instances);
458      let end   = instance_vertices.len() as u32;
459      self.instanced_aabb_lines = start..end;
460    }
461    if let Some (instances) = instances_init.aabb_lines_and_triangles {
462      // lines and triangles
463      let start = instance_vertices.len() as u32;
464      instance_vertices.extend_from_slice (instances);
465      let end   = instance_vertices.len() as u32;
466      if self.instanced_aabb_lines.end != 0 {
467        debug_assert!(instances_init.aabb_lines.is_none());
468        self.instanced_aabb_lines.start = start;
469      }
470      self.instanced_aabb_lines.end = end;
471      self.instanced_aabb_triangles = start..end;
472    }
473    if let Some (instances) = instances_init.aabb_triangles {
474      // triangles only
475      let start = instance_vertices.len() as u32;
476      instance_vertices.extend_from_slice (instances);
477      let end   = instance_vertices.len() as u32;
478      if self.instanced_aabb_triangles.end == 0 {
479        debug_assert!(instances_init.aabb_lines_and_triangles.is_none());
480        self.instanced_aabb_triangles.start = start;
481      }
482      self.instanced_aabb_triangles.end = end;
483    }
484
485    // meshes
486    for (mesh_key, instances) in instances_init.meshes.into_iter() {
487      let start = instance_vertices.len() as u32;
488      instance_vertices.extend_from_slice (instances);
489      let end   = instance_vertices.len() as u32;
490      self.instanced_meshes.meshes[mesh_key].instances_range = start..end;
491    }
492
493    // billboards
494    for (billboard_key, instances) in instances_init.billboards.into_iter() {
495      let start = instance_vertices.len() as u32;
496      instance_vertices.extend_from_slice (instances);
497      let end   = instance_vertices.len() as u32;
498      self.instanced_billboards[billboard_key].instances_range = start..end;
499    }
500
501    // create per instance vertex buffer
502    self.instance_vertices = glium::VertexBuffer::dynamic (
503      glium_display, instance_vertices.as_slice()
504    ).unwrap();
505  }
506
507  #[inline]
508  pub fn instance_vertices_aabb_lines_write (&self,
509    vertex_data : &[vertex::Vert3dOrientationScaleColor]
510  ) {
511    let range =
512      self.instanced_aabb_lines.start as usize..
513      self.instanced_aabb_lines.end   as usize;
514    self.instance_vertices.slice (range).unwrap().write (vertex_data);
515  }
516
517  #[inline]
518  pub fn instance_vertices_aabb_triangles_write (&self,
519    vertex_data : &[vertex::Vert3dOrientationScaleColor]
520  ) {
521    let range =
522      self.instanced_aabb_triangles.start as usize..
523      self.instanced_aabb_triangles.end   as usize;
524    self.instance_vertices.slice (range).unwrap().write (vertex_data);
525  }
526
527  #[inline]
528  pub fn instance_vertices_billboard_write (&self,
529    billboard_key : usize,
530    vertex_data   : &[vertex::Vert3dOrientationScaleColor]
531  ) {
532    let range = {
533      let range = self.instanced_billboards[billboard_key].instances_range.clone();
534      range.start as usize..range.end as usize
535    };
536    self.instance_vertices.slice (range).unwrap().write (vertex_data);
537  }
538
539  #[inline]
540  pub fn instance_vertices_mesh_write (&self,
541    mesh_key    : usize,
542    vertex_data : &[vertex::Vert3dOrientationScaleColor]
543  ) {
544    let range = {
545      let range = self.instanced_meshes.meshes[mesh_key].instances_range.clone();
546      range.start as usize..range.end as usize
547    };
548    self.instance_vertices.slice (range).unwrap().write (vertex_data);
549  }
550
551  /// Create a new instanced billboard by blitting a string of tiles to a new
552  /// texture.
553  ///
554  /// Panics if billboard texture with key already exists.
555  pub fn tile_billboard_create (&mut self,
556    glium_display   : &glium::Display <glutin::surface::WindowSurface>,
557    tileset_texture : &glium::Texture2d,
558    billboard_key   : usize,
559    instances_range : std::ops::Range <u32>,
560    string          : &str
561  ) {
562    use glium::Surface;
563    debug_assert_eq!(0, tileset_texture.width() %16);
564    debug_assert_eq!(0, tileset_texture.height()%16);
565    let tile_width  = tileset_texture.width()  / 16;
566    let tile_height = tileset_texture.height() / 16;
567    let texture = glium::Texture2d::empty_with_mipmaps (
568      glium_display, glium::texture::MipmapsOption::NoMipmap,
569      tile_width * string.len() as u32, tile_height
570    ).unwrap();
571    { // blit tiles from default tileset
572      let source     = tileset_texture.as_surface();
573      let mut target = texture.as_surface();
574      target.clear_color (1.0, 0.0, 1.0, 1.0);
575      for (i,ch) in string.chars().enumerate() {
576        let tile = ch as u32;
577        // NB: (0,0) is bottom-left in texture pixel space
578        let source_rect = glium::Rect {
579          left:   tile_width  * (tile % 16),
580          bottom: tile_height * (15 - tile / 16),
581          width:  tile_width,
582          height: tile_height
583        };
584        #[expect(clippy::identity_op)]
585        let target_rect = glium::BlitTarget {
586          left:   0 + i as u32 * tile_width,
587          bottom: 0,
588          width:  tile_width  as i32,
589          height: tile_height as i32
590        };
591        target.blit_from_simple_framebuffer (
592          &source, &source_rect, &target_rect,
593          glium::uniforms::MagnifySamplerFilter::Linear);
594      }
595    }
596    let instanced_billboard = InstancedBillboard { texture, instances_range };
597    assert!(self.instanced_billboards.insert (
598      billboard_key, instanced_billboard
599    ).is_none());
600  }
601}
602
603impl InstancesInit <'_> {
604  pub fn instance_count (&self) -> usize {
605    let mut count = 0;
606    count += self.aabb_lines.map_or(0, <[_]>::len);
607    count += self.aabb_triangles.map_or(0, <[_]>::len);
608    for (_, mesh_data) in self.meshes.iter() {
609      count += mesh_data.len();
610    }
611    for (_, billboard_data) in self.billboards.iter() {
612      count += billboard_data.len();
613    }
614    count
615  }
616}
617
618impl InstancedMeshes {
619  pub fn new (
620    glium_display : &glium::Display <glutin::surface::WindowSurface>,
621    user_meshes   : Vec <(MeshKey, Mesh, DrawPass)>
622  ) -> Self {
623    let InstancedMeshInit {
624      instanced_vertex_data,
625      instanced_line_index_data,
626      line_indices_ranges,
627      shader_program_ids,
628      draw_passes,
629      capsule_vertex_id_offset,
630      hemisphere_vertex_count
631    } = InstancedMeshInit::new (user_meshes);
632    let vertices     = glium::VertexBuffer::dynamic (
633      glium_display, instanced_vertex_data.as_slice()
634    ).unwrap();
635    let line_indices = glium::IndexBuffer::dynamic (
636      glium_display, glium::index::PrimitiveType::LinesList,
637      instanced_line_index_data.as_slice()
638    ).unwrap();
639    let meshes       = {
640      let mut v = VecMap::new();
641      for (mesh_key, line_indices_range) in line_indices_ranges.into_iter() {
642        let instanced_mesh = InstancedMesh {
643          line_indices_range,
644          instances_range: 0..0,  // empty
645          shader_program_id: shader_program_ids[mesh_key],
646          draw_pass:         draw_passes[mesh_key]
647        };
648        assert!(v.insert (mesh_key, instanced_mesh).is_none());
649      }
650      v
651    };
652    InstancedMeshes {
653      vertices, line_indices, meshes, capsule_vertex_id_offset,
654      hemisphere_vertex_count
655    }
656  }
657}
658
659impl InstancedMeshInit {
660  pub fn new (user_meshes : Vec <(MeshKey, Mesh, DrawPass)>) -> Self {
661    const GRID_DIMS                 : u16 = MESH_GRID_DIMS;
662    const HEMISPHERE_LATITUDE_DIVS  : u16 = 6;
663    const SPHERE_LATITUDE_DIVS      : u16 = 2 * HEMISPHERE_LATITUDE_DIVS;
664    const LONGITUDE_DIVS            : u16 = 24;
665    const CYLINDER_DIVS             : u16 = LONGITUDE_DIVS;
666    let mut instanced_vertex_data     = Vec::new();
667    let mut instanced_line_index_data = Vec::new();
668    // constant value to shift all indices during mesh creation
669    let mut index_offset      = 0;
670    // the beginning of the range where indices begin for the next mesh
671    let mut index_range_start = 0;
672
673    let mut line_indices_ranges = VecMap::with_capacity (MeshId::COUNT);
674    let mut shader_program_ids  = VecMap::with_capacity (MeshId::COUNT);
675    let mut draw_passes         = VecMap::with_capacity (MeshId::COUNT);
676
677    // grid
678    let mesh::Lines3d {
679      vertices: mut grid_vertex_data, indices: mut grid_index_data
680    } = mesh::Lines3d::grid (index_offset, GRID_DIMS);
681    assert!(line_indices_ranges.insert (
682      MeshId::Grid as usize,
683      index_range_start..index_range_start + grid_index_data.len() as u32
684    ).is_none());
685    assert!(shader_program_ids.insert (
686      MeshId::Grid as usize,
687      shader::ProgramId::ModelSpace3dInstancedOrientationScaleColor
688    ).is_none());
689    assert!(draw_passes.insert (MeshId::Grid as usize, DrawPass::Depth)
690      .is_none());
691    instanced_vertex_data.append (&mut grid_vertex_data);
692    instanced_line_index_data.append  (&mut grid_index_data);
693    index_offset      = instanced_vertex_data.len() as u32;
694    index_range_start = instanced_line_index_data.len() as u32;
695
696    // capsule: vertex and index data will be shared with sphere and hemisphere
697    // meshes
698    let capsule_vertex_id_offset = index_offset; // uniform used by capsule shader
699    let mesh::Lines3d {
700      vertices: mut capsule_vertex_data,
701      indices:  mut capsule_index_data
702    } = mesh::Lines3d::capsule (
703      index_offset, HEMISPHERE_LATITUDE_DIVS, LONGITUDE_DIVS);
704    let capsule_line_indices_range =
705      index_range_start..index_range_start + capsule_index_data.len() as u32;
706    assert!(line_indices_ranges.insert (
707      MeshId::Capsule as usize, capsule_line_indices_range.clone()
708    ).is_none());
709    assert!(shader_program_ids.insert (
710      MeshId::Capsule as usize,
711      shader::ProgramId::ModelSpace3dInstancedCapsule
712    ).is_none());
713    assert!(draw_passes.insert (MeshId::Capsule as usize, DrawPass::Depth)
714      .is_none());
715    instanced_vertex_data.append (&mut capsule_vertex_data);
716    instanced_line_index_data.append  (&mut capsule_index_data);
717
718    index_offset      = instanced_vertex_data.len() as u32;
719    index_range_start = instanced_line_index_data.len() as u32;
720
721    // hemisphere: this is defined to share the top half of the vertices and
722    // indices of the capsule mesh
723    let (hemisphere_vertex_count, hemisphere_index_count) =
724      mesh::hemisphere::lines3d_vertex_index_counts (
725        HEMISPHERE_LATITUDE_DIVS, LONGITUDE_DIVS);
726    assert!(line_indices_ranges.insert (
727      MeshId::Hemisphere as usize,
728      capsule_line_indices_range.start..
729      capsule_line_indices_range.start + hemisphere_index_count
730    ).is_none());
731    assert!(shader_program_ids.insert (
732      MeshId::Hemisphere as usize,
733      shader::ProgramId::ModelSpace3dInstancedScaleColor
734    ).is_none());
735    assert!(draw_passes.insert (MeshId::Hemisphere as usize, DrawPass::Depth)
736      .is_none());
737
738    // sphere: defined to use part of the capsule mesh indices except for the
739    // extra equator lines and cylinder lines
740    let (_, sphere_index_count) = mesh::sphere::lines3d_vertex_index_counts (
741      SPHERE_LATITUDE_DIVS, LONGITUDE_DIVS);
742    assert!(line_indices_ranges.insert (
743      MeshId::Sphere as usize,
744      capsule_line_indices_range.start..
745      capsule_line_indices_range.start + sphere_index_count
746    ).is_none());
747    assert!(shader_program_ids.insert (
748      MeshId::Sphere as usize,
749      shader::ProgramId::ModelSpace3dInstancedScaleColor
750    ).is_none());
751    assert!(draw_passes.insert (MeshId::Sphere as usize, DrawPass::Depth)
752      .is_none());
753
754    // cylinder
755    let mesh::Lines3d {
756      vertices: mut cylinder_vertex_data, indices: mut cylinder_index_data
757    } = mesh::Lines3d::cylinder (index_offset, CYLINDER_DIVS);
758    assert!(line_indices_ranges.insert (
759      MeshId::Cylinder as usize,
760      index_range_start..index_range_start + cylinder_index_data.len() as u32
761    ).is_none());
762    assert!(shader_program_ids.insert (
763      MeshId::Cylinder as usize,
764      shader::ProgramId::ModelSpace3dInstancedScaleColor
765    ).is_none());
766    assert!(draw_passes.insert (MeshId::Cylinder as usize, DrawPass::Depth)
767      .is_none());
768    instanced_vertex_data.append (&mut cylinder_vertex_data);
769    instanced_line_index_data.append  (&mut cylinder_index_data);
770
771    // NB: the following is not required between meshes that share all vertices
772    // comment this out between each new mesh when adding more meshes here:
773    //index_offset      = instanced_vertex_data.len()     as u32;
774    //index_range_start = instanced_line_index_data.len() as u32;
775
776    // user meshes
777    let num_user_meshes = user_meshes.len();
778    for (mesh_key, mut mesh, draw_pass) in user_meshes {
779      debug_assert!(mesh_key.index() >= MeshId::COUNT);
780      index_offset      = instanced_vertex_data.len()     as u32;
781      index_range_start = instanced_line_index_data.len() as u32;
782      match mesh {
783        Mesh::Lines3d (mesh::Lines3d { ref mut vertices, ref mut indices }) => {
784          indices.iter_mut().for_each (|ix| *ix += index_offset);
785          assert!(line_indices_ranges.insert (
786            mesh_key.index(),
787            index_range_start..index_range_start + indices.len() as u32
788          ).is_none());
789          assert!(shader_program_ids.insert (
790            mesh_key.index(),
791            shader::ProgramId::ModelSpace3dInstancedOrientationScaleColor
792          ).is_none());
793          assert!(draw_passes.insert (mesh_key.index(), draw_pass).is_none());
794          instanced_vertex_data.append (vertices);
795          instanced_line_index_data.append (indices);
796        }
797      }
798    }
799
800    debug_assert_eq!(line_indices_ranges.len(), MeshId::COUNT + num_user_meshes);
801    debug_assert_eq!(shader_program_ids.len(),  MeshId::COUNT + num_user_meshes);
802
803    InstancedMeshInit {
804      instanced_vertex_data,
805      instanced_line_index_data,
806      line_indices_ranges,
807      shader_program_ids,
808      draw_passes,
809      capsule_vertex_id_offset,
810      hemisphere_vertex_count
811    }
812  }
813}
814
815impl MeshKey {
816  pub const fn index (self) -> usize {
817    self.0 as usize
818  }
819}
820
821impl UserBufferKey {
822  pub const fn index (self) -> usize {
823    self.0 as usize
824  }
825}