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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
//! A simple API for drawing 2D and 3D graphics. See the [**Draw** type](./struct.Draw.html) for
//! more details.

use geom::graph::{edge, node};
use geom::{self, Vector3};
use math::BaseFloat;
use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::mem;
use std::ops;

pub use self::background::Background;
pub use self::drawing::Drawing;
pub use self::mesh::Mesh;
use self::properties::spatial::orientation::{self, Orientation};
use self::properties::spatial::position::{self, Position};
use self::properties::{IntoDrawn, Primitive};
pub use self::theme::Theme;

pub mod backend;
pub mod background;
mod drawing;
pub mod mesh;
pub mod properties;
pub mod theme;

/// A simple API for drawing 2D and 3D graphics.
///
/// **Draw** provides a simple way to compose together geometric primitives and text (TODO) with
/// custom colours and textures and draw them to the screen.
///
/// You can also ask **Draw** for the sequence of vertices or triangles (with or without
/// colours/textures) that make up the entire scene that you have created.
///
/// Internally **Draw** uses a **geom::Graph** for placing geometry and text in 3D space.
///
/// **Draw** has 2 groups of methods:
///
/// 1. **Creation**: These methods compose new geometry and text with colours and textures.
///
/// 2. **Rendering**: These methods provide ways of rendering the graphics either directly to the
///    frame for the current display or to a list of vertices or triangles for lower-level, more
///    flexible access.
///
/// See the
/// [simple_draw.rs](https://github.com/nannou-org/nannou/blob/master/examples/simple_draw.rs)
/// example for a demonstration of how to use the **App**'s custom **Draw** type.
#[derive(Clone, Debug)]
pub struct Draw<S = geom::scalar::Default>
where
    S: BaseFloat,
{
    // The state of the **Draw** behind a RefCell. We do this in order to avoid requiring a `mut`
    // handle to a `draw`. The primary purpose of a **Draw** is to be an easy-as-possible,
    // high-level API for drawing stuff. In order to be friendlier to new users, we want to avoid
    // them having to think about mutability and focus on creativity. Rust-lang nuances can come
    // later.
    state: RefCell<State<S>>,
}

/// The inner state of the **Draw** type.
///
/// The **Draw** type stores its **State** behind a **RefCell** - a type used for moving mutability
/// checks from compile time to runtime. We do this in order to avoid requiring a `mut` handle to a
/// `draw`. The primary purpose of a **Draw** is to be an easy-as-possible, high-level API for
/// drawing stuff. In order to be friendlier to new users, we want to avoid requiring them to think
/// about mutability and instead focus on creativity. Rust-lang nuances can come later.
#[derive(Clone, Debug)]
pub struct State<S = geom::scalar::Default>
where
    S: BaseFloat,
{
    /// Relative positioning, orientation and scaling of geometry.
    geom_graph: geom::Graph<S>,
    /// For performing a depth-first search over the geometry graph.
    geom_graph_dfs: RefCell<geom::graph::node::Dfs<S>>,
    /// Buffers of vertex data that may be re-used for polylines, polygons, etc between view calls.
    intermediary_mesh: RefCell<IntermediaryMesh<S>>,
    /// The mesh containing vertices for all drawn shapes, etc.
    mesh: Mesh<S>,
    /// The map from node indices to their vertex and index ranges within the mesh.
    ranges: HashMap<node::Index, Ranges>,
    /// Primitives that are in the process of being drawn.
    drawing: HashMap<node::Index, properties::Primitive<S>>,
    /// The last node that was **Drawn**.
    last_node_drawn: Option<node::Index>,
    /// The theme containing default values.
    theme: Theme,
    /// If `Some`, the **Draw** should first clear the frame's gl context with the given color.
    background_color: Option<properties::Rgba>,
}

/// A set of intermediary buffers for collecting geometry point data for geometry types that may
/// produce a dynamic number of vertices that may or not also contain colour or texture data.
#[derive(Clone, Debug)]
pub struct IntermediaryVertexData<S> {
    pub(crate) points: Vec<mesh::vertex::Point<S>>,
    pub(crate) colors: Vec<mesh::vertex::Color>,
    pub(crate) tex_coords: Vec<mesh::vertex::TexCoords<S>>,
}

/// An intermediary mesh to which drawings-in-progress may store vertex data and indices until they
/// are submitted to the **Draw**'s inner mesh.
#[derive(Clone, Debug)]
pub struct IntermediaryMesh<S> {
    pub(crate) vertex_data: IntermediaryVertexData<S>,
    pub(crate) indices: Vec<usize>,
}

/// A set of ranges into the **IntermediaryVertexData**.
///
/// This allows polygons, polylines, etc to track which slices of data are associated with their
/// own instance.
#[derive(Clone, Debug)]
pub struct IntermediaryVertexDataRanges {
    pub points: ops::Range<usize>,
    pub colors: ops::Range<usize>,
    pub tex_coords: ops::Range<usize>,
}

impl<S> Default for IntermediaryVertexData<S> {
    fn default() -> Self {
        IntermediaryVertexData {
            points: Default::default(),
            colors: Default::default(),
            tex_coords: Default::default(),
        }
    }
}

impl<S> Default for IntermediaryMesh<S> {
    fn default() -> Self {
        IntermediaryMesh {
            vertex_data: Default::default(),
            indices: Default::default(),
        }
    }
}

impl Default for IntermediaryVertexDataRanges {
    fn default() -> Self {
        IntermediaryVertexDataRanges {
            points: 0..0,
            colors: 0..0,
            tex_coords: 0..0,
        }
    }
}

/// The vertex and index ranges into a mesh for a particular node.
#[derive(Clone, Debug)]
struct Ranges {
    vertices: ops::Range<usize>,
    indices: ops::Range<usize>,
}

const WOULD_CYCLE: &'static str =
    "drawing the given primitive with the given relative positioning would have caused a cycle \
     within the geometry graph";

/// An iterator yielding the transformed, indexed vertices for a node.
pub type NodeVertices<'a, S = geom::scalar::Default> =
    node::TransformedVertices<::mesh::Vertices<Ref<'a, Mesh<S>>>, S>;

// /// An iterator yielding the transformed vertices for a node.
// pub struct NodeVertices<'a, S> {
// }

/// An iterator yielding the transformed raw vertices for a node.
pub type RawNodeVertices<'a, S = geom::scalar::Default> =
    node::TransformedVertices<::mesh::RawVertices<Ref<'a, Mesh<S>>>, S>;

/// An iterator yielding the transformed triangles for a node.
pub type NodeTriangles<'a, S = geom::scalar::Default> =
    geom::tri::IterFromVertices<NodeVertices<'a, S>>;

/// An iterator yielding all indexed mesh vertices transformed via the geometry graph.
#[derive(Debug)]
pub struct Vertices<'a, S = geom::scalar::Default>
where
    S: 'a + BaseFloat,
{
    draw: &'a Draw<S>,
    node_vertices: Option<NodeVertices<'a, S>>,
}

/// An iterator yielding all indexed mesh triangles transformed via the geometry graph.
pub type Triangles<'a, S = geom::scalar::Default> = geom::tri::IterFromVertices<Vertices<'a, S>>;

/// An iterator yielding all raw mesh vertices transformed via the geometry graph.
#[derive(Debug)]
pub struct RawVertices<'a, S = geom::scalar::Default>
where
    S: 'a + BaseFloat,
{
    draw: &'a Draw<S>,
    node_vertices: Option<RawNodeVertices<'a, S>>,
}

// Given some `position` along the given axis return the resulting geom::Graph edge and the parent.
fn position_to_edge<S, F>(
    node_index: node::Index,
    position: &Position<S>,
    draw: &mut State<S>,
    axis: edge::Axis,
    point_axis: &F,
) -> (geom::graph::Edge<S>, node::Index)
where
    S: BaseFloat,
    F: Fn(&mesh::vertex::Point<S>) -> S,
{
    match *position {
        // *s* relative to *origin*.
        Position::Absolute(s) => {
            let edge = geom::graph::Edge::position(axis, s);
            let origin = draw.geom_graph.origin();
            (edge, origin)
        }

        Position::Relative(relative, maybe_parent) => {
            let parent = maybe_parent
                .or(draw.last_node_drawn)
                .unwrap_or(draw.geom_graph.origin());
            let edge = match relative {
                // Relative position.
                position::Relative::Scalar(s) => geom::graph::Edge::position(axis, s),

                // Align end with
                position::Relative::Align(align) => match align {
                    position::Align::Middle => {
                        let zero = S::zero();
                        geom::graph::Edge::position(axis, zero)
                    }
                    align => {
                        let one = S::one();
                        let (direction, margin) = match align {
                            position::Align::Start(mgn) => (-one, mgn.unwrap_or(S::zero())),
                            position::Align::End(mgn) => (one, mgn.unwrap_or(S::zero())),
                            _ => unreachable!(),
                        };
                        let node_dimension = draw
                            .untransformed_dimension_of(&node_index, point_axis)
                            .unwrap();
                        let parent_dimension = draw
                            .dimension_of(&parent, point_axis)
                            .expect("no node for relative position");
                        let half = S::from(0.5).unwrap();
                        let node_half_dim = node_dimension * half;
                        let parent_half_dim = parent_dimension * half;
                        let weight = direction * (parent_half_dim - node_half_dim - margin);
                        geom::graph::Edge::position(axis, weight)
                    }
                },

                position::Relative::Direction(direction, amt) => {
                    let one = S::one();
                    let direction = match direction {
                        position::Direction::Backwards => -one,
                        position::Direction::Forwards => one,
                    };
                    let node_dimension = draw
                        .untransformed_dimension_of(&node_index, point_axis)
                        .unwrap();
                    let parent_dimension = draw
                        .dimension_of(&parent, point_axis)
                        .expect("no node for relative position");
                    let half = S::from(0.5).unwrap();
                    let node_half_dim = node_dimension * half;
                    let parent_half_dim = parent_dimension * half;
                    let weight = direction * (parent_half_dim + node_half_dim + amt);
                    geom::graph::Edge::position(axis, weight)
                }
            };
            (edge, parent)
        }
    }
}

// Given some `orientation` around the given axis return the resulting `geom::Graph` edge and the
// parent.
fn orientation_to_edge<S>(
    orientation: &Orientation<S>,
    draw: &mut State<S>,
    axis: edge::Axis,
) -> (geom::graph::Edge<S>, node::Index)
where
    S: BaseFloat,
{
    match *orientation {
        Orientation::Absolute(s) => {
            let edge = geom::graph::Edge::orientation(axis, s);
            let origin = draw.geom_graph.origin();
            (edge, origin)
        }
        Orientation::Relative(s, maybe_parent) => {
            let parent = maybe_parent
                .or(draw.last_node_drawn)
                .unwrap_or(draw.geom_graph.origin());
            let edge = geom::graph::Edge::orientation(axis, s);
            (edge, parent)
        }
    }
}

fn point_x<S: Clone>(p: &mesh::vertex::Point<S>) -> S {
    p.x.clone()
}
fn point_y<S: Clone>(p: &mesh::vertex::Point<S>) -> S {
    p.y.clone()
}
fn point_z<S: Clone>(p: &mesh::vertex::Point<S>) -> S {
    p.z.clone()
}

// Convert the given `drawing` into its **Drawn** state and insert it into the mesh and geometry
// graph.
fn into_drawn<T, S>(
    draw: &mut State<S>,
    node_index: node::Index,
    drawing: T,
) -> Result<(), geom::graph::WouldCycle<S>>
where
    T: IntoDrawn<S>,
    S: BaseFloat,
{
    // Convert the target into its **Drawn** state.
    let (spatial, vertices, indices) = drawing.into_drawn(properties::Draw::new(draw));

    // Update the mesh with the non-transformed vertices.
    let vertices_start_index = draw.mesh.raw_vertex_count();
    let indices_start_index = draw.mesh.indices().len();

    {
        let State {
            ref mut mesh,
            ref intermediary_mesh,
            ..
        } = *draw;
        let intermediary_mesh = &*intermediary_mesh.borrow();
        let vertices = properties::Vertices::into_iter(vertices, intermediary_mesh);
        let indices = properties::Indices::into_iter(indices, &intermediary_mesh.indices)
            .map(|i| vertices_start_index + i);
        mesh.extend(vertices, indices);
    }

    // Update the **Draw**'s range map.
    let vertices_end_index = draw.mesh.raw_vertex_count();
    let indices_end_index = draw.mesh.indices().len();
    let vertices = vertices_start_index..vertices_end_index;
    let indices = indices_start_index..indices_end_index;
    let ranges = Ranges { vertices, indices };
    draw.ranges.insert(node_index, ranges);

    // Update the position edges within the geometry graph.
    let p = &spatial.position;
    let x = p.x.map(|pos| {
        (
            pos,
            edge::Axis::X,
            point_x as fn(&mesh::vertex::Point<S>) -> S,
        )
    });
    let y = p.y.map(|pos| (pos, edge::Axis::Y, point_y as _));
    let z = p.z.map(|pos| (pos, edge::Axis::Z, point_z as _));
    let positions = x.into_iter().chain(y).chain(z);
    for (position, axis, point_axis) in positions {
        let (edge, parent) = position_to_edge(node_index, &position, draw, axis, &point_axis);
        draw.geom_graph.set_edge(parent, node_index, edge)?;
    }

    // Update the orientation edges within the geometry graph.
    match spatial.orientation {
        orientation::Properties::LookAt(look_at) => {
            // The location of the target.
            let _p = match look_at {
                orientation::LookAt::Node(_node) => unimplemented!(),
                orientation::LookAt::Point(point) => point,
            };
            unimplemented!();
        }
        orientation::Properties::Axes(axes) => {
            let x = axes.x.map(|axis| (axis, edge::Axis::X));
            let y = axes.y.map(|axis| (axis, edge::Axis::Y));
            let z = axes.z.map(|axis| (axis, edge::Axis::Z));
            let axes = x.into_iter().chain(y).chain(z);
            for (orientation, axis) in axes {
                let (edge, parent) = orientation_to_edge(&orientation, draw, axis);
                draw.geom_graph.set_edge(parent, node_index, edge)?;
            }
        }
    }

    // Set this node as the last drawn node.
    draw.last_node_drawn = Some(node_index);

    Ok(())
}

// Convert the given `primitive` into its **Drawn** state and insert it into the mesh and geometry
// graph.
fn draw_primitive<S>(
    draw: &mut State<S>,
    node_index: node::Index,
    primitive: Primitive<S>,
) -> Result<(), geom::graph::WouldCycle<S>>
where
    S: BaseFloat,
{
    match primitive {
        Primitive::Ellipse(prim) => into_drawn(draw, node_index, prim),
        Primitive::Line(prim) => into_drawn(draw, node_index, prim),
        Primitive::MeshVertexless(prim) => into_drawn(draw, node_index, prim),
        Primitive::Mesh(prim) => into_drawn(draw, node_index, prim),
        Primitive::PolygonPointless(prim) => into_drawn(draw, node_index, prim),
        Primitive::PolygonFill(prim) => into_drawn(draw, node_index, prim),
        Primitive::PolygonColorPerVertex(prim) => into_drawn(draw, node_index, prim),
        Primitive::PolylineVertexless(prim) => into_drawn(draw, node_index, prim),
        Primitive::Polyline(prim) => into_drawn(draw, node_index, prim),
        Primitive::Quad(prim) => into_drawn(draw, node_index, prim),
        Primitive::Rect(prim) => into_drawn(draw, node_index, prim),
        Primitive::Tri(prim) => into_drawn(draw, node_index, prim),
    }
}

// Produce the min and max over the axis yielded via `point_axis` for the given `points`.
fn min_max_dimension<I, F, S>(points: I, point_axis: &F) -> Option<(S, S)>
where
    I: IntoIterator<Item = mesh::vertex::Point<S>>,
    F: Fn(&mesh::vertex::Point<S>) -> S,
    S: BaseFloat,
{
    let mut points = points.into_iter();
    points.next().map(|first| {
        let s = point_axis(&first);
        let init = (s, s);
        points.fold(init, |(min, max), p| {
            let s = point_axis(&p);
            (s.min(min), s.max(max))
        })
    })
}

impl<S> IntermediaryVertexData<S> {
    /// Clears all buffers.
    pub fn reset(&mut self) {
        self.points.clear();
        self.colors.clear();
        self.tex_coords.clear();
    }
}

impl<S> IntermediaryMesh<S> {
    /// Clears all buffers.
    pub fn reset(&mut self) {
        self.vertex_data.reset();
        self.indices.clear();
    }
}

impl<S> State<S>
where
    S: BaseFloat,
{
    // Resets all state within the `Draw` instance.
    fn reset(&mut self) {
        self.geom_graph.clear();
        self.geom_graph_dfs.borrow_mut().reset(&self.geom_graph);
        self.drawing.clear();
        self.ranges.clear();
        self.intermediary_mesh.borrow_mut().reset();
        self.mesh.clear();
        self.background_color = None;
        self.last_node_drawn = None;
    }

    // // Produce the transformed mesh vertices for the node at the given index.
    // //
    // // Returns **None** if there is no node for the given index.
    // fn node_vertices(&mut self, n: node::Index) -> Option<NodeVertices<S>> {

    // }

    // Drain any remaining `drawing`s, convert them to their **Drawn** state and insert them into
    // the inner mesh and geometry graph.
    fn finish_remaining_drawings(&mut self) -> Result<(), geom::graph::WouldCycle<S>> {
        let mut drawing = mem::replace(&mut self.drawing, Default::default());
        for (node_index, primitive) in drawing.drain() {
            draw_primitive(self, node_index, primitive)?;
        }
        mem::replace(&mut self.drawing, drawing);
        Ok(())
    }

    // Finish the drawing at the given node index if it is not yet complete.
    fn finish_drawing(&mut self, n: &node::Index) -> Result<(), geom::graph::WouldCycle<S>> {
        if let Some(primitive) = self.drawing.remove(n) {
            draw_primitive(self, *n, primitive)?;
        }
        Ok(())
    }

    // The length of the untransformed node at the given index along the axis returned by the
    // given `point_axis` function.
    //
    // **Note:** If this node's **Drawing** is not yet complete, this method will cause it to
    // finish and submit the **Drawn** state to the inner geometry graph and mesh.
    fn untransformed_dimension_of<F>(&mut self, n: &node::Index, point_axis: &F) -> Option<S>
    where
        F: Fn(&mesh::vertex::Point<S>) -> S,
    {
        self.finish_drawing(n).expect(WOULD_CYCLE);
        self.ranges.get(n).and_then(|ranges| {
            let points = self.mesh.points()[ranges.vertices.clone()].iter().cloned();
            min_max_dimension(points, point_axis).map(|(min, max)| max - min)
        })
    }

    // The length of the untransformed node at the given index along the *x* axis.
    fn untransformed_x_dimension_of(&mut self, n: &node::Index) -> Option<S> {
        self.untransformed_dimension_of(n, &point_x)
    }

    // The length of the untransformed node at the given index along the *y* axis.
    fn untransformed_y_dimension_of(&mut self, n: &node::Index) -> Option<S> {
        self.untransformed_dimension_of(n, &point_y)
    }

    // The length of the untransformed node at the given index along the *y* axis.
    fn untransformed_z_dimension_of(&mut self, n: &node::Index) -> Option<S> {
        self.untransformed_dimension_of(n, &point_z)
    }

    // The length of the transformed node at the given index along the axis returned by the given
    // `point_axis` function.
    //
    // **Note:** If this node's **Drawing** is not yet complete, this method will cause it to
    // finish and submit the **Drawn** state to the inner geometry graph and mesh.
    fn dimension_of<F>(&mut self, n: &node::Index, point_axis: &F) -> Option<S>
    where
        F: Fn(&mesh::vertex::Point<S>) -> S,
    {
        self.finish_drawing(n).expect(WOULD_CYCLE);
        self.ranges.get(n).and_then(|ranges| {
            let points = self.mesh.points()[ranges.vertices.clone()].iter().cloned();
            let points = self
                .geom_graph
                .node_vertices(*n, points)
                .expect("no node at index");
            min_max_dimension(points, point_axis).map(|(min, max)| max - min)
        })
    }

    // The length of the transformed node at the given index along the *x* axis.
    fn x_dimension_of(&mut self, n: &node::Index) -> Option<S> {
        self.dimension_of(n, &point_x)
    }

    // The length of the transformed node at the given index along the *y* axis.
    fn y_dimension_of(&mut self, n: &node::Index) -> Option<S> {
        self.dimension_of(n, &point_y)
    }

    // The length of the transformed node at the given index along the *z* axis.
    fn z_dimension_of(&mut self, n: &node::Index) -> Option<S> {
        self.dimension_of(n, &point_z)
    }
}

impl<S> Draw<S>
where
    S: BaseFloat,
{
    /// Create a new **Draw** instance.
    ///
    /// This is the same as calling **Draw::default**.
    pub fn new() -> Self {
        Self::default()
    }

    /// Resets all state within the `Draw` instance.
    pub fn reset(&self) {
        self.state.borrow_mut().reset();
    }

    // Primitive geometry.

    /// Specify a color with which the background should be cleared.
    pub fn background(&self) -> Background<S> {
        background::new(self)
    }

    /// Add the given type to be drawn.
    pub fn a<T>(&self, primitive: T) -> Drawing<T, S>
    where
        T: IntoDrawn<S> + Into<Primitive<S>>,
        Primitive<S>: Into<Option<T>>,
    {
        let index = self
            .state
            .borrow_mut()
            .geom_graph
            .add_node(geom::graph::Node::Point);
        let primitive: Primitive<S> = primitive.into();
        self.state.borrow_mut().drawing.insert(index, primitive);
        drawing::new(self, index)
    }

    /// Begin drawing an **Ellipse**.
    pub fn ellipse(&self) -> Drawing<properties::Ellipse<S>, S> {
        self.a(Default::default())
    }

    /// Begin drawing a **Line**.
    pub fn line(&self) -> Drawing<properties::Line<S>, S> {
        self.a(Default::default())
    }

    /// Begin drawing a **Quad**.
    pub fn quad(&self) -> Drawing<properties::Quad<S>, S> {
        self.a(Default::default())
    }

    /// Begin drawing a **Rect**.
    pub fn rect(&self) -> Drawing<properties::Rect<S>, S> {
        self.a(Default::default())
    }

    /// Begin drawing a **Triangle**.
    pub fn tri(&self) -> Drawing<properties::Tri<S>, S> {
        self.a(Default::default())
    }

    /// Begin drawing a **Polygon**.
    pub fn polygon(&self) -> Drawing<properties::primitive::polygon::Pointless, S> {
        self.a(Default::default())
    }

    /// Begin drawing a **Mesh**.
    pub fn mesh(&self) -> Drawing<properties::primitive::mesh::Vertexless, S> {
        self.a(Default::default())
    }

    /// Begin drawing a **Polyline**.
    pub fn polyline(&self) -> Drawing<properties::primitive::polyline::Vertexless, S> {
        self.a(Default::default())
    }

    /// Produce the transformed mesh vertices for the node at the given index.
    ///
    /// Returns **None** if there is no node for the given index.
    pub fn node_vertices(&self, n: node::Index) -> Option<NodeVertices<S>> {
        self.state
            .borrow_mut()
            .finish_drawing(&n)
            .expect(WOULD_CYCLE);
        let index_range = match self.state.borrow().ranges.get(&n) {
            None => return None,
            Some(ranges) => ranges.indices.clone(),
        };
        let vertices = ::mesh::vertices(self.inner_mesh()).index_range(index_range);
        self.state.borrow().geom_graph.node_vertices(n, vertices)
    }

    /// Produce the transformed triangles for the node at the given index.
    ///
    /// **Note:** If the node's **Drawing** was still in progress, it will first be finished and
    /// inserted into the mesh and geometry graph before producing the triangles iterator.
    pub fn node_triangles(&self, n: node::Index) -> Option<NodeTriangles<S>> {
        self.node_vertices(n).map(geom::tri::iter_from_vertices)
    }

    /// Produce an iterator yielding all vertices from the inner mesh transformed via the inner
    /// geometry graph.
    ///
    /// This method ignores the mesh indices buffer and instead produces the vertices "raw".
    ///
    /// **Note:** If there are any **Drawing**s in progress, these will first be drained and
    /// completed before any vertices are yielded.
    pub fn raw_vertices(&self) -> RawVertices<S> {
        self.finish_remaining_drawings().expect(WOULD_CYCLE);
        let state = self.state.borrow();
        state.geom_graph_dfs.borrow_mut().reset(&state.geom_graph);
        let draw = self;
        let node_vertices = None;
        RawVertices {
            draw,
            node_vertices,
        }
    }

    /// Produce an iterator yielding all indexed vertices from the inner mesh transformed via the
    /// inner geometry graph.
    ///
    /// Vertices are yielded in depth-first-order of the geometry graph nodes from which they are
    /// produced.
    ///
    /// **Note:** If there are any **Drawing**s in progress, these will first be drained and
    /// completed before any vertices are yielded.
    pub fn vertices(&self) -> Vertices<S> {
        self.finish_remaining_drawings().expect(WOULD_CYCLE);
        let state = self.state.borrow();
        state.geom_graph_dfs.borrow_mut().reset(&state.geom_graph);
        let draw = self;
        let node_vertices = None;
        Vertices {
            draw,
            node_vertices,
        }
    }

    /// Produce an iterator yielding all triangles from the inner mesh transformed via the inner
    /// geometry graph.
    ///
    /// Triangles are yielded in depth-first-order of the geometry graph nodes from which they are
    /// produced.
    ///
    /// **Note:** If there are any **Drawing**s in progress, these will first be drained and
    /// completed before any vertices are yielded.
    pub fn triangles(&self) -> Triangles<S> {
        geom::tri::iter_from_vertices(self.vertices())
    }

    /// Borrow the **Draw**'s inner **Mesh**.
    pub fn inner_mesh(&self) -> Ref<Mesh<S>> {
        Ref::map(self.state.borrow(), |s| &s.mesh)
    }

    // Dimensions methods.

    /// The length of the untransformed node at the given index along the axis returned by the
    /// given `point_axis` function.
    pub fn untransformed_dimension_of<F>(&self, n: &node::Index, point_axis: &F) -> Option<S>
    where
        F: Fn(&mesh::vertex::Point<S>) -> S,
    {
        self.state
            .borrow_mut()
            .untransformed_dimension_of(n, point_axis)
    }

    /// The length of the untransformed node at the given index along the *x* axis.
    pub fn untransformed_x_dimension_of(&self, n: &node::Index) -> Option<S> {
        self.state.borrow_mut().untransformed_x_dimension_of(n)
    }

    /// The length of the untransformed node at the given index along the *y* axis.
    pub fn untransformed_y_dimension_of(&self, n: &node::Index) -> Option<S> {
        self.state.borrow_mut().untransformed_y_dimension_of(n)
    }

    /// The length of the untransformed node at the given index along the *y* axis.
    pub fn untransformed_z_dimension_of(&self, n: &node::Index) -> Option<S> {
        self.state.borrow_mut().untransformed_z_dimension_of(n)
    }

    /// Determine the raw, untransformed dimensions of the node at the given index.
    ///
    /// Returns `None` if their is no node within the **geom::Graph** for the given index or if
    /// the node has not yet been **Drawn**.
    pub fn untransformed_dimensions_of(&self, n: &node::Index) -> Option<Vector3<S>> {
        if self.state.borrow().geom_graph.node(*n).is_none()
            || !self.state.borrow().ranges.contains_key(n)
        {
            return None;
        }
        let dimensions = Vector3 {
            x: self.untransformed_x_dimension_of(n).unwrap_or_else(S::zero),
            y: self.untransformed_y_dimension_of(n).unwrap_or_else(S::zero),
            z: self.untransformed_z_dimension_of(n).unwrap_or_else(S::zero),
        };
        Some(dimensions)
    }

    /// The length of the transformed node at the given index along the axis returned by the given
    /// `point_axis` function.
    pub fn dimension_of<F>(&self, n: &node::Index, point_axis: &F) -> Option<S>
    where
        F: Fn(&mesh::vertex::Point<S>) -> S,
    {
        self.state.borrow_mut().dimension_of(n, point_axis)
    }

    /// The length of the transformed node at the given index along the *x* axis.
    pub fn x_dimension_of(&self, n: &node::Index) -> Option<S> {
        self.state.borrow_mut().x_dimension_of(n)
    }

    /// The length of the transformed node at the given index along the *y* axis.
    pub fn y_dimension_of(&self, n: &node::Index) -> Option<S> {
        self.state.borrow_mut().y_dimension_of(n)
    }

    /// The length of the transformed node at the given index along the *z* axis.
    pub fn z_dimension_of(&self, n: &node::Index) -> Option<S> {
        self.state.borrow_mut().z_dimension_of(n)
    }

    /// Drain any remaining `drawing`s, convert them to their **Drawn** state and insert them into
    /// the inner mesh and geometry graph.
    pub fn finish_remaining_drawings(&self) -> Result<(), geom::graph::WouldCycle<S>> {
        self.state.borrow_mut().finish_remaining_drawings()
    }
}

impl<S> Default for State<S>
where
    S: BaseFloat,
{
    fn default() -> Self {
        let geom_graph = Default::default();
        let geom_graph_dfs = RefCell::new(geom::graph::node::Dfs::new(&geom_graph));
        let drawing = Default::default();
        let intermediary_mesh = RefCell::new(Default::default());
        let mesh = Default::default();
        let ranges = Default::default();
        let theme = Default::default();
        let last_node_drawn = Default::default();
        let background_color = Default::default();
        State {
            geom_graph,
            geom_graph_dfs,
            intermediary_mesh,
            mesh,
            drawing,
            ranges,
            theme,
            last_node_drawn,
            background_color,
        }
    }
}

impl<S> Default for Draw<S>
where
    S: BaseFloat,
{
    fn default() -> Self {
        let state = RefCell::new(Default::default());
        Draw { state }
    }
}

impl<'a, S> Iterator for Vertices<'a, S>
where
    S: BaseFloat,
{
    type Item = mesh::Vertex<S>;
    fn next(&mut self) -> Option<Self::Item> {
        let Vertices {
            ref draw,
            ref mut node_vertices,
        } = *self;
        loop {
            if let Some(v) = node_vertices.as_mut().and_then(|n| n.next()) {
                return Some(v);
            }
            let next_transform = {
                let state = draw.state.borrow();
                let mut dfs = state.geom_graph_dfs.borrow_mut();
                dfs.next_transform(&state.geom_graph)
            };
            match next_transform {
                None => return None,
                Some((n, transform)) => {
                    let index_range = match draw.state.borrow().ranges.get(&n) {
                        None => continue,
                        Some(ranges) => ranges.indices.clone(),
                    };
                    let vertices = ::mesh::vertices(draw.inner_mesh()).index_range(index_range);
                    let transformed_vertices = transform.vertices(vertices);
                    *node_vertices = Some(transformed_vertices);
                }
            }
        }
    }
}

impl<'a, S> Iterator for RawVertices<'a, S>
where
    S: BaseFloat,
{
    type Item = mesh::Vertex<S>;
    fn next(&mut self) -> Option<Self::Item> {
        let RawVertices {
            ref draw,
            ref mut node_vertices,
        } = *self;
        loop {
            if let Some(v) = node_vertices.as_mut().and_then(|n| n.next()) {
                return Some(v);
            }
            let next_transform = {
                let state = draw.state.borrow();
                let mut dfs = state.geom_graph_dfs.borrow_mut();
                dfs.next_transform(&state.geom_graph)
            };
            match next_transform {
                None => return None,
                Some((n, transform)) => {
                    let vertex_range = match draw.state.borrow().ranges.get(&n) {
                        None => continue,
                        Some(ranges) => ranges.vertices.clone(),
                    };
                    let vertices = ::mesh::raw_vertices(draw.inner_mesh()).range(vertex_range);
                    let transformed_vertices = transform.vertices(vertices);
                    *node_vertices = Some(transformed_vertices);
                }
            }
        }
    }
}