1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
//! Mesh generation utilities.

use ::{cgmath};

use ::{vertex};

/// Produces vertices and indices for a 3D lines list arranged in a square grid
/// in the X/Y plane of `dims` by `dims` dimensions.
///
/// The number of vertices will be `(dims + 1)^2`.
///
/// The number of indices will be `4*(dims^2 + dims)`
///
/// # Panics
///
/// Panics if `dims` is zero
pub fn grid_3d_instanced_lines_list (index_offset : u32, dims : u16)
  -> (Vec <vertex::Vert3dInstanced>, Vec <u32>)
{
  assert!(0 < dims);
  let (num_vertices, num_indices) = grid_3d_instanced_lines_list_counts (dims);
  let dims = dims as u32;
  let mut vertices
    = Vec::<vertex::Vert3dInstanced>::with_capacity (num_vertices as usize);
  for i in 0..(dims+1) {
    for j in 0..(dims+1) {
      let x = i as f32 - 0.5 * dims as f32;
      let y = j as f32 - 0.5 * dims as f32;
      vertices.push (vertex::Vert3dInstanced { inst_position: [x, y, 0.0] })
    }
  }
  debug_assert_eq!(vertices.len(), num_vertices as usize);

  let mut indices  = Vec::<u32>::with_capacity (num_indices as usize);
  for i in 0..dims {
    for j in 0..dims {
      let base_index = index_offset + (i * (dims+1) + j);
      indices.push (base_index);
      indices.push (base_index + (dims+1));
      indices.push (base_index);
      indices.push (base_index + 1);
    }
  }
  let top_base_index   = index_offset + (dims+1) * dims;
  let right_base_index = index_offset + dims;
  for k in 0..dims {
    indices.push (top_base_index   + k);
    indices.push (top_base_index   + k + 1);
    indices.push (right_base_index + k * (dims+1));
    indices.push (right_base_index + (k + 1) * (dims+1));
  }
  debug_assert_eq!(indices.len(), num_indices as usize);

  (vertices, indices)
}

/// Returns the `(num_vertices, num_indices)` for a mesh generated with
/// `grid_3d_instanced_lines_list`
pub fn grid_3d_instanced_lines_list_counts (dims : u16) -> (u32, u32) {
  let dims = dims as u32;
  ( (dims+1) * (dims+1),
    4 * (dims * dims + dims) )
}

/// Generates a hemisphere with unit radius in the positive Z half-space
/// with a number of parallels equal to `latitude_divisions` and a number of
/// half-meridians equal to `longitude_divisions`
pub fn hemisphere_3d_instanced_lines_list (
  index_offset : u32, latitude_divisions : u16, longitude_divisions : u16
) -> (Vec <vertex::Vert3dInstanced>, Vec <u32>) {
  use std::f32::consts::PI;
  assert!(1 <= latitude_divisions);
  assert!(2 <= longitude_divisions);
  let (num_vertices, num_indices) = hemisphere_3d_instanced_lines_list_counts (
    latitude_divisions, longitude_divisions);
  let latitude_divisions  = latitude_divisions  as u32;
  let longitude_divisions = longitude_divisions as u32;
  let num_parallels       = latitude_divisions;
  let num_meridians       = longitude_divisions;
  let latitude_angle      = 0.5 * (PI / latitude_divisions  as f32);
  let longitude_angle     = 2.0 * (PI / longitude_divisions as f32);
  let mut vertices
    = Vec::<vertex::Vert3dInstanced>::with_capacity (num_vertices as usize);

  // the "north pole"
  vertices.push (vertex::Vert3dInstanced {
    inst_position: cgmath::Vector3::unit_z().into()
  });

  // for each parallel, generate a vertex for each meridian
  for i in 0..num_parallels {
    use cgmath::{Rotation, Rotation3};

    let i = i as f32 + 1.0;
    let v = cgmath::Basis3::from_angle_x (cgmath::Rad (i * latitude_angle))
      .rotate_vector (cgmath::Vector3::unit_z());
    for j in 0..num_meridians {
      let j = j as f32;
      let w = cgmath::Basis3::from_angle_z (cgmath::Rad (j * longitude_angle))
        .rotate_vector (v);
      // each meridian for this parallel
      vertices.push (vertex::Vert3dInstanced { inst_position: w.into() });
    }
  }
  debug_assert_eq!(vertices.len(), num_vertices as usize);

  let mut indices  = Vec::<u32>::with_capacity (num_indices as usize);
  // connect north pole to first parallel
  for i in 0..num_meridians {
    indices.push (index_offset + 0);
    indices.push (index_offset + 1 + i);
  }
  // connect each parallel with itself and the next parallel along the meridians
  for i in 0..num_parallels {
    let parallel_base_index = index_offset + 1 + i * num_meridians;
    for j in 0..num_meridians {
      indices.push (parallel_base_index + j);
      indices.push (parallel_base_index + (j + 1) % num_meridians);
      // only connect to the next parallel if this is not the *last* parallel
      if i < num_parallels-1 {
        indices.push (parallel_base_index + j);
        indices.push (parallel_base_index + j + num_meridians);
      }
    }
  }
  debug_assert_eq!(indices.len(), num_indices as usize);

  (vertices, indices)
}

pub fn hemisphere_3d_instanced_lines_list_counts (
  latitude_divisions : u16, longitude_divisions : u16
) -> (u32, u32) {
  let latitude_divisions  = latitude_divisions  as u32;
  let longitude_divisions = longitude_divisions as u32;
  (
    1 + latitude_divisions  * longitude_divisions,  // vertex count
    4 * longitude_divisions * latitude_divisions    // index count
  )
}

/// Produces vertices and indices for a 3D lines list unit sphere (radius
/// $1.0$) with the given number of latitudinal divisions rounded down to the
/// nearest even number (ensuring the sphere always has an 'equator'), and with
/// the given number of longitudinal divisions.
///
/// The number of parallels will be equal to $latitude_divisions -
/// (latitude_divisions % 2) - 1$ and the number of meridians will be equal to
/// $longitude_divisions$.
///
/// There will be $2 + (latitude_divisions-1) * longitude_divisions$
/// vertices and $4 * longitude_divisions * latitude_divisions -
/// 2 * longitude_divisions$ indices.
///
/// The first $4 * (latitude_divisions / 2) * longitude_divisions$ indices
/// can be used to render only the top hemisphere (the sphere itself is
/// computed progressively by adding more vertices and indices onto a base
/// hemisphere to form the southern hemisphere).
///
/// # Panics
///
/// Panics if `latitude_divisions` or `longitude_divisions` are less than two
/// (i.e. there must be at least an equator latitude dividing the north and
/// south hemispheres and a prime meridian dividing the east and west
/// hemispheres.
pub fn sphere_3d_instanced_lines_list (
  index_offset : u32, latitude_divisions : u16, longitude_divisions : u16
) -> (Vec <vertex::Vert3dInstanced>, Vec <u32>) {
  use std::f32::consts::PI;
  assert!(2 <= latitude_divisions);
  assert!(2 <= longitude_divisions);
  let (num_vertices, num_indices) = sphere_3d_instanced_lines_list_counts (
    latitude_divisions, longitude_divisions);
  let latitude_divisions  = (latitude_divisions - latitude_divisions % 2) as u32;
  let hemisphere_latitude_divisions = latitude_divisions / 2;
  let longitude_divisions = longitude_divisions as u32;
  let num_parallels       = latitude_divisions - 1;
  let num_meridians       = longitude_divisions;
  let latitude_angle      = PI / latitude_divisions  as f32;
  let longitude_angle     = 2.0 * (PI / longitude_divisions as f32);
  let (mut vertices, mut indices) = {
    let mut vertices
      = Vec::<vertex::Vert3dInstanced>::with_capacity (num_vertices as usize);
    let mut indices = Vec::<u32>::with_capacity (num_indices as usize);
    let (mut hemisphere_vertices, mut hemisphere_indices) =
      hemisphere_3d_instanced_lines_list (
        index_offset,
        hemisphere_latitude_divisions as u16,
        longitude_divisions as u16);
    vertices.append (&mut hemisphere_vertices);
    indices.append  (&mut hemisphere_indices);
    (vertices, indices)
  };
  let south_pole_index  = index_offset + vertices.len() as u32;
  // the "south pole"
  vertices.push (vertex::Vert3dInstanced {
    inst_position: (-1.0 * cgmath::Vector3::<f32>::unit_z()).into()
  });
  // for each southern parallel, generate a vertex for each meridian
  for i in 0..num_parallels / 2 {
    use cgmath::{Rotation, Rotation3};

    let i = i as f32 + 1.0;
    let v = cgmath::Basis3::from_angle_x (cgmath::Rad (-i * latitude_angle))
      .rotate_vector (-1.0 * cgmath::Vector3::<f32>::unit_z());
    for j in 0..num_meridians {
      let j = j as f32;
      let w = cgmath::Basis3::from_angle_z (cgmath::Rad (j * longitude_angle))
        .rotate_vector (v);
      // each meridian for this parallel
      vertices.push (vertex::Vert3dInstanced { inst_position: w.into() });
    }
  }
  debug_assert_eq!(vertices.len(), num_vertices as usize);

  // connect south pole to last parallel
  for i in 0..num_meridians {
    indices.push (south_pole_index);
    indices.push (south_pole_index + 1 + i);
  }
  // connect each southern parallel with itself and the next parallel along the
  // meridians
  for i in hemisphere_latitude_divisions..num_parallels {
    let parallel_base_index = index_offset + 2 + i * num_meridians;
    for j in 0..num_meridians {
      indices.push (parallel_base_index + j);
      indices.push (parallel_base_index + (j + 1) % num_meridians);
      if i < num_parallels-1 {
        // if this is not the last parallel, connect this to the next parallel
        indices.push (parallel_base_index + j);
        indices.push (parallel_base_index + j + num_meridians);
      } else {
        // if this is the last parallel, connect it with the equator
        indices.push (parallel_base_index + j);
        indices.push (south_pole_index - num_meridians + j);
      }
    }
  }
  debug_assert_eq!(indices.len(), num_indices as usize);

  (vertices, indices)
}

/// Returns the `(num_vertices, num_indices)` for a mesh generated with
/// `sphere_3d_instanced_lines_list`
pub fn sphere_3d_instanced_lines_list_counts (
  latitude_divisions : u16, longitude_divisions : u16
) -> (u32, u32) {
  let latitude_divisions  = (latitude_divisions - latitude_divisions % 2) as u32;
  let longitude_divisions = longitude_divisions as u32;
  ( 2 + (latitude_divisions - 1) * longitude_divisions,      // vertex_count
    2 * longitude_divisions * (2 * latitude_divisions - 1) ) // index count
}

/// Two hemispherical "caps" connected at their equators.
///
/// Intended to be scaled first and then each cap translated along the Z axis
/// to achieve the correct capsule height.
///
/// Can also be used to render a hemisphere or a sphere by slicing the
/// corresponding number of indices. Note that the sphere is slightly
/// degenerate since there are duplicate vertices on the equator, and so the
/// last `2 * longitude_divisions` indices will differ but the total index
/// count will be the same.
///
/// # Panics
///
/// Panics of `hemisphere_latitude_divisions` is zero or if
/// `longitude_divisions` is less than two.
pub fn capsule_3d_instanced_lines_list (
  index_offset : u32,
  hemisphere_latitude_divisions : u16, longitude_divisions : u16
) -> (Vec <vertex::Vert3dInstanced>, Vec <u32>) {
  let (num_vertices, num_indices) = capsule_3d_instanced_lines_list_counts (
    hemisphere_latitude_divisions, longitude_divisions);
  let mut vertices
    = Vec::<vertex::Vert3dInstanced>::with_capacity (num_vertices as usize);
  let mut indices = Vec::<u32>::with_capacity (num_indices as usize);
  { // generate upper hemisphere
    let (mut upper_vertices, mut upper_indices) =
       hemisphere_3d_instanced_lines_list (
        index_offset,
        hemisphere_latitude_divisions,
        longitude_divisions);
    vertices.append (&mut upper_vertices);
    indices.append  (&mut upper_indices);
  }
  let hemisphere_vertex_count = vertices.len() as u32;
  let hemisphere_index_count  = indices.len()  as u32;
  debug_assert_eq!(
   (hemisphere_vertex_count, hemisphere_index_count),
   hemisphere_3d_instanced_lines_list_counts (
    hemisphere_latitude_divisions, longitude_divisions)
  );
  { // generate lower hemisphere and flip Z axis
    let (mut lower_vertices, mut lower_indices) =
       hemisphere_3d_instanced_lines_list (
        index_offset + hemisphere_vertex_count,
        hemisphere_latitude_divisions,
        longitude_divisions);
    for vertex in lower_vertices.as_mut_slice() {
      vertex.inst_position[2] *= -1.0;
    }
    vertices.append (&mut lower_vertices);
    indices.append  (&mut lower_indices);
  }
  let double_hemisphere_vertex_count = 2 * hemisphere_vertex_count;
  // add lines connecting equators of each hemisphere
  for i in 0..longitude_divisions as u32 {
    indices.push (index_offset + double_hemisphere_vertex_count - 1 - i);
    indices.push (index_offset + hemisphere_vertex_count - 1 - i);
  }
  debug_assert_eq!(vertices.len(), num_vertices as usize);
  debug_assert_eq!(indices.len(),  num_indices as usize);

  (vertices, indices)
}

pub fn capsule_3d_instanced_lines_list_counts (
  hemisphere_latitude_divisions : u16, longitude_divisions : u16
) -> (u32, u32) {
  let (hemisphere_vertex_count, hemisphere_index_count)
    = hemisphere_3d_instanced_lines_list_counts (
        hemisphere_latitude_divisions, longitude_divisions);
  (
    2 * hemisphere_vertex_count,                               // vertex_count
    2 * (hemisphere_index_count + longitude_divisions as u32)  // index count
  )
}

/// Unit cylinder-- total height is 2.0 centered at 0.0 in the vertical (Z)
/// axis, radius 1.0 in the X/Y plane.
///
/// # Panics
///
/// Divisions must be 2 or greater.
pub fn cylinder_3d_instanced_lines_list (index_offset : u32, divisions : u16)
  -> (Vec <vertex::Vert3dInstanced>, Vec <u32>)
{
  use std::f32::consts::PI;
  assert!(2 <= divisions);
  let (num_vertices, num_indices) = cylinder_3d_instanced_lines_list_counts (
    divisions);
  let divisions      = divisions as u32;
  let division_angle = 2.0 * (PI / divisions as f32);
  let vertices = {
    let mut vertices
      = Vec::<vertex::Vert3dInstanced>::with_capacity (num_vertices as usize);
    let mut top
      = Vec::<vertex::Vert3dInstanced>::with_capacity (num_vertices as usize / 2);
    let mut bottom
      = Vec::<vertex::Vert3dInstanced>::with_capacity (num_vertices as usize / 2);
    for i in 0..divisions {
      use cgmath::{Rotation, Rotation3};
      let i = i as f32;
      let v = cgmath::Basis3::from_angle_z (cgmath::Rad (i * division_angle))
        .rotate_vector (cgmath::Vector3::unit_y());
      top.push    (vertex::Vert3dInstanced { inst_position: [v.x, v.y,  1.0] });
      bottom.push (vertex::Vert3dInstanced { inst_position: [v.x, v.y, -1.0] });
    }
    vertices.append (&mut top);
    vertices.append (&mut bottom);
    vertices
  };
  debug_assert_eq!(vertices.len(), num_vertices as usize);

  let mut indices  = Vec::<u32>::with_capacity (num_indices as usize);
  for i in 0..divisions {
    // connect to next vertex in the loop
    indices.push (index_offset + i);
    indices.push (index_offset + (i + 1) % divisions);
    // connect to lower loop
    indices.push (index_offset + i);
    indices.push (index_offset + i + divisions);
    // connect lower loop to next vertex
    indices.push (index_offset + divisions + i);
    indices.push (index_offset + divisions + (i + 1) % divisions);
  }
  debug_assert_eq!(indices.len(), num_indices as usize);

  (vertices, indices)
}

#[inline]
pub fn cylinder_3d_instanced_lines_list_counts (divisions : u16) -> (u32, u32) {
  // (vertex count, index count)
  ( 2 * divisions as u32, 6 * divisions as u32)
}