1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Tessellation features.
//!
//! # Tessellation mode
//!
//! Tessellation is geometric information. Currently, several kinds of tessellation are supported:
//!
//! - *point clouds*;
//! - *lines*;
//! - *line strips*;
//! - *triangles*;
//! - *triangle fans*;
//! - *triangle strips*.
//!
//! Those kinds of tessellation are designated by the `Mode` type.
//!
//! # Tessellation creation
//!
//! Creation is done via the `Tess::new` function. This function is polymorphing in the type of
//! vertices you send. See the `TessVertices` type for further details.
//!
//! # Tessellation vertices mapping
//!
//! It’s possible to map `Tess`’ vertices into your code. You’re provided with two types to do so:
//!
//! - `BufferSlice`, which gives you an immutable access to the vertices
//! - `BufferSliceMut`, which gives you a mutable access to the vertices
//!
//! You can retrieve those slices with the `Tess::as_slice` and `Tess::as_slice_mut` methods. 
//!
//! # Tessellation render
//!
//! In order to render a `Tess`, you have to use a `TessSlice` object. You’ll be able to use that
//! object in *pipelines*. See the `pipeline` module for further details.

use gl;
use gl::types::*;
use std::error::Error;
use std::fmt;
use std::marker::PhantomData;
use std::mem::size_of;
use std::ops::{Range, RangeFull, RangeFrom, RangeTo};
use std::os::raw::c_void;
use std::ptr;

use buffer::{Buffer, BufferError, BufferSlice, BufferSliceMut, RawBuffer};
use context::GraphicsContext;
use vertex::{Dim, Type, Vertex, VertexComponentFormat};

/// Vertices can be connected via several modes.
#[derive(Copy, Clone, Debug)]
pub enum Mode {
  /// A single point.
  Point,
  /// A line, defined by two points.
  Line,
  /// A strip line, defined by at least two points and zero or many other ones.
  LineStrip,
  /// A triangle, defined by three points.
  Triangle,
  /// A triangle fan, defined by at least three points and zero or many other ones.
  TriangleFan,
  /// A triangle strip, defined by at least three points and zero or many other ones.
  TriangleStrip
}

/// Error that can occur while trying to map GPU tessellation to host code.
#[derive(Debug, Eq, PartialEq)]
pub enum TessMapError {
  VertexBufferMapFailed(BufferError),
  ForbiddenAttributelessMapping
}

impl fmt::Display for TessMapError {
  fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
    match *self {
      TessMapError::VertexBufferMapFailed(ref e) => {
        write!(f, "cannot map tessallation buffer: {}", e)
      }

      TessMapError::ForbiddenAttributelessMapping => {
        f.write_str("cannot map an attributeless buffer")
      }
    }
  }
}

impl Error for TessMapError {
  fn cause(&self) -> Option<&Error> {
    match *self {
      TessMapError::VertexBufferMapFailed(ref e) => Some(e),
      _ => None
    }
  }
}

/// Accepted vertices for building tessellations.
///
/// This type enables you to pass in a slice of vertices or ask for the GPU to only reserve enough
/// space for the number of vertices, leaving the allocated memory uninitialized.
#[derive(Debug, Eq, PartialEq)]
pub enum TessVertices<'a, T> where T: 'a + Vertex {
  /// Pass in a slice of vertices.
  Fill(&'a [T]),
  /// Reserve a certain number of vertices.
  Reserve(usize)
}

impl<'a, T> From<&'a [T]> for TessVertices<'a, T> where T: 'a + Vertex {
  fn from(slice: &'a [T]) -> Self {
    TessVertices::Fill(slice)
  }
}

/// GPU typed tessellation.
///
/// The tessellation is typed with the vertex type.
pub struct Tess<V> {
  mode: GLenum,
  vert_nb: usize,
  vao: GLenum,
  vbo: Option<RawBuffer>, // no vbo means attributeless render
  ibo: Option<RawBuffer>,
  _v: PhantomData<V>
}

impl<V> Tess<V> where V: Vertex {
  /// Create a new tessellation.
  ///
  /// The `mode` argument gives the type of the primitives and how to interpret the `vertices` and
  /// `indices` slices. If `indices` is set to `None`, the tessellation will use the `vertices`
  /// as-is.
  pub fn new<'a, C, W, I>(ctx: &mut C, mode: Mode, vertices: W, indices: I) -> Self
      where C: GraphicsContext,
            TessVertices<'a, V>: From<W>,
            V: 'a + Vertex,
            I: Into<Option<&'a[u32]>> {
    let vertices = vertices.into();

    let mut vao: GLuint = 0;
    let vert_nb = match vertices {
      TessVertices::Fill(slice) => slice.len(),
      TessVertices::Reserve(nb) => nb
    };

    unsafe {
      gl::GenVertexArrays(1, &mut vao);

      ctx.state().borrow_mut().bind_vertex_array(vao);

      // vertex buffer
      let vertex_buffer = Buffer::new(ctx, vert_nb);

      // fill the buffer with vertices only if asked by the user
      if let TessVertices::Fill(verts) = vertices {
        vertex_buffer.fill(verts).unwrap();
      }

      let raw_vbo = vertex_buffer.to_raw();

      ctx.state().borrow_mut().bind_array_buffer(raw_vbo.handle()); // FIXME: issue the call whatever the caching result
      set_vertex_pointers(&V::vertex_format());

      // TODO: refactor this schiesse
      // in case of indexed render, create an index buffer
      if let Some(indices) = indices.into() {
        let ind_nb = indices.len();
        let index_buffer = Buffer::new(ctx, ind_nb);
        index_buffer.fill(indices).unwrap();

        let raw_ibo = index_buffer.to_raw();

        gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, raw_ibo.handle());

        ctx.state().borrow_mut().bind_vertex_array(vao);

        Tess {
          mode: opengl_mode(mode),
          vert_nb: ind_nb,
          vao: vao,
          vbo: Some(raw_vbo),
          ibo: Some(raw_ibo),
          _v: PhantomData
        }
      } else {
        ctx.state().borrow_mut().bind_vertex_array(vao);

        Tess {
          mode: opengl_mode(mode),
          vert_nb: vert_nb,
          vao: vao,
          vbo: Some(raw_vbo),
          ibo: None,
          _v: PhantomData
        }
      }
    }
  }

  // Render the tessellation by providing the number of vertices to pick from it and how many
  // instances are wished.
  fn render<C>(
    &self,
    ctx: &mut C,
    start_index: usize,
    vert_nb: usize,
    inst_nb: usize
  )
  where C: GraphicsContext {
    let vert_nb = vert_nb as GLsizei;
    let inst_nb = inst_nb as GLsizei;

    unsafe {
      ctx.state().borrow_mut().bind_vertex_array(self.vao);

      if self.ibo.is_some() { // indexed render
        let first = (size_of::<u32>() * start_index) as *const c_void;

        if inst_nb == 1 {
          gl::DrawElements(self.mode, vert_nb, gl::UNSIGNED_INT, first);
        } else if inst_nb > 1 {
          gl::DrawElementsInstanced(self.mode, vert_nb, gl::UNSIGNED_INT, first, inst_nb);
        } else {
          panic!("cannot index-render 0 instance");
        }
      } else { // direct render
        let first = start_index as GLint;

        if inst_nb == 1 {
          gl::DrawArrays(self.mode, first, vert_nb);
        } else if inst_nb > 1 {
          gl::DrawArraysInstanced(self.mode, first, vert_nb, inst_nb);
        } else {
          panic!("cannot render 0 instance");
        }
      }
    }
  }

  /// Get an immutable slice over the vertices stored on GPU.
  pub fn as_slice(&self) -> Result<BufferSlice<V>, TessMapError> {
    self.vbo.as_ref()
      .ok_or(TessMapError::ForbiddenAttributelessMapping)
      .and_then(|raw| RawBuffer::as_slice(raw).map_err(TessMapError::VertexBufferMapFailed))
  }

  /// Get a mutable slice over the vertices stored on GPU.
  pub fn as_slice_mut<C>(&mut self) -> Result<BufferSliceMut<V>, TessMapError> {
    self.vbo.as_mut()
      .ok_or(TessMapError::ForbiddenAttributelessMapping)
      .and_then(|raw| RawBuffer::as_slice_mut(raw).map_err(TessMapError::VertexBufferMapFailed))
  }
}

impl Tess<()> {
  /// Create a tessellation that will procedurally generate its vertices (i.e. *attribute-less*).
  ///
  /// You just have to give the `Mode` to use and the number of vertices the tessellation must
  /// generate. You’ll be handed back a tessellation object that doesn’t actually hold anything.
  /// You will have to generate the vertices on the fly in your shaders.
  pub fn attributeless<C>(
    ctx: &mut C,
    mode: Mode,
    vert_nb: usize
  ) -> Self
  where C: GraphicsContext {
    let mut gfx_state = ctx.state().borrow_mut();
    let mut vao = 0;

    unsafe {
      gl::GenVertexArrays(1, &mut vao);

      gfx_state.bind_vertex_array(vao);
      gfx_state.bind_vertex_array(0);

      Tess {
        mode: opengl_mode(mode),
        vert_nb: vert_nb,
        vao: vao,
        vbo: None,
        ibo: None,
        _v: PhantomData
      }
    }
  }
}

impl<V> Drop for Tess<V> {
  fn drop(&mut self) {
    unsafe {
      gl::DeleteVertexArrays(1, &self.vao);
    }
  }
}

// Give OpenGL types information on the content of the VBO by setting vertex formats and pointers
// to buffer memory.
fn set_vertex_pointers(formats: &[VertexComponentFormat]) {
  let offsets = aligned_offsets(formats);
  let vertex_weight = offset_based_vertex_weight(formats, &offsets) as GLsizei;

  for (i, (format, off)) in formats.iter().zip(offsets).enumerate() {
    set_component_format(i as u32, vertex_weight, off, format);
  }
}

// Compute offsets for all the vertex components according to the alignments provided.
fn aligned_offsets(formats: &[VertexComponentFormat]) -> Vec<usize> {
  let mut offsets = Vec::with_capacity(formats.len());
  let mut off = 0;

  // compute offsets
  for f in formats {
    off = off_align(off, f.align); // keep the current component format aligned
    offsets.push(off);
    off += component_weight(f); // increment the offset by the pratical size of the component
  }

  offsets
}

// Align an offset.
#[inline]
fn off_align(off: usize, align: usize) -> usize {
  let a = align - 1;
  (off + a) & !a
}

// Weight in bytes of a vertex component.
fn component_weight(f: &VertexComponentFormat) -> usize {
  dim_as_size(&f.dim) as usize * f.unit_size
}

fn dim_as_size(d: &Dim) -> GLint {
  match *d {
    Dim::Dim1 => 1,
    Dim::Dim2 => 2,
    Dim::Dim3 => 3,
    Dim::Dim4 => 4
  }
}

// Weight in bytes of a single vertex, taking into account padding so that the vertex stay correctly
// aligned.
fn offset_based_vertex_weight(formats: &[VertexComponentFormat], offsets: &[usize]) -> usize {
  if formats.is_empty() || offsets.is_empty() {
    return 0;
  }

  off_align(offsets[offsets.len() - 1] + component_weight(&formats[formats.len() - 1]), formats[0].align)
}

// Set the vertex component OpenGL pointers regarding the index of the component (i), the stride
fn set_component_format(i: u32, stride: GLsizei, off: usize, f: &VertexComponentFormat) {
  match f.comp_type {
    Type::Floating => {
      unsafe {
        gl::VertexAttribPointer(i as GLuint, dim_as_size(&f.dim), opengl_sized_type(&f), gl::FALSE, stride, ptr::null::<c_void>().offset(off as isize));
      }
    },
    Type::Integral | Type::Unsigned | Type::Boolean => {
      unsafe {
        gl::VertexAttribIPointer(i as GLuint, dim_as_size(&f.dim), opengl_sized_type(&f), stride, ptr::null::<c_void>().offset(off as isize));
      }
    }
  }

  unsafe {
    gl::EnableVertexAttribArray(i as GLuint);
  }
}

fn opengl_sized_type(f: &VertexComponentFormat) -> GLenum {
  match (f.comp_type, f.unit_size) {
    (Type::Integral, 1) => gl::BYTE,
    (Type::Integral, 2) => gl::SHORT,
    (Type::Integral, 4) => gl::INT,
    (Type::Unsigned, 1) | (Type::Boolean, 1) => gl::UNSIGNED_BYTE,
    (Type::Unsigned, 2) => gl::UNSIGNED_SHORT,
    (Type::Unsigned, 4) => gl::UNSIGNED_INT,
    (Type::Floating, 4) => gl::FLOAT,
    _ => panic!("unsupported vertex component format: {:?}", f)
  }
}

fn opengl_mode(mode: Mode) -> GLenum {
  match mode {
    Mode::Point => gl::POINTS,
    Mode::Line => gl::LINES,
    Mode::LineStrip => gl::LINE_STRIP,
    Mode::Triangle => gl::TRIANGLES,
    Mode::TriangleFan => gl::TRIANGLE_FAN,
    Mode::TriangleStrip => gl::TRIANGLE_STRIP
  }
}

/// Tessellation slice.
///
/// This type enables slicing a tessellation on the fly so that we can render patches of it.
#[derive(Clone)]
pub struct TessSlice<'a, V> where V: 'a {
  /// Tessellation to render.
  tess: &'a Tess<V>,
  /// Start index (vertex) in the tessellation.
  start_index: usize,
  /// Number of vertices to pick from the tessellation. If `None`, all of them are selected.
  vert_nb: usize,
  /// Number of instances to render.
  inst_nb: usize
}

impl<'a, V> TessSlice<'a, V> {
  /// Create a tessellation render that will render the whole input tessellation with only one
  /// instance.
  pub fn one_whole(tess: &'a Tess<V>) -> Self {
    TessSlice {
      tess: tess,
      start_index: 0,
      vert_nb: tess.vert_nb,
      inst_nb: 1
    }
  }

  /// Create a tessellation render for a part of the tessellation starting at the beginning of its
  /// buffer with only one instance.
  ///
  /// The part is selected by giving the number of vertices to render.
  ///
  /// > Note: if you also need to use an arbitrary part of your tessellation (not starting at the
  /// > first vertex in its buffer), have a look at `TessSlice::one_slice`.
  ///
  /// # Panic
  ///
  /// Panic if the number of vertices is higher to the capacity of the tessellation’s vertex buffer.
  pub fn one_sub(tess: &'a Tess<V>, vert_nb: usize) -> Self {
    if vert_nb > tess.vert_nb {
      panic!("cannot render {} vertices for a tessellation which vertex capacity is {}", vert_nb, tess.vert_nb);
    }

    TessSlice {
      tess: tess,
      start_index: 0,
      vert_nb: vert_nb,
      inst_nb: 1
    }
  }

  /// Create a tessellation render for a slice of the tessellation starting anywhere in its buffer
  /// with only one instance.
  ///
  /// The part is selected by giving the start vertex and the number of vertices to render. This
  ///
  /// # Panic
  ///
  /// Panic if the start vertex is higher to the capacity of the tessellation’s vertex buffer.
  ///
  /// Panic if the number of vertices is higher to the capacity of the tessellation’s vertex buffer.
  pub fn one_slice(tess: &'a Tess<V>, start: usize, nb: usize) -> Self {
    if start > tess.vert_nb {
      panic!("cannot render {} vertices starting at vertex {} for a tessellation which vertex capacity is {}", nb, start, tess.vert_nb);
    }

    if nb > tess.vert_nb {
      panic!("cannot render {} vertices for a tessellation which vertex capacity is {}", nb, tess.vert_nb);
    }

    TessSlice {
      tess: tess,
      start_index: start,
      vert_nb: nb,
      inst_nb: 1
    }
  }

  /// Render a tessellation.
  pub fn render<C>(&self, ctx: &mut C) where C: GraphicsContext, V: Vertex {
    self.tess.render(ctx, self.start_index, self.vert_nb, self.inst_nb);
  }
}

impl<'a, V> From<&'a Tess<V>> for TessSlice<'a, V> {
  fn from(tess: &'a Tess<V>) -> Self {
    TessSlice::one_whole(tess)
  }
}

pub trait TessSliceIndex<Idx, V> {
  fn slice<'a>(&'a self, idx: Idx) -> TessSlice<'a, V>;
}

impl<V> TessSliceIndex<RangeFull, V> for Tess<V> {
  fn slice<'a>(&'a self, _: RangeFull) -> TessSlice<'a, V> {
    TessSlice::one_whole(self)
  }
}

impl<V> TessSliceIndex<RangeTo<usize>, V> for Tess<V> {
  fn slice<'a>(&'a self, to: RangeTo<usize>) -> TessSlice<'a, V> {
    TessSlice::one_sub(self, to.end)
  }
}

impl<V> TessSliceIndex<RangeFrom<usize>, V> for Tess<V> {
  fn slice<'a>(&'a self, from: RangeFrom<usize>) -> TessSlice<'a, V> {
    TessSlice::one_slice(self, from.start, self.vert_nb)
  }
}

impl<V> TessSliceIndex<Range<usize>, V> for Tess<V> {
  fn slice<'a>(&'a self, range: Range<usize>) -> TessSlice<'a, V> {
    TessSlice::one_slice(self, range.start, range.end)
  }
}