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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Types and functions for 3D rendering.

use ::{std, cgmath};

use ::{graphics};

const PERSPECTIVE_INITIAL_FOVY : cgmath::Deg <f32> = cgmath::Deg (90.0);
const PERSPECTIVE_NEAR_PLANE   : f32 =    0.1;
const PERSPECTIVE_FAR_PLANE    : f32 = 1000.0;
/// 1.0 units is equal to `ORTHOGRAPHIC_PIXEL_SCALE` pixels at 1.0x zoom
const ORTHOGRAPHIC_PIXEL_SCALE : f32 =   64.0;
const ORTHOGRAPHIC_NEAR_PLANE  : f32 =    0.0;
const ORTHOGRAPHIC_FAR_PLANE   : f32 = 1000.0;

/// Represents a camera ("view") positioned and oriented in a 3D scene with a
/// 3D transformation and a 3D projection.
pub struct Camera3d {
  // transform
  /// Position in 3D world space
  pub position                    : cgmath::Point3  <f32>,
  /// Yaw represents a clockwise rotation restricted to the range $[0,
  /// 2\pi)$.
  pub yaw                         : cgmath::Rad     <f32>,
  /// Pitch represents a rotation up or down restricted to the range $[-\pi/2,
  /// \pi/2]$.
  pub pitch                       : cgmath::Rad     <f32>,
  // TODO: roll
  /// Basis derived from `yaw` and `pitch`.
  pub orientation                 : cgmath::Basis3  <f32>,
  /// Transforms points from world space to camera (view, eye) space as
  /// specified by the camera position and orientation.
  ///
  /// Note that world space is assumed to have 'up' vector Z while in OpenGL
  /// the negative Z axis is 'into' the screen so this matrix performs the
  /// required transform mapping positive Y to negative Z and positive Z to
  /// positive Y.
  pub transform_mat_world_to_view : cgmath::Matrix4 <f32>,

  // projection
  pub projection3d               : Projection3d
}

/// The 3D projection which can be either perspective or orthographic
pub struct Projection3d {
  pub viewport_width  : u16,
  pub viewport_height : u16,
  pub inner           : Projection3dInner
}

/// Either a `Perspective` or `Orthographic` projection
pub enum Projection3dInner {
  Perspective {
    /// Used to create the perspective projection matrix
    perspective_fov : cgmath::PerspectiveFov <f32>,
    /// Constructed from the parameters in `perspective_fov` to transform
    /// points in view space to 4D homogenous clip coordinates based on a
    /// perspective projection
    mat             : cgmath::Matrix4        <f32>
  },
  Orthographic {
    /// Constant factor to zoom in and out orthographically.
    ///
    /// The scale at `zoom == 1.0` is defined by the constant
    /// `ORTHOGRAPHIC_PIXEL_SCALE`.
    zoom            : f32,
    /// Used to create the orthographic projection matrix
    ortho           : cgmath::Ortho   <f32>,
    /// Constructed from the parameters in `ortho` to transform points in view
    /// space to 4D homogenous clip coordinates based on an orthographic
    /// projection
    mat             : cgmath::Matrix4 <f32>
  }
}

/// Computes floating point 'width/height' ratio from unsigned resolution
/// input
#[inline]
pub fn aspect_ratio (viewport_width : u16, viewport_height : u16) -> f32 {
  viewport_width as f32 / viewport_height as f32
}

/// Builds a 4x4 transformation matrix that will transform points in world
/// space coordinates to view space coordinates for a given view position and
/// orientation.
///
/// Note this accepts input such that the identity orientation defines the view
/// looking down the *positive Y axis* with the 'up' vector defined by the
/// *positive Z axis* and the constructed matrix will send points in front of
/// the view to the *negative Z axis* and points above the view to the
/// *positive Y axis*:
///
/// ```
/// # extern crate gl_utils;
/// # #[macro_use] extern crate cgmath;
/// # fn main () {
/// # use std::f32::consts::FRAC_PI_2;
/// # use gl_utils::camera3d::transform_mat_world_to_view;
/// use cgmath::{ApproxEq, EuclideanSpace, One, Rotation3, Transform};
/// let position      = cgmath::Point3::origin();
/// let orientation   = cgmath::Basis3::one();
/// let transform_mat = transform_mat_world_to_view (&position, &orientation);
/// assert_eq!(
///  transform_mat,
///  cgmath::Matrix4::new (
///    1.0, 0.0, 0.0, 0.0,
///    0.0, 0.0, -1.0, 0.0,
///    0.0, 1.0, 0.0, 0.0,
///    0.0, 0.0, 0.0, 1.0)
/// );
/// let point = cgmath::Point3::new (0.0, 10.0, 0.0);
/// assert_eq!(
///   transform_mat.transform_point (point),
///   cgmath::Point3::new (0.0, 0.0, -10.0)
/// );
/// let orientation   = cgmath::Basis3::from_angle_z (cgmath::Rad (FRAC_PI_2));
/// let transform_mat = transform_mat_world_to_view (&position, &orientation);
/// let point = cgmath::Point3::new (-10.0, 0.0, 0.0);
/// assert_relative_eq!(
///   transform_mat.transform_point (point),
///   cgmath::Point3::new (0.0, 0.0, -10.0),
///   epsilon = 10.0 * f32::default_epsilon()
/// );
/// # }
/// ```

pub fn transform_mat_world_to_view (
  view_position    : &cgmath::Point3 <f32>,
  view_orientation : &cgmath::Basis3 <f32>
) -> cgmath::Matrix4 <f32> {
  let eye    = view_position;
  let center = view_position + view_orientation.as_ref().y;
  let up     = view_orientation.as_ref().z;
  cgmath::Matrix4::<f32>::look_at (*eye, center, up)
}

// private
fn compute_ortho (viewport_width : u16, viewport_height : u16, zoom : f32)
  -> cgmath::Ortho <f32>
{
  let half_scaled_width  = (0.5 * (viewport_width as f32  / zoom))
    / ORTHOGRAPHIC_PIXEL_SCALE;
  let half_scaled_height = (0.5 * (viewport_height as f32 / zoom))
    / ORTHOGRAPHIC_PIXEL_SCALE;
  cgmath::Ortho {
    left:   -half_scaled_width,
    right:   half_scaled_width,
    bottom: -half_scaled_height,
    top:     half_scaled_height,
    near:    ORTHOGRAPHIC_NEAR_PLANE,
    far:     ORTHOGRAPHIC_FAR_PLANE
  }
}

impl Camera3d {
  /// Create a new camera centered at the origin looking down the positive Y
  /// axis with 'up' vector aligned with the Z axis.
  #[inline]
  pub fn new (viewport_width : u16, viewport_height : u16) -> Self {
    Self::with_pose (
      viewport_width, viewport_height, Default::default())
  }

  /// Create a new 3D camera with the given viewport, position, and
  /// orientation.
  pub fn with_pose (
    viewport_width  : u16,
    viewport_height : u16,
    pose            : graphics::Pose3d <f32>
  ) -> Self {
    // transform: world space -> view space
    let orientation = graphics::orientation_from_yaw_pitch (
      pose.yaw, pose.pitch);
    let transform_mat_world_to_view
      = transform_mat_world_to_view (&pose.position, &orientation);

    // projection: view space -> clip space
    let projection3d = Projection3d::perspective (
      viewport_width, viewport_height, PERSPECTIVE_INITIAL_FOVY.into());

    Camera3d {
      position: pose.position,
      yaw:      pose.yaw,
      pitch:    pose.pitch,
      orientation,
      transform_mat_world_to_view,
      projection3d
    }
  }

  /// Should be called when the screen resolution changes.
  #[inline]
  pub fn set_viewport_dimensions (&mut self,
    viewport_width : u16, viewport_height : u16
  ) {
    self.projection3d.set_viewport_dimensions (
      viewport_width, viewport_height);
  }

  pub fn set_position (&mut self, position : &cgmath::Point3 <f32>) {
    if self.position != *position {
      self.position = *position;
      self.compute_transform();
    }
  }

  pub fn rotate (&mut self,
    dyaw   : cgmath::Rad <f32>, dpitch : cgmath::Rad <f32>
  ) {
    use std::f32::consts::{PI, FRAC_PI_2};
    use cgmath::Zero;
    if !dyaw.is_zero() {
      self.yaw += dyaw;
      if self.yaw < cgmath::Rad (0.0) {
        self.yaw += cgmath::Rad (2.0*PI);
      }
      if cgmath::Rad (2.0*PI) <= self.yaw {
        self.yaw -= cgmath::Rad (2.0*PI);
      }
    }
    if !dpitch.is_zero() {
      self.pitch += dpitch;
      if self.pitch < cgmath::Rad (-FRAC_PI_2) {
        self.pitch = cgmath::Rad (-FRAC_PI_2)
      }
      if cgmath::Rad (FRAC_PI_2) < self.pitch {
        self.pitch = cgmath::Rad (FRAC_PI_2)
      }
    }
    if !dyaw.is_zero() || !dpitch.is_zero() {
      self.compute_orientation();
    }
  }

  /// Moves the view position relative to the X/Y plane with X and Y direction
  /// determined by heading and Z always aligned with the Z axis, i.e. the
  /// translated position is only determined by the current *yaw* not the
  /// pitch.
  pub fn move_local_xy (&mut self,
    dx : f32, dy : f32, dz : f32
  ) {
    if dx != 0.0 || dy != 0.0 || dz != 0.0 {
      let xy_basis  = cgmath::Matrix3::from_angle_z (self.yaw);
      self.position +=
        (dx * xy_basis.x) + (dy * xy_basis.y) + (dz * xy_basis.z);
      self.compute_transform();
    }
  }

  /// Returns the raw *world to view transform* and *view to clip projection*
  /// matrix data, suitable for use as shader uniforms.
  #[inline]
  pub fn view_mats (&self) -> (&[[f32; 4]; 4], &[[f32; 4]; 4]) {
    (
      self.transform_mat_world_to_view.as_ref(),
      self.projection3d.as_matrix().as_ref()
    )
  }

  #[inline]
  fn compute_transform (&mut self) {
    self.transform_mat_world_to_view
      = transform_mat_world_to_view (&self.position, &self.orientation);
  }

  /// Convenience method to compute orientation from current yaw and pitch
  /// followed by updating the transform matrix
  fn compute_orientation (&mut self) {
    self.orientation
      = graphics::orientation_from_yaw_pitch (self.yaw, self.pitch);
    self.compute_transform();
  }
}

impl Projection3d {

  /// Create a new 3D perspective projection
  ///
  /// # Panics
  ///
  /// Viewport width or height is zero:
  ///
  /// ```should_panic
  /// # extern crate gl_utils;
  /// # extern crate cgmath;
  /// # fn main () {
  /// # use gl_utils::camera3d::Projection3d;
  /// # use cgmath::{EuclideanSpace, One, Transform};
  /// // panics:
  /// let perspective = Projection3d::perspective (0, 240, cgmath::Deg (90.0).into());
  /// # }
  /// ```
  ///
  /// If `fovy` is greater than or equal to $\pi$ radians:
  ///
  /// ```should_panic
  /// # extern crate gl_utils;
  /// # extern crate cgmath;
  /// # fn main () {
  /// # use gl_utils::camera3d::Projection3d;
  /// # use cgmath::{EuclideanSpace, One, Transform};
  /// // panics:
  /// let perspective = Projection3d::perspective (320, 240, cgmath::Rad (4.0));
  /// # }
  /// ```
  ///
  /// If `fovy` is less than or equal to $0.0$ radians:
  ///
  /// ```should_panic
  /// # extern crate gl_utils;
  /// # extern crate cgmath;
  /// # fn main () {
  /// # use gl_utils::camera3d::Projection3d;
  /// # use cgmath::{EuclideanSpace, One, Transform};
  /// // panics:
  /// let perspective = Projection3d::perspective (320, 240, cgmath::Rad (0.0));
  /// # }
  /// ```

  pub fn perspective (
    viewport_width : u16, viewport_height : u16, fovy : cgmath::Rad <f32>
  ) -> Self {
    let inner
      = Projection3dInner::perspective (viewport_width, viewport_height, fovy);
    Projection3d { viewport_width, viewport_height, inner }
  }

  /// Create a new 3D orthographic projection
  ///
  /// # Panics
  ///
  /// Viewport width or height is zero:
  ///
  /// ```should_panic
  /// # extern crate gl_utils;
  /// # extern crate cgmath;
  /// # fn main () {
  /// # use gl_utils::camera3d::Projection3d;
  /// # use cgmath::{EuclideanSpace, One, Transform};
  /// // panics:
  /// let perspective = Projection3d::perspective (0, 240, cgmath::Deg (90.0).into());
  /// # }
  /// ```
  ///
  /// If `zoom` is less than or equal to $0.0$:
  ///
  /// ```should_panic
  /// # extern crate gl_utils;
  /// # extern crate cgmath;
  /// # fn main () {
  /// # use gl_utils::camera3d::Projection3d;
  /// # use cgmath::{EuclideanSpace, One, Transform};
  /// let ortho = Projection3d::orthographic (320, 240, 0.0);  // panics
  /// # }
  /// ```

  pub fn orthographic (viewport_width : u16, viewport_height : u16, zoom : f32)
    -> Self
  {
    let inner
      = Projection3dInner::orthographic (viewport_width, viewport_height, zoom);
    Projection3d { viewport_width, viewport_height, inner }
  }

  /// Returns a reference to the underlying projection matrix
  #[inline]
  pub fn as_matrix (&self) -> &cgmath::Matrix4 <f32> {
    self.inner.as_matrix()
  }

  pub fn is_orthographic (&self) -> bool {
    match self.inner {
      Projection3dInner::Orthographic {..} => true,
      Projection3dInner::Perspective  {..} => false
    }
  }

  pub fn is_perspective (&self) -> bool {
    match self.inner {
      Projection3dInner::Orthographic {..} => false,
      Projection3dInner::Perspective  {..} => true
    }
  }

  /// Converts the inner projection type to an `Orthographic` projection with
  /// the given zoom; if already an orthographic projection this will modify
  /// the zoom
  pub fn to_orthographic (&mut self, zoom : f32) {
    match self.inner {
      ref mut inner@Projection3dInner::Orthographic { .. } => {
        inner.set_orthographic_zoom (
          self.viewport_width, self.viewport_height, zoom);
      }
      ref mut inner@Projection3dInner::Perspective  { .. } => {
        *inner = Projection3dInner::orthographic (
          self.viewport_width, self.viewport_height, 1.0);
      }
    }
  }

  /// Converts the inner projection type to a `Perspective` projection with the
  /// given vertical FOV; if already a perspective projection this will modify
  /// the FOV
  pub fn to_perspective (&mut self, fovy : cgmath::Rad <f32>) {
    match self.inner {
      ref mut inner@Projection3dInner::Orthographic { .. } => {
        *inner = Projection3dInner::perspective (
          self.viewport_width, self.viewport_height, fovy);
      }
      ref mut inner@Projection3dInner::Perspective  { .. } => {
        inner.set_perspective_fovy (fovy);
      }
    }
  }

  /// Sets the current viewport dimensions
  ///
  /// # Panics
  ///
  /// Viewport width or height is zero:
  ///
  /// ```should_panic
  /// # extern crate gl_utils;
  /// # extern crate cgmath;
  /// # fn main () {
  /// # use gl_utils::camera3d::Projection3d;
  /// # use cgmath::{EuclideanSpace, One, Transform};
  /// let mut projection = Projection3d::perspective (320, 240, cgmath::Deg (90.0).into());
  /// projection.set_viewport_dimensions (0, 240);  // panics
  /// # }
  /// ```

  pub fn set_viewport_dimensions (&mut self,
    viewport_width : u16, viewport_height : u16
  ) {
    self.viewport_width  = viewport_width;
    self.viewport_height = viewport_height;
    self.inner.update_viewport_dimensions (viewport_width, viewport_height);
  }

  /// Multiply the current perspective vertical FOV or orthographic zoom by the
  /// given scale factor.
  ///
  /// Will not increase vertical FOV greater than $\pi$ radians, nor will it
  /// decrease the zoom or vertical FOV to zero.
  ///
  /// # Panics
  ///
  /// Panics if scale factor is zero or negative:
  ///
  /// ```should_panic
  /// # extern crate gl_utils;
  /// # extern crate cgmath;
  /// # fn main () {
  /// # use gl_utils::Camera3d;
  /// # use cgmath::{EuclideanSpace, One, Transform};
  /// let mut camera3d = Camera3d::new (320, 240);
  /// camera3d.projection3d.scale_fovy_or_zoom (-1.0);   // panics
  /// # }
  /// ```
  pub fn scale_fovy_or_zoom (&mut self, scale : f32) {
    assert!(0.0 < scale);
    if scale != 1.0 {
      use cgmath::ApproxEq;
      match self.inner {
        Projection3dInner::Perspective {
          ref mut perspective_fov, ref mut mat
        } => {
          let max_fovy = cgmath::Rad (
            std::f32::consts::PI - cgmath::Rad::<f32>::default_epsilon()
          );
          let min_fovy = cgmath::Rad::<f32>::default_epsilon();
          perspective_fov.fovy *= scale;
          debug_assert!(cgmath::Rad (0.0) <= perspective_fov.fovy);
          if max_fovy < perspective_fov.fovy {
            perspective_fov.fovy = max_fovy;
          } else if perspective_fov.fovy < cgmath::Rad (min_fovy) {
            perspective_fov.fovy = cgmath::Rad (min_fovy);
          }
          *mat = graphics::projection_mat_perspective (perspective_fov);
        }
        Projection3dInner::Orthographic {
          ref mut zoom, ref mut ortho, ref mut mat
        } => {
          *zoom *= scale;
          debug_assert!(0.0 <= *zoom);
          if *zoom < f32::default_epsilon() {
            *zoom = f32::default_epsilon();
          }
          *ortho = compute_ortho (
            self.viewport_width, self.viewport_height, *zoom);
          *mat   = graphics::projection_mat_orthographic (ortho);
        }
      }
    }
  }

}

impl Projection3dInner {
  fn perspective (
    viewport_width : u16, viewport_height : u16, fovy : cgmath::Rad <f32>
  ) -> Self {
    use cgmath::ApproxEq;
    assert!(0   < viewport_width);
    assert!(0   < viewport_height);
    assert!(0.0 < fovy.0);
    assert!(fovy.0 <=
      std::f32::consts::PI - cgmath::Rad::<f32>::default_epsilon());
    let perspective_fov = cgmath::PerspectiveFov {
        fovy,
        aspect: aspect_ratio (viewport_width, viewport_height),
        near:   PERSPECTIVE_NEAR_PLANE,
        far:    PERSPECTIVE_FAR_PLANE
    };
    let mat = graphics::projection_mat_perspective (&perspective_fov);
    Projection3dInner::Perspective { perspective_fov, mat }
  }

  fn orthographic (viewport_width : u16, viewport_height : u16, zoom : f32)
    -> Self
  {
    assert!(0   < viewport_width);
    assert!(0   < viewport_height);
    assert!(0.0 < zoom);
    let ortho = compute_ortho (viewport_width, viewport_height, zoom);
    let mat   = graphics::projection_mat_orthographic (&ortho);
    Projection3dInner::Orthographic { zoom, ortho, mat }
  }

  /// Returns a reference to the underlying matrix
  fn as_matrix (&self) -> &cgmath::Matrix4 <f32> {
    match *self {
      Projection3dInner::Perspective  { ref mat, .. } => mat,
      Projection3dInner::Orthographic { ref mat, .. } => mat
    }
  }

  fn update_viewport_dimensions (&mut self,
    viewport_width : u16, viewport_height : u16
  ) {
    assert!(0 < viewport_width);
    assert!(0 < viewport_height);
    match *self {
      Projection3dInner::Perspective  { ref mut perspective_fov, ref mut mat } => {
        perspective_fov.aspect = aspect_ratio (viewport_width, viewport_height);
        *mat = graphics::projection_mat_perspective (perspective_fov);
      }
      Projection3dInner::Orthographic { ref zoom, ref mut ortho, ref mut mat } => {
        *ortho = compute_ortho (viewport_width, viewport_height, *zoom);
        *mat   = graphics::projection_mat_orthographic (ortho);
      }
    }
  }

  fn set_perspective_fovy (&mut self, new_fovy : cgmath::Rad <f32>) {
    use cgmath::ApproxEq;
    let max_fovy = cgmath::Rad (
      std::f32::consts::PI - cgmath::Rad::<f32>::default_epsilon()
    );
    assert!(cgmath::Rad::<f32>::default_epsilon() < new_fovy.0);
    assert!(new_fovy <= max_fovy);
    match *self {
      Projection3dInner::Perspective {
        ref mut perspective_fov, ref mut mat
      } => {
        if perspective_fov.fovy != new_fovy {
          perspective_fov.fovy = new_fovy;
          *mat = graphics::projection_mat_perspective (perspective_fov);
        }
      }
      _ => unreachable!("expected perspective projection")
    }
  }

  fn set_orthographic_zoom (&mut self,
    viewport_width : u16, viewport_height : u16, new_zoom : f32
  ) {
    use cgmath::ApproxEq;
    assert!(f32::default_epsilon() < new_zoom);
    match *self {
      Projection3dInner::Orthographic {
        ref mut zoom, ref mut ortho, ref mut mat
      } => {
        if *zoom != new_zoom {
          *zoom  = new_zoom;
          *ortho = compute_ortho (viewport_width, viewport_height, *zoom);
          *mat   = graphics::projection_mat_orthographic (ortho);
        }
      }
      _ => unreachable!("expected orthographic projection")
    }
  }

}