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
//! Dynamic rendering pipelines.
//!
//! This module gives you types and functions to build *dynamic* rendering **pipelines**. A
//! pipeline represents a functional stream that consumes geometric data and rasterizes them.
//!
//! When you want to build a render, the main entry point is the `entry` function. It gives you a
//! `Gpu` object that enables you to perform stateful graphics operations.
//!
//! # Key concepts
//!
//! luminance exposes several concepts you have to be familiar with:
//!
//! - render buffers;
//! - blending;
//! - shaders;
//! - tessellations;
//! - gates;
//! - render commands;
//! - shading commands;
//! - pipelines;
//!
//! # Render buffers
//!
//! The render buffers are GPU-allocated memory regions used while rendering images into
//! framebuffers. Typically, a framebuffer has at least three buffers:
//!
//! - a *color buffer*, that will receive texels (akin to pixels, but for textures/buffers);
//! - a *depth buffer*, a special buffer mostly used to determine whether a fragment (pixel) is
//!   behind something that was previously rendered – it’s a simple solution to discard render that
//!   won’t be visible anyway;
//! - a *stencil buffer*, which often acts as a mask to create interesting effects to your renders.
//!
//! luminance gives you access to the first two – the stencil buffer will be added in a future
//! release.
//!
//! Alternatively, you can also tell your GPU that you won’t be using a depth buffer, or that you
//! need several color buffers – this is called [MRT](https://en.wikipedia.org/wiki/Multiple_Render_Targets).
//! In most frameworks, you create some textures to hold the color information, then you “bind” them
//! to your pipeline, and you’re good to go. In luminance, everything happens at the type level: you
//! say to luminance which type of framebuffer you want (for instance, a framebuffer with two color
//! outputs and a depth buffer). luminance will handle the textures for you – you can retrieve access
//! to them whenever you want to.
//!
//! If you have a depth buffer, you can ask luminance to perform a depth test that will discard any
//! fragment being “behind” the fragment already in place. You can also give luminance the *clear
//! color* it must use when you issue a new pipeline to fill the buffers.
//!
//! # Blending
//!
//! When you render a fragment A at a position P in a framebuffer, there are several configurations:
//!
//! - you have a depth buffer and the depth test is enabled: in that case, no blending will happen
//!   as either the already in-place fragment will be chosen or the new one you try to write,
//!   depending on the result of the depth test;
//! - the depth test is disabled: in that case, each time a fragment is to be written to a place in
//!   a buffer, its output will be blended with the color already present according to a *blending
//!   equation* and two *blending factors*.
//!
//! # Shaders
//!
//! Shaders in luminance are pretty simple: you have `Stage` that represents each type of shader
//! stages you can use, and `Program`, that links them into a GPU executable.
//!
//! In luminance, you’re supposed to create a `Program` with `Stage`. Some of them are mandatory and
//! others are optional. In order to customize your build, you can use a *uniform interface*. The
//! uniform interface is defined by our own type. When you create a program, you pass code to tell
//! luminance how to get such a type. Then that type will be handed back to you when needed in the
//! form of an immutable object.
//!
//! # Tessellations
//!
//! The `Tess` type represents a tessellation associated with a possible set of GPU vertices and
//! indices. Note that it’s also possible to create *attributeless* tesselations – i.e.
//! tessellations that don’t own any vertices nor indices and are used with specific shaders only.
//!
//! # Gates
//!
//! The gate concept is quite easy to understand: picture a pipeline as tree. Each node is typed,
//! hence, the structure is quite limited to what your GPU can understand. Gates are a way to
//! spread information of root nodes down. For instance, if you have a shader node, every nested
//! child of that shader node will have the possibility to use its features via a shading gate.
//!
//! # Render commands
//!
//! A set of values that tag a collection of tessellations. Typical information is whether we should
//! use a depth test, the blending factors and equation, etc.
//!
//! # Shading commands
//!
//! A set of values that tag a collection of render commands. Typical information is a shader
//! program along with its uniform interface.
//!
//! # Pipelines
//!
//! A pipeline is just an aggregation of shadings commands with a few extra information.

use gl;
use gl::types::*;

use std::cell::RefCell;
use std::marker::PhantomData;
use std::ops::Deref;
use std::rc::Rc;

use buffer::RawBuffer;
use blending::{Equation, Factor};
use framebuffer::{ColorSlot, DepthSlot, Framebuffer};
use shader::program::{Dim, Program, Type, Uniform, Uniformable, UniformInterface};
use tess::TessRender;
use texture::{Dimensionable, Layerable, RawTexture};
use vertex::{CompatibleVertex, Vertex};

struct GpuState {
  next_texture_unit: u32,
  free_texture_units: Vec<u32>,
  next_buffer_binding: u32,
  free_buffer_bindings: Vec<u32>
}

impl GpuState {
  fn new() -> Self {
    GpuState {
      next_texture_unit: 0,
      free_texture_units: Vec::new(),
      next_buffer_binding: 0,
      free_buffer_bindings: Vec::new()
    }
  }
}

/// An opaque type representing the GPU. You can perform stateful operations on it.
pub struct Gpu {
  gpu_state: Rc<RefCell<GpuState>>
}

impl Gpu {
  fn new() -> Self {
    Gpu {
      gpu_state: Rc::new(RefCell::new(GpuState::new()))
    }
  }

  /// Bind a texture and return the bound texture.
  pub fn bind_texture<'a, T>(&self, texture: &'a T) -> BoundTexture<'a, T> where T: Deref<Target = RawTexture> {
    let mut state = self.gpu_state.borrow_mut();

    let unit = state.free_texture_units.pop().unwrap_or_else(|| {
      // no more free units; reserve one
      let unit = state.next_texture_unit;
      state.next_texture_unit += 1;
      unit
    });

    unsafe { bind_texture_at(texture.deref(), unit) };
    BoundTexture::new(self.gpu_state.clone(), unit)
  }

  /// Bind a buffer and return the bound buffer.
  pub fn bind_buffer<'a, T>(&self, buffer: &T) -> BoundBuffer<'a, T> where T: Deref<Target = RawBuffer> {
    let mut state = self.gpu_state.borrow_mut();

    let binding = state.free_buffer_bindings.pop().unwrap_or_else(|| {
      // no more free bindings; reserve one
      let binding = state.next_buffer_binding;
      state.next_buffer_binding += 1;
      binding
    });

    unsafe { bind_buffer_at(buffer.deref(), binding) };
    BoundBuffer::new(self.gpu_state.clone(), binding)
  }
}

/// An opaque type representing a bound texture in a `Gpu`. You may want to pass such an object to
/// a shader’s uniform’s update.
pub struct BoundTexture<'a, T> where T: 'a {
  unit: u32,
  gpu_state: Rc<RefCell<GpuState>>,
  _t: PhantomData<&'a T>
}

impl<'a, T> BoundTexture<'a, T> {
  fn new(gpu_state: Rc<RefCell<GpuState>>, unit: u32) -> Self {
    BoundTexture {
      unit,
      gpu_state,
      _t: PhantomData
    }
  }
}

impl<'a, T> Drop for BoundTexture<'a, T> {
  fn drop(&mut self) {
    let mut state = self.gpu_state.borrow_mut();
    // place the unit into the free list
    state.free_texture_units.push(self.unit);
  }
}

impl<'a, T> Uniformable for BoundTexture<'a, T> {
  fn update(self, u: &Uniform<Self>) {
    unsafe { gl::Uniform1i(u.index(), self.unit as GLint) }
  }

  fn ty() -> Type { Type::TextureUnit }

  fn dim() -> Dim { Dim::Dim1 }
}

/// An opaque type representing a bound buffer in a `Gpu`. You may want to pass such an object to
/// a shader’s uniform’s update.
pub struct BoundBuffer<'a, T> where T: 'a {
  binding: u32,
  gpu_state: Rc<RefCell<GpuState>>,
  _t: PhantomData<&'a T>
}

impl<'a, T> BoundBuffer<'a, T> {
  fn new(gpu_state: Rc<RefCell<GpuState>>, binding: u32) -> Self {
    BoundBuffer {
      binding,
      gpu_state,
      _t: PhantomData
    }
  }
}

impl<'a, T> Drop for BoundBuffer<'a, T> {
  fn drop(&mut self) {
    let mut state = self.gpu_state.borrow_mut();
    // place the binding into the free list
    state.free_buffer_bindings.push(self.binding);
  }
}

impl<'a, T> Uniformable for BoundBuffer<'a, T> {
  fn update(self, u: &Uniform<Self>) {
    unsafe { gl::UniformBlockBinding(u.program(), u.index() as GLuint, self.binding as GLuint) }
  }

  fn ty() -> Type { Type::TextureUnit }

  fn dim() -> Dim { Dim::Dim1 }
}

/// This is the entry point of a render.
///
/// You’re handed a `Gpu` object that allows you to perform stateful operations on the GPU. For
/// instance, you can bind textures and buffers to use them in shaders.
pub fn entry<F>(f: F) where F: FnOnce(Gpu) {
  let gpu = Gpu::new();
  f(gpu);
}

/// A dynamic rendering pipeline. A *pipeline* is responsible of rendering into a `Framebuffer`.
///
/// `L` refers to the `Layering` of the underlying `Framebuffer`.
///
/// `D` refers to the `Dim` of the underlying `Framebuffer`.
///
/// `CS` and `DS` are – respectively – the *color* and *depth* `Slot`(s) of the underlying
/// `Framebuffer`.
///
/// Pipelines also have several transient objects:
///
/// - a *clear color*, used to clear the framebuffer
/// - a *texture set*, used to make textures available in subsequent structures
/// - a *buffer set*, used to make uniform buffers available in subsequent structures
pub fn pipeline<L, D, CS, DS, F>(framebuffer: &Framebuffer<L, D, CS, DS>, clear_color: [f32; 4], f: F)
    where L: Layerable,
          D: Dimensionable,
          D::Size: Copy,
          CS: ColorSlot<L, D>,
          DS: DepthSlot<L, D>,
          F: FnOnce(&ShadingGate) {
  unsafe {
    gl::BindFramebuffer(gl::FRAMEBUFFER, framebuffer.handle());
    gl::Viewport(0, 0, framebuffer.width() as GLint, framebuffer.height() as GLint);
    gl::ClearColor(clear_color[0], clear_color[1], clear_color[2], clear_color[3]);
    gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
  }

  f(&ShadingGate);
}

/// An object created only via `pipeline` and that gives you shading features.
pub struct ShadingGate;

impl ShadingGate {
  pub fn shade<In, Out, Uni, F>(&self, program: &Program<In, Out, Uni>, f: F)
      where In: Vertex, Uni: UniformInterface, F: FnOnce(&RenderGate<In>, &Uni) {
    unsafe { gl::UseProgram(program.handle()) };

    let render_gate = RenderGate {
      _v: PhantomData,
    };

    let uni_iface = program.uniform_interface();
    f(&render_gate, uni_iface);
  }
}

pub struct RenderGate<V> {
  _v: PhantomData<*const V>
}

impl<V> RenderGate<V> {
  pub fn render<B, F>(&self, blending: B, depth_test: bool, f: F)
      where B: Into<Option<(Equation, Factor, Factor)>>, F: FnOnce(&TessGate<V>) {
    unsafe {
      set_blending(blending);
      set_depth_test(depth_test);
    }

    let tess_gate = TessGate {
      _v: PhantomData,
    };

    f(&tess_gate);
  }
}

pub struct TessGate<V> {
  _v: PhantomData<*const V>
}

impl<V> TessGate<V> where V: Vertex {
  pub fn render<W>(&self, tess: TessRender<W>) where W: CompatibleVertex<V> {
    tess.render();
  }
}

#[inline]
unsafe fn bind_buffer_at(buf: &RawBuffer, binding: u32) {
  gl::BindBufferBase(gl::UNIFORM_BUFFER, binding as GLuint, buf.handle());
}

#[inline]
unsafe fn bind_texture_at(tex: &RawTexture, unit: u32) {
  gl::ActiveTexture(gl::TEXTURE0 + unit as GLenum);
  gl::BindTexture(tex.target(), tex.handle());
}

#[inline]
unsafe fn set_blending<B>(blending: B) where B: Into<Option<(Equation, Factor, Factor)>> {
  match blending.into() {
    Some((equation, src_factor, dest_factor)) => {
      gl::Enable(gl::BLEND);
      gl::BlendEquation(blending_equation(equation));
      gl::BlendFunc(blending_factor(src_factor), blending_factor(dest_factor));
    },
    None => {
      gl::Disable(gl::BLEND);
    }
  }
}

#[inline]
unsafe fn set_depth_test(test: bool) {
  if test {
    gl::Enable(gl::DEPTH_TEST);
  } else {
    gl::Disable(gl::DEPTH_TEST);
  }
}

#[inline]
fn blending_equation(equation: Equation) -> GLenum {
  match equation {
    Equation::Additive => gl::FUNC_ADD,
    Equation::Subtract => gl::FUNC_SUBTRACT,
    Equation::ReverseSubtract => gl::FUNC_REVERSE_SUBTRACT,
    Equation::Min => gl::MIN,
    Equation::Max => gl::MAX
  }
}

#[inline]
fn blending_factor(factor: Factor) -> GLenum {
  match factor {
    Factor::One => gl::ONE,
    Factor::Zero => gl::ZERO,
    Factor::SrcColor => gl::SRC_COLOR,
    Factor::SrcColorComplement => gl::ONE_MINUS_SRC_COLOR,
    Factor::DestColor => gl::DST_COLOR,
    Factor::DestColorComplement => gl::ONE_MINUS_DST_COLOR,
    Factor::SrcAlpha => gl::SRC_ALPHA,
    Factor::SrcAlphaComplement => gl::ONE_MINUS_SRC_ALPHA,
    Factor::DstAlpha => gl::DST_ALPHA,
    Factor::DstAlphaComplement => gl::ONE_MINUS_DST_ALPHA,
    Factor::SrcAlphaSaturate => gl::SRC_ALPHA_SATURATE
  }
}