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
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
//! A trait for resource types with arbitrary `draw` functionality and a
//! default implementation that supports switching to a "quad viewport" mode.

use ::{std, cgmath, glium, glium::glutin, image, vec_map};
use ::{color, graphics, mesh, render, render::params, shader, texture, vertex,
  Render};

pub const MAIN_VIEWPORT        : usize = 0;
pub const UPPER_LEFT_VIEWPORT  : usize = 1;
pub const UPPER_RIGHT_VIEWPORT : usize = 2;
pub const LOWER_LEFT_VIEWPORT  : usize = 3;
#[allow(dead_code)]
pub const LOWER_RIGHT_VIEWPORT : usize = 0;  // unused

// indices into `textures_16x16` array texture
/// For use with `BLEND_FUNC_NORMAL`
pub const TEXTURE_16X16_INDEX_CROSSHAIR              : u32 = 0;
/// For use with `BLEND_FUNC_INVERT_COLOR`
pub const TEXTURE_16X16_INDEX_CROSSHAIR_INVERSE      : u32 = 1;

// indices into `tileset_textures_128x128` array texture
/// For use with `BLEND_FUNC_NORMAL`
pub const TILESET_128X128_INDEX_EASCII_ACORN         : u32 = 0;
/// For use with `BLEND_FUNC_INVERT_COLOR`
pub const TILESET_128X128_INDEX_EASCII_ACORN_INVERSE : u32 = 1;

/// Index into `sprites_16x16_vertices` for the crosshair.
///
/// In `draw_2d` this vertex is drawn as a separate draw call.
pub const CROSSHAIR_SPRITE_16X16_VERTEX_INDEX        : u32 = 0;

pub const MESH_3D_GRID_DIMS                          : u16 = 12;

lazy_static!{
  static ref VIEWPORT_TILE_DATA_DEFAULT : ViewportTileData = Default::default();
}

/// Represents a generic Glium resource type for a renderer to use as a source
/// of *drawing* (vertex rendering).
///
/// The resource should have all the shader programs, vertex buffers, textures,
/// etc. necessary to make a `draw` call on a given `glium::Frame`.
///
/// The default frame functions will call the `draw_2d` and `draw_3d` methods,
/// which do nothing by default.
pub trait Resource {
  fn new     (glium_display : &glium::Display) -> Self;
  fn init    (_render : &mut Render <Self>)
    where Self : Sized { /* default: do nothing */ }
  fn draw_2d (_render : &Render <Self>, _glium_frame : &mut glium::Frame)
    where Self : Sized { /* default: do nothing */ }
  fn draw_3d (_render : &Render <Self>, _glium_frame : &mut glium::Frame)
    where Self : Sized { /* default: do nothing */ }
}

/// A default implementation of `Resource` containing the builtin shader
/// programs and some pre-defined vertex sources.
pub struct DefaultResource {
  pub shader_programs               : vec_map::VecMap     <glium::Program>,

  //
  // 2d drawing resources
  //
  // sprites
  /// Texture array of 16x16 pixel general purpose textures
  pub textures_16x16                : glium::texture::Texture2dArray,
  /// Position and texture index of 2d sprites sprites indexing the
  /// 16x16 texture array
  pub sprite_16x16_vertices         : glium::VertexBuffer <vertex::Vert2dLayer>,
  // tiles
  /// Texture array of 128x128 pixel tileset textures with 8x8 tile dimensions
  pub tileset_textures_128x128      : glium::texture::Texture2dArray,
  /// Tile vertices with sub-ranges mapped to viewports by
  /// `viewport_tile_data[i].vertex_range`.
  ///
  /// In the default 2D drawing function, each viewport draws with the slice of
  /// tile vertices represented by its range.
  pub tile_vertices                 : glium::VertexBuffer <vertex::Vert2dTile>,
  // viewports
  /// Data used by each viewport when drawing tiles
  pub viewport_tile_data            : vec_map::VecMap     <ViewportTileData>,
  /// Vertices for each viewport to be rendered as line loops
  // TODO: combine this with other 2d vertex data ?
  pub viewport_line_loop_vertices   : glium::VertexBuffer <vertex::Vert2d>,

  //
  // 3d drawing resources
  //
  // instanced meshes
  /// 3D vertices for instanced drawing.
  ///
  /// Multiple instanced meshes are stored here, indexed by slices of
  /// `instanced_3d_indices_lines`.
  pub instanced_3d_vertices         : glium::VertexBuffer
    <vertex::Vert3dInstanced>,
  /// Indices for drawing instanced 3D meshes in `instanced_3d_vertices`.
  ///
  /// Each separate mesh has a corresponding slice of indices in this index
  /// buffer.
  pub instanced_3d_indices_lines    : glium::IndexBuffer  <u32>,
  pub per_instance_3d_vertices      : glium::VertexBuffer
    <vertex::Vert3dOrientationScaleColor>,
  // grid
  /// Slice of `instanced_3d_indices_lines` that contains the indices for
  /// rendering the debug grid mesh as a lines list
  pub grid_instanced_3d_index_lines_range       : std::ops::Range <usize>,
  /// Per-instance vertices used to draw instanced XY grid mesh
  pub grid_per_instance_3d_vertex_range         : std::ops::Range <usize>,
  // hemisphere
  /// Slice of `instanced_3d_indices_lines` that contains the indices for
  /// rendering the hemisphere mesh as a lines list
  pub hemisphere_instanced_3d_index_lines_range : std::ops::Range <usize>,
  /// Per-instance vertices used to draw instanced hemisphere mesh
  pub hemisphere_per_instance_3d_vertex_range   : std::ops::Range <usize>,
  // sphere
  /// Slice of `instanced_3d_indices_lines` that contains the indices for
  /// rendering the sphere mesh as a lines list
  pub sphere_instanced_3d_index_lines_range     : std::ops::Range <usize>,
  /// Per-instance vertices used to draw instanced sphere mesh
  pub sphere_per_instance_3d_vertex_range       : std::ops::Range <usize>,
  // capsule
  /// Slice of `instanced_3d_indices_lines` that contains the indices for
  /// rendering the capsule mesh as a lines list
  pub capsule_instanced_3d_index_lines_range    : std::ops::Range <usize>,
  /// Per-instance vertices used to draw instanced capsule mesh
  pub capsule_per_instance_3d_vertex_range      : std::ops::Range <usize>,
  // cylinder
  /// Slice of `instanced_3d_indices_lines` that contains the indices for
  /// rendering the cylinder mesh as a lines list
  pub cylinder_instanced_3d_index_lines_range   : std::ops::Range <usize>,
  /// Per-instance vertices used to draw instanced cylinder mesh
  pub cylinder_per_instance_3d_vertex_range     : std::ops::Range <usize>,
  // aabb
  pub aabb_per_instance_3d_vertex_range         : std::ops::Range <usize>,

  // some uniforms for the capsule shader
  capsule_vertex_id_offset : u32,
  hemisphere_vertex_count  : u32,
}

/// Per-viewport data for tile rendering
pub struct ViewportTileData {
  /// Each range defines the tiles in the `tiles_vertex_buffer` belonging to the
  /// corresponding viewport.
  ///
  /// In the default 2D drawing function, each viewport draws with the slice of
  /// tile vertices represented by its range.
  pub vertex_range   : std::ops::Range <usize>,
  /// A positive margin will shift the tile grid relative to the left of the
  /// viewport by this many pixels.
  pub margin_px_left : i16,
  /// A positive margin will shift the tile grid downward from the top of the
  /// viewport by this many pixels.
  pub margin_px_top  : i16
}

///////////////////////////////////////////////////////////////////////////////
//  impls                                                                    //
///////////////////////////////////////////////////////////////////////////////

impl Resource for DefaultResource {
  fn new (glium_display : &glium::Display) -> Self {
    use cgmath::SquareMatrix;

    //
    //  shaders
    //
    let shader_programs = shader::build_programs (glium_display).unwrap();

    //
    //  textures
    //
    // 2d textures
    let textures_16x16 = texture::texture2darray_with_mipmaps_from_bytes (
      glium_display,
      vec![
        // for use with normal blending
        texture::CROSSHAIR_PNG_FILE_BYTES,
        // for use with inverse blending
        texture::CROSSHAIR_INVERSE_PNG_FILE_BYTES,
      ],
      image::PNG,
      glium::texture::MipmapsOption::NoMipmap
    ).unwrap();

    // 2d tileset
    let tileset_textures_128x128
      = texture::texture2darray_with_mipmaps_from_bytes
    (
      glium_display,
      vec![
        // for use with normal blending
        texture::TILESET_EASCII_ACORN_8X8_PNG_FILE_BYTES,
        // for use with inverse blending
        texture::TILESET_EASCII_ACORN_8X8_INVERSE_PNG_FILE_BYTES,
      ],
      image::PNG,
      glium::texture::MipmapsOption::NoMipmap
    ).unwrap();

    //
    //  vertex data
    //
    // 2d sprites
    let sprite_16x16_vertices = glium::VertexBuffer::immutable (
      glium_display,
      &[
        // crosshair
        vertex::Vert2dLayer { position: [0.0, 0.0], layer: 1 }
      ]
    ).unwrap();

    // 2d tiles
    let tile_vertices      = glium::VertexBuffer::dynamic (
      glium_display, &[ ]
    ).unwrap();
    let viewport_tile_data = vec_map::VecMap::with_capacity (
      render::INITIAL_VIEWPORT_VECMAP_CAPACITY);

    // 2d viewport line loops
    let viewport_line_loop_vertices = glium::VertexBuffer::dynamic (
      glium_display, &[ ]
    ).unwrap();

    // 3d instanced mesh data
    const GRID_DIMS                 : u16 = MESH_3D_GRID_DIMS;
    const HEMISPHERE_LATITUDE_DIVS  : u16 = 6;
    const SPHERE_LATITUDE_DIVS      : u16 = 2 * HEMISPHERE_LATITUDE_DIVS;
    const LONGITUDE_DIVS            : u16 = 24;
    const CYLINDER_DIVS             : u16 = LONGITUDE_DIVS;
    let (vertex_count, index_count) : (u32, u32) = (cgmath::Vector2::from (
      mesh::grid_3d_instanced_lines_list_counts (GRID_DIMS)
    ) + cgmath::Vector2::from (
      mesh::capsule_3d_instanced_lines_list_counts (
        HEMISPHERE_LATITUDE_DIVS, LONGITUDE_DIVS)
    ) + cgmath::Vector2::from (
      mesh::cylinder_3d_instanced_lines_list_counts (CYLINDER_DIVS)
    )).into();

    let mut instanced_3d_vertex_data = Vec::with_capacity (vertex_count as usize);
    let mut instanced_3d_index_data  = Vec::with_capacity (index_count  as usize);
    // constant value to shift all indices during mesh creation
    let mut index_offset      = 0;
    // the beginning of the range where indices begin for the next mesh
    let mut index_range_start = 0;

    // grid
    let (mut grid_vertex_data, mut grid_index_data)
      = mesh::grid_3d_instanced_lines_list (index_offset, GRID_DIMS);
    let grid_instanced_3d_index_lines_range
      = index_range_start..index_range_start + grid_index_data.len();
    let grid_per_instance_3d_vertex_range = 0..0; // empty
    instanced_3d_vertex_data.append (&mut grid_vertex_data);
    instanced_3d_index_data.append  (&mut grid_index_data);
    index_offset      = instanced_3d_vertex_data.len() as u32;
    index_range_start = instanced_3d_index_data.len();

    // capsule: vertex and index data will be shared with sphere and hemisphere
    // meshes
    let capsule_vertex_id_offset = index_offset; // uniform used by capsule shader
    let (mut capsule_vertex_data, mut capsule_index_data)
      = mesh::capsule_3d_instanced_lines_list (
          index_offset, HEMISPHERE_LATITUDE_DIVS, LONGITUDE_DIVS);
    let capsule_instanced_3d_index_lines_range
      = index_range_start..index_range_start + capsule_index_data.len();
    let capsule_per_instance_3d_vertex_range = 0..0; // empty
    instanced_3d_vertex_data.append (&mut capsule_vertex_data);
    instanced_3d_index_data.append  (&mut capsule_index_data);

    index_offset      = instanced_3d_vertex_data.len() as u32;
    index_range_start = instanced_3d_index_data.len();

    // hemisphere: this is defined to share the top half of the vertices and
    // indices of the capsule mesh
    let (hemisphere_vertex_count, hemisphere_index_count)
      = mesh::hemisphere_3d_instanced_lines_list_counts (
          HEMISPHERE_LATITUDE_DIVS, LONGITUDE_DIVS);
    let hemisphere_instanced_3d_index_lines_range =
      capsule_instanced_3d_index_lines_range.start..
      capsule_instanced_3d_index_lines_range.start
        + hemisphere_index_count as usize;
    let hemisphere_per_instance_3d_vertex_range = 0..0; // empty

    // sphere: defined to use part of the capsule mesh indices except for the
    // extra equator lines and cylinder lines
    let (_, sphere_index_count)
      = mesh::sphere_3d_instanced_lines_list_counts (
          SPHERE_LATITUDE_DIVS, LONGITUDE_DIVS);
    let sphere_instanced_3d_index_lines_range =
      capsule_instanced_3d_index_lines_range.start..
      capsule_instanced_3d_index_lines_range.start
        + sphere_index_count as usize;
    let sphere_per_instance_3d_vertex_range = 0..0; // empty

    // cylinder
    let (mut cylinder_vertex_data, mut cylinder_index_data)
      = mesh::cylinder_3d_instanced_lines_list (index_offset, CYLINDER_DIVS);
    let cylinder_instanced_3d_index_lines_range
      = index_range_start..index_range_start + cylinder_index_data.len();
    let cylinder_per_instance_3d_vertex_range = 0..0; // empty
    instanced_3d_vertex_data.append (&mut cylinder_vertex_data);
    instanced_3d_index_data.append  (&mut cylinder_index_data);

    //index_offset      = instanced_3d_vertex_data.len() as u32;
    //index_range_start = instanced_3d_index_data.len();

    debug_assert_eq!(instanced_3d_vertex_data.len(), vertex_count as usize);
    debug_assert_eq!(instanced_3d_index_data.len(), index_count as usize);

    // collect instanced vertices and indices
    let instanced_3d_vertices = glium::VertexBuffer::dynamic (
      glium_display, instanced_3d_vertex_data.as_slice()
    ).unwrap();
    let instanced_3d_indices_lines = glium::IndexBuffer::dynamic (
      glium_display,
      glium::index::PrimitiveType::LinesList,
      instanced_3d_index_data.as_slice()
    ).unwrap();

    // aabb
    let aabb_per_instance_3d_vertex_range = 0..0; // empty

    // per instance
    let per_instance_3d_vertices = glium::VertexBuffer::dynamic (
      glium_display,
      &[
        // origin
        vertex::Vert3dOrientationScaleColor {
          position:    [0.0, 0.0, 0.0],
          orientation: cgmath::Matrix3::identity().into(),
          scale:       [1.0, 1.0, 1.0],
          color:       color::rgba_u8_to_rgba_f32 (&color::DEBUG_CHARTREUSE)
        }
      ]
    ).unwrap();

    DefaultResource {
      shader_programs,
      textures_16x16,
      sprite_16x16_vertices,
      tileset_textures_128x128,
      tile_vertices,
      viewport_tile_data,
      viewport_line_loop_vertices,

      instanced_3d_vertices,
      instanced_3d_indices_lines,
      per_instance_3d_vertices,

      grid_instanced_3d_index_lines_range,
      grid_per_instance_3d_vertex_range,
      hemisphere_instanced_3d_index_lines_range,
      hemisphere_per_instance_3d_vertex_range,
      sphere_instanced_3d_index_lines_range,
      sphere_per_instance_3d_vertex_range,
      capsule_instanced_3d_index_lines_range,
      capsule_per_instance_3d_vertex_range,
      cylinder_instanced_3d_index_lines_range,
      cylinder_per_instance_3d_vertex_range,
      aabb_per_instance_3d_vertex_range,

      capsule_vertex_id_offset,
      hemisphere_vertex_count
    }
  }

  fn init (render : &mut Render <Self>) {
    render.update_viewport_line_loops();
  }

  fn draw_2d (render : &Render <Self>, glium_frame : &mut glium::Frame) {
    use glium::Surface;

    // draw each viewport 2d
    for (i, viewport) in render.viewports.iter() {
      let tile_data = render.resource.viewport_tile_data.get (i)
        .unwrap_or (&VIEWPORT_TILE_DATA_DEFAULT);
      let pixel_size_2d = 1.0 / viewport.camera2d.zoom;

      // draw parameters
      let draw_parameters_viewport = glium::DrawParameters {
        viewport: Some (viewport.rect),
        .. Default::default()
      };
      let draw_parameters_blend_invert = glium::DrawParameters {
        //blend: params::BLEND_FUNC_NORMAL,
        // NOTE: inverse blending does not really have an effect when rendering
        // with 'Nearest' magnify filter below
        blend: params::BLEND_FUNC_INVERT_COLOR,
        .. draw_parameters_viewport.clone()
      };

      // uniforms
      let (transform_mat_world_to_view, projection_mat_ortho) =
        viewport.camera2d.view_ortho_mats();
      let uniforms = uniform!{
        uni_tile_space_origin:    [
          viewport.camera2d.ortho.left + pixel_size_2d * tile_data.margin_px_left as f32,
          viewport.camera2d.ortho.top  - pixel_size_2d * tile_data.margin_px_top  as f32
        ],
        uni_transform_mat_view:   *transform_mat_world_to_view,
        uni_projection_mat_ortho: *projection_mat_ortho,
        uni_color:                color::rgba_u8_to_rgba_f32 (&color::DEBUG_GREY),
        uni_sampler2darray:         render.resource.textures_16x16.sampled()
          .magnify_filter (glium::uniforms::MagnifySamplerFilter::Nearest),
        uni_sampler2darray_tileset: render.resource.tileset_textures_128x128
          .sampled()
          .magnify_filter (glium::uniforms::MagnifySamplerFilter::Nearest)
      };

      if let Some (tile_data) = render.resource.viewport_tile_data.get (i) {
        // draw tiles
        glium_frame.draw (
          render.resource.tile_vertices.slice (tile_data.vertex_range.clone())
            .unwrap(),
          glium::index::IndicesSource::NoIndices {
            primitives: glium::index::PrimitiveType::Points
          },
          &render.resource.shader_programs [
            shader::ProgramId::WorldSpace2dTile as usize],
          &uniforms,
          &draw_parameters_blend_invert
        ).unwrap();
      }

      // draw crosshair
      glium_frame.draw (
        render.resource.sprite_16x16_vertices.slice (
          (CROSSHAIR_SPRITE_16X16_VERTEX_INDEX as usize)..
          (CROSSHAIR_SPRITE_16X16_VERTEX_INDEX as usize + 1)
        ).unwrap(),
        glium::index::IndicesSource::NoIndices {
          primitives: glium::index::PrimitiveType::Points
        },
        &render.resource.shader_programs [
          shader::ProgramId::WorldSpace2dSprite as usize],
        &uniforms,
        &draw_parameters_blend_invert
      ).unwrap();

      // draw viewport line loop
      let base_index = i * 4;
      glium_frame.draw (
        render.resource.viewport_line_loop_vertices
          .slice (base_index..(base_index + 4)).unwrap(),
        glium::index::IndicesSource::NoIndices {
          primitives: glium::index::PrimitiveType::LineLoop
        },
        &render.resource.shader_programs [
          shader::ProgramId::WorldSpace2dUniColor as usize],
        &uniforms,
        &draw_parameters_viewport
      ).unwrap();
    } // end loop over viewports
  }

  fn draw_3d (render : &Render <Self>, glium_frame : &mut glium::Frame) {
    // draw each viewport 3d
    for (_, viewport) in render.viewports.iter() {
      use glium::Surface;
      // draw parameters: viewport
      let draw_parameters_viewport = glium::DrawParameters {
        viewport: Some (viewport.rect),
        .. Default::default()
      };
      // draw parameters: depth test
      let draw_parameters_write_depth = glium::DrawParameters {
        depth: glium::Depth {
          test:  glium::DepthTest::IfLess,
          write: true,
          .. Default::default()
        },
        .. draw_parameters_viewport
      };
      // uniforms
      let (transform_mat_world_to_view, projection_mat_perspective) =
        viewport.camera3d.view_mats();
      let uniforms = uniform!{
        uni_transform_mat_view:         *transform_mat_world_to_view,
        uni_projection_mat_perspective: *projection_mat_perspective,
        uni_capsule_vertex_id_offset:   render.resource.capsule_vertex_id_offset,
        uni_hemisphere_vertex_count:    render.resource.hemisphere_vertex_count
      };

      // draw debug grids
      glium_frame.draw (
        (&render.resource.instanced_3d_vertices,
          render.resource.per_instance_3d_vertices.slice (
            render.resource.grid_per_instance_3d_vertex_range.clone()
          ).unwrap().per_instance().unwrap()
        ),
        render.resource.instanced_3d_indices_lines.slice (
          render.resource.grid_instanced_3d_index_lines_range.clone()
        ).unwrap(),
        &render.resource.shader_programs [
          shader::ProgramId::ModelSpace3dInstancedOrientationScaleColor as usize
        ],
        &uniforms,
        &draw_parameters_write_depth
      ).unwrap();

      // draw hemispheres
      glium_frame.draw (
        (&render.resource.instanced_3d_vertices,
          render.resource.per_instance_3d_vertices.slice (
            render.resource.hemisphere_per_instance_3d_vertex_range.clone()
          ).unwrap().per_instance().unwrap()
        ),
        render.resource.instanced_3d_indices_lines.slice (
          render.resource.hemisphere_instanced_3d_index_lines_range.clone()
        ).unwrap(),
        &render.resource.shader_programs [
          shader::ProgramId::ModelSpace3dInstancedScaleColor as usize
        ],
        &uniforms,
        &draw_parameters_write_depth
      ).unwrap();

      // draw spheres
      glium_frame.draw (
        (&render.resource.instanced_3d_vertices,
          render.resource.per_instance_3d_vertices.slice (
            render.resource.sphere_per_instance_3d_vertex_range.clone()
          ).unwrap().per_instance().unwrap()
        ),
        render.resource.instanced_3d_indices_lines.slice (
          render.resource.sphere_instanced_3d_index_lines_range.clone()
        ).unwrap(),
        &render.resource.shader_programs [
          shader::ProgramId::ModelSpace3dInstancedScaleColor as usize
        ],
        &uniforms,
        &draw_parameters_write_depth
      ).unwrap();

      // draw capsules
      glium_frame.draw (
        (&render.resource.instanced_3d_vertices,
          render.resource.per_instance_3d_vertices.slice (
            render.resource.capsule_per_instance_3d_vertex_range.clone()
          ).unwrap().per_instance().unwrap()
        ),
        render.resource.instanced_3d_indices_lines.slice (
          render.resource.capsule_instanced_3d_index_lines_range.clone()
        ).unwrap(),
        &render.resource.shader_programs [
          shader::ProgramId::ModelSpace3dInstancedCapsule as usize
        ],
        &uniforms,
        &draw_parameters_write_depth
      ).unwrap();

      // draw cylinders
      glium_frame.draw (
        (&render.resource.instanced_3d_vertices,
          render.resource.per_instance_3d_vertices.slice (
            render.resource.cylinder_per_instance_3d_vertex_range.clone()
          ).unwrap().per_instance().unwrap()
        ),
        render.resource.instanced_3d_indices_lines.slice (
          render.resource.cylinder_instanced_3d_index_lines_range.clone()
        ).unwrap(),
        &render.resource.shader_programs [
          shader::ProgramId::ModelSpace3dInstancedScaleColor as usize
        ],
        &uniforms,
        &draw_parameters_write_depth
      ).unwrap();

      // draw aabbs
      glium_frame.draw (
        render.resource.per_instance_3d_vertices.slice (
          render.resource.aabb_per_instance_3d_vertex_range.clone()
        ).unwrap(),
        glium::index::IndicesSource::NoIndices {
          primitives: glium::index::PrimitiveType::Points
        },
        &render.resource.shader_programs [
          shader::ProgramId::WorldSpace3dAabb as usize
        ],
        &uniforms,
        &draw_parameters_write_depth
      ).unwrap();

    } // end loop over viewports
  } // end fn draw_3d
} // end impl Resource for DefaultResource

impl Render <DefaultResource> {

  #[inline]
  pub fn camera3d_position_set (&mut self, position : &cgmath::Point3 <f32>) {
    for (_, viewport) in self.viewports.iter_mut() {
      viewport.camera3d.set_position (position);
    }
  }

  pub fn camera3d_move_local_xy (&mut self, dx : f32, dy : f32, dz : f32) {
    self.viewports[MAIN_VIEWPORT].camera3d.move_local_xy (dx, dy, dz);
    let position = self.viewports[MAIN_VIEWPORT].camera3d.position;
    for (_, viewport) in self.viewports.iter_mut().skip (1) {
      viewport.camera3d.set_position (&position);
    }
  }

  #[inline]
  pub fn camera3d_rotate (&mut self,
    dyaw : cgmath::Rad <f32>, dpitch : cgmath::Rad <f32>
  ) {
    self.viewports[MAIN_VIEWPORT].camera3d.rotate (dyaw, dpitch);
  }

  /// Scales 3D zoom of viewports 1-3.
  ///
  /// Does nothing in single viewport mode.
  ///
  /// # Panics
  ///
  /// Panics if scale is negative.
  pub fn camera3d_orthographic_zoom_scale (&mut self, scale : f32) {
    assert!(0.0 < scale);
    for (_, viewport) in self.viewports.iter_mut().skip(1) {
      debug_assert!(viewport.camera3d.projection3d.is_orthographic());
      viewport.camera3d.projection3d.scale_fovy_or_zoom (scale);
    }
  }

  /// Scales 3D zoom of viewport 0 (the main viewport) only.
  ///
  /// # Panics
  ///
  /// Panics if scale is negative.
  pub fn camera3d_perspective_fovy_scale (&mut self, scale : f32) {
    assert!(0.0 < scale);
    debug_assert!(self.viewports[MAIN_VIEWPORT].camera3d.projection3d
      .is_perspective());
    self.viewports[MAIN_VIEWPORT].camera3d.projection3d
      .scale_fovy_or_zoom (scale);
  }

  pub fn camera2d_zoom_set (&mut self, zoom : f32) {
    assert!(0.0 < zoom);
    for (_, viewport) in self.viewports.iter_mut() {
      viewport.camera2d.set_zoom (zoom);
    }
    self.update_viewport_line_loops();
  }

  /// Modifies the 2D zoom by the given amount for all viewports.
  pub fn camera2d_zoom_shift (&mut self, shift : f32) {
    let mut dirty = false;
    for (_, viewport) in self.viewports.iter_mut() {
      let zoom = viewport.camera2d.zoom + shift;
      if 0.0 < zoom {
        viewport.camera2d.set_zoom (zoom);
        dirty = true;
      }
    }
    if dirty {
      self.update_viewport_line_loops();
    }
  }

  pub fn window_resized (&mut self, width : u32, height : u32) {
    if self.viewports.len() == 1 {
      // single viewport
      self.viewports[MAIN_VIEWPORT].set_rect (
        glium::Rect { left: 0, bottom: 0, width, height }
      );
    } else {
      // quad viewports
      let left_width    = left_width   (width);
      let right_width   = right_width  (width);
      let upper_height  = upper_height (height);
      let lower_height  = lower_height (height);
      self.viewports[LOWER_RIGHT_VIEWPORT].set_rect (
        glium::Rect {
          width:  right_width,
          height: lower_height,
          left:   left_width,
          bottom: 0
        }
      );
      self.viewports[UPPER_LEFT_VIEWPORT].set_rect (
        glium::Rect {
          width:  left_width,
          height: upper_height,
          left:   0,
          bottom: lower_height
        }
      );
      self.viewports[UPPER_RIGHT_VIEWPORT].set_rect (
        glium::Rect {
          width:  right_width,
          height: upper_height,
          left:   left_width,
          bottom: lower_height
        }
      );
      self.viewports[LOWER_LEFT_VIEWPORT].set_rect (
        glium::Rect {
          width:  left_width,
          height: lower_height,
          left:   0,
          bottom: 0
        }
      );
    }
    self.update_viewport_line_loops();
  }

  /// Initializes "demo" state such as example mesh instances and viewport text
  /// tiles.
  ///
  /// This should normally be called immediately after render context creation
  /// as some assumptions are made about the current state (see Panics below).
  /// The renderer can be returned to this state with the `reset` method.
  ///
  /// After `demo_init`, `demo_handle_glutin_event` can be called on incoming
  /// events to interact with the demo.
  ///
  /// A usage example is provided in `./examples/demo.rs`.
  ///
  /// # Panics
  ///
  /// A prerequisite is that the first four `viewport_tile_data` entries are
  /// empty.
  ///
  /// The currently allocated per-instance buffers should be empty.
  // TODO: doctests, make safe to call from any state?
  pub fn demo_init (&mut self) {
    use cgmath::{Rotation3, SquareMatrix};
    use std::f32::consts::FRAC_PI_2;

    println!(">>> Initializing demo...");
    println!("  Press 'Q' or 'Esc' to quit");
    println!("  Horizontal movement: 'W', 'A', 'S', 'D'");
    println!("  Vertical movement: 'Space', 'LCtrl' or 'R', 'F'");
    println!("  Rotation: 'Up', 'Down', 'Left', 'Right' or 'H', 'J', 'K', 'L'");
    println!("  Zoom in/out 3D (perspective): 'I', 'O'");
    println!("  Zoom in/out 3D (orthographic): 'Alt+I', 'Alt+O'");
    println!("  Zoom in/out 2D: 'Shift+Alt+I', 'Shift+Alt+O'");
    println!("  Toggle split into 4 viewports with orthographic views: 'X'");

    //
    // set per-instance data
    //
    let mut per_instance_data = Vec::new();

    // start grid data
    let half_grid_dims = 0.5 * MESH_3D_GRID_DIMS as f32;
    self.resource.grid_per_instance_3d_vertex_range.start
      = per_instance_data.len();
    // Z plane
    per_instance_data.push (vertex::Vert3dOrientationScaleColor {
      position:    [0.0, 0.0, 0.0],
      orientation: cgmath::Matrix3::identity().into(),
      scale:       [1.0, 1.0, 1.0],
      color:       color::rgba_u8_to_rgba_f32 (&[0, 0, 255, 255])
    });
    // Y plane
    per_instance_data.push (vertex::Vert3dOrientationScaleColor {
      position:    [0.0, half_grid_dims, half_grid_dims],
      orientation: (*cgmath::Basis3::from_angle_x (cgmath::Rad (FRAC_PI_2))
        .as_ref()).into(),
      scale:       [1.0, 1.0, 1.0],
      color:       color::rgba_u8_to_rgba_f32 (&[0, 255, 0, 255])
    });
    // X plane
    per_instance_data.push (vertex::Vert3dOrientationScaleColor {
      position:    [half_grid_dims, 0.0, half_grid_dims],
      orientation: (*cgmath::Basis3::from_angle_y (cgmath::Rad (FRAC_PI_2))
        .as_ref()).into(),
      scale:       [1.0, 1.0, 1.0],
      color:       color::rgba_u8_to_rgba_f32 (&[255, 0, 0, 255])
    });
    // end grid data
    self.resource.grid_per_instance_3d_vertex_range.end
      = per_instance_data.len();

    // start sphere data
    self.resource.sphere_per_instance_3d_vertex_range.start
      = per_instance_data.len();
    // sphere: 1.0 diameter
    per_instance_data.push (vertex::Vert3dOrientationScaleColor {
      position:    [1.5, 2.5, 0.5],
      orientation: cgmath::Matrix3::identity().into(),
      scale:       [0.5, 0.5, 0.5],
      color:       color::rgba_u8_to_rgba_f32 (&color::DEBUG_RED)
    });
    // end sphere data
    self.resource.sphere_per_instance_3d_vertex_range.end
      = per_instance_data.len();

    // start hemisphere data
    self.resource.hemisphere_per_instance_3d_vertex_range.start
      = per_instance_data.len();
    // hemisphere
    per_instance_data.push (vertex::Vert3dOrientationScaleColor {
      position:    [2.5, 2.5, 0.0],
      orientation: cgmath::Matrix3::identity().into(),
      scale:       [0.5, 0.5, 0.5],
      color:       color::rgba_u8_to_rgba_f32 (&color::DEBUG_VIOLET)
    });
    // end hemisphere data
    self.resource.hemisphere_per_instance_3d_vertex_range.end
      = per_instance_data.len();

    // start capsule data
    self.resource.capsule_per_instance_3d_vertex_range.start
      = per_instance_data.len();
    // capsule
    per_instance_data.push (vertex::Vert3dOrientationScaleColor {
      position:    [0.5, 2.5, 1.0],
      orientation: cgmath::Matrix3::identity().into(),
      scale:       [0.5, 0.5, 1.0],
      color:       color::rgba_u8_to_rgba_f32 (&color::DEBUG_AZURE)
    });
    // end capsule data
    self.resource.capsule_per_instance_3d_vertex_range.end
      = per_instance_data.len();

    // start cylinder data
    self.resource.cylinder_per_instance_3d_vertex_range.start
      = per_instance_data.len();
    // cylinder
    per_instance_data.push (vertex::Vert3dOrientationScaleColor {
      position:    [3.5, 2.5, 1.0],
      orientation: cgmath::Matrix3::identity().into(),
      scale:       [0.5, 0.5, 1.0],
      color:       color::rgba_u8_to_rgba_f32 (&color::DEBUG_LIGHT_BLUE)
    });
    // end cylinder data
    self.resource.cylinder_per_instance_3d_vertex_range.end
      = per_instance_data.len();

    // start aabb data
    self.resource.aabb_per_instance_3d_vertex_range.start
      = per_instance_data.len();
    // aabb
    per_instance_data.push (vertex::Vert3dOrientationScaleColor {
      position:    [-0.5, 2.5, 1.0],
      orientation: cgmath::Matrix3::identity().into(),
      scale:       [0.5, 0.5, 1.0],
      color:       color::rgba_u8_to_rgba_f32 (&color::DEBUG_PINK)
    });
    // end aabb data
    self.resource.aabb_per_instance_3d_vertex_range.end
      = per_instance_data.len();

    // create per instance vertex buffer
    self.resource.per_instance_3d_vertices = glium::VertexBuffer::dynamic (
      &self.glium_display, per_instance_data.as_slice()).unwrap();

    // add some text tiles
    // TODO: better interface
    self.resource.tile_vertices = glium::VertexBuffer::dynamic (
      &self.glium_display, &[
        vertex::Vert2dTile { row: 0, column:  0, tile: 'V' as u8 },
        vertex::Vert2dTile { row: 0, column:  1, tile: 'i' as u8 },
        vertex::Vert2dTile { row: 0, column:  2, tile: 'e' as u8 },
        vertex::Vert2dTile { row: 0, column:  3, tile: 'w' as u8 },
        vertex::Vert2dTile { row: 0, column:  4, tile: 'p' as u8 },
        vertex::Vert2dTile { row: 0, column:  5, tile: 'o' as u8 },
        vertex::Vert2dTile { row: 0, column:  6, tile: 'r' as u8 },
        vertex::Vert2dTile { row: 0, column:  7, tile: 't' as u8 },
        vertex::Vert2dTile { row: 0, column:  8, tile: '0' as u8 },

        vertex::Vert2dTile { row: 0, column:  0, tile: 'V' as u8 },
        vertex::Vert2dTile { row: 0, column:  1, tile: 'i' as u8 },
        vertex::Vert2dTile { row: 0, column:  2, tile: 'e' as u8 },
        vertex::Vert2dTile { row: 0, column:  3, tile: 'w' as u8 },
        vertex::Vert2dTile { row: 0, column:  4, tile: 'p' as u8 },
        vertex::Vert2dTile { row: 0, column:  5, tile: 'o' as u8 },
        vertex::Vert2dTile { row: 0, column:  6, tile: 'r' as u8 },
        vertex::Vert2dTile { row: 0, column:  7, tile: 't' as u8 },
        vertex::Vert2dTile { row: 0, column:  8, tile: '1' as u8 },
        vertex::Vert2dTile { row: 0, column:  9, tile: ':' as u8 },
        vertex::Vert2dTile { row: 0, column: 10, tile: ' ' as u8 },
        vertex::Vert2dTile { row: 0, column: 11, tile: '+' as u8 },
        vertex::Vert2dTile { row: 0, column: 12, tile: 'Y' as u8 },

        vertex::Vert2dTile { row: 0, column:  0, tile: 'V' as u8 },
        vertex::Vert2dTile { row: 0, column:  1, tile: 'i' as u8 },
        vertex::Vert2dTile { row: 0, column:  2, tile: 'e' as u8 },
        vertex::Vert2dTile { row: 0, column:  3, tile: 'w' as u8 },
        vertex::Vert2dTile { row: 0, column:  4, tile: 'p' as u8 },
        vertex::Vert2dTile { row: 0, column:  5, tile: 'o' as u8 },
        vertex::Vert2dTile { row: 0, column:  6, tile: 'r' as u8 },
        vertex::Vert2dTile { row: 0, column:  7, tile: 't' as u8 },
        vertex::Vert2dTile { row: 0, column:  8, tile: '2' as u8 },
        vertex::Vert2dTile { row: 0, column:  9, tile: ':' as u8 },
        vertex::Vert2dTile { row: 0, column: 10, tile: ' ' as u8 },
        vertex::Vert2dTile { row: 0, column: 11, tile: '+' as u8 },
        vertex::Vert2dTile { row: 0, column: 12, tile: 'X' as u8 },

        vertex::Vert2dTile { row: 0, column:  0, tile: 'V' as u8 },
        vertex::Vert2dTile { row: 0, column:  1, tile: 'i' as u8 },
        vertex::Vert2dTile { row: 0, column:  2, tile: 'e' as u8 },
        vertex::Vert2dTile { row: 0, column:  3, tile: 'w' as u8 },
        vertex::Vert2dTile { row: 0, column:  4, tile: 'p' as u8 },
        vertex::Vert2dTile { row: 0, column:  5, tile: 'o' as u8 },
        vertex::Vert2dTile { row: 0, column:  6, tile: 'r' as u8 },
        vertex::Vert2dTile { row: 0, column:  7, tile: 't' as u8 },
        vertex::Vert2dTile { row: 0, column:  8, tile: '3' as u8 },
        vertex::Vert2dTile { row: 0, column:  9, tile: ':' as u8 },
        vertex::Vert2dTile { row: 0, column: 10, tile: ' ' as u8 },
        vertex::Vert2dTile { row: 0, column: 11, tile: '-' as u8 },
        vertex::Vert2dTile { row: 0, column: 12, tile: 'Z' as u8 },
      ]
    ).unwrap();
    assert!(self.resource.viewport_tile_data.insert (
      MAIN_VIEWPORT,
      render::resource::ViewportTileData {
        margin_px_left: 2,
        margin_px_top:  2,
        vertex_range:   0..9
      }
    ).is_none());
    assert!(self.resource.viewport_tile_data.insert (
      UPPER_LEFT_VIEWPORT,
      render::resource::ViewportTileData {
        margin_px_left: 2,
        margin_px_top:  2,
        vertex_range:   9..22
      }
    ).is_none());
    assert!(self.resource.viewport_tile_data.insert (
      UPPER_RIGHT_VIEWPORT,
      render::resource::ViewportTileData {
        margin_px_left: 2,
        margin_px_top:  2,
        vertex_range:   22..35
      }
    ).is_none());
    assert!(self.resource.viewport_tile_data.insert (
      LOWER_LEFT_VIEWPORT,
      render::resource::ViewportTileData {
        margin_px_left: 2,
        margin_px_top:  2,
        vertex_range:   35..48
      }
    ).is_none());
  }

  pub fn demo_handle_glutin_event (&mut self,
    running : &mut bool, event : glutin::Event
  ) {
    // glutin events:
    // - window events includes input events received by the window
    // - device events are received independent of window focus
    // there may be differences in the events received depending on platform:
    // - on Linux keyboard input is received as both a device and window event
    // - on Windows only mouse motion device events are received, all other
    //   input is received as window events
    // here we just handle input contained in window events
    match event {
      glutin::Event::WindowEvent { event, .. } => {
        //println!("window event: {:?}", event);
        match event {
          // window resized event
          glutin::WindowEvent::Resized (width, height) => {
            info!("window event: {:?}", event);
            self.window_resized (width, height);
          }
          // window closed event
          glutin::WindowEvent::Closed => { *running = false; }
          // keyboard input pressed event
          glutin::WindowEvent::KeyboardInput {
            input: glutin::KeyboardInput {
              state: glutin::ElementState::Pressed,
              virtual_keycode, scancode, modifiers,
              ..
            },
            ..
          } => {
            // handle virtual keycodes
            if let Some (virtual_keycode) = virtual_keycode {
              use cgmath::Zero;
              match virtual_keycode {
                // quit
                glutin::VirtualKeyCode::Q | glutin::VirtualKeyCode::Escape
                  => { *running = false; }
                // choose a frame function 0-9
                glutin::VirtualKeyCode::Key1 => {
                  self.frame_fun
                    = render::frame_fun_default::<render::DefaultResource>;
                }
                // TODO: more frame functions
                // TODO: cycle between frame functions
                //glutin::VirtualKeyCode::Tab => { }
                glutin::VirtualKeyCode::W => {
                  self.camera3d_move_local_xy (0.0, 1.0, 0.0);
                }
                glutin::VirtualKeyCode::S => {
                  self.camera3d_move_local_xy (0.0, -1.0, 0.0);
                }
                glutin::VirtualKeyCode::D => {
                  self.camera3d_move_local_xy (1.0, 0.0, 0.0);
                }
                glutin::VirtualKeyCode::A => {
                  self.camera3d_move_local_xy (-1.0, 0.0, 0.0);
                }
                glutin::VirtualKeyCode::Space | glutin::VirtualKeyCode::R => {
                  self.camera3d_move_local_xy (0.0, 0.0, 1.0);
                }
                glutin::VirtualKeyCode::LControl |
                glutin::VirtualKeyCode::F        => {
                  self.camera3d_move_local_xy (0.0, 0.0, -1.0);
                }
                glutin::VirtualKeyCode::J | glutin::VirtualKeyCode::Down => {
                  use std::f32::consts::PI;
                  self.camera3d_rotate (
                    cgmath::Rad::zero(), cgmath::Rad (-PI / 12.0));
                }
                glutin::VirtualKeyCode::K | glutin::VirtualKeyCode::Up => {
                  use std::f32::consts::PI;
                  self.camera3d_rotate (
                    cgmath::Rad::zero(), cgmath::Rad (PI / 12.0));
                }
                glutin::VirtualKeyCode::H | glutin::VirtualKeyCode::Left => {
                  use std::f32::consts::PI;
                  self.camera3d_rotate (
                    cgmath::Rad (PI / 12.0), cgmath::Rad::zero());
                  //self.camera2d.rotate (cgmath::Rad (PI / 12.0));
                }
                glutin::VirtualKeyCode::L | glutin::VirtualKeyCode::Right => {
                  use std::f32::consts::PI;
                  self.camera3d_rotate (
                    cgmath::Rad (-PI / 12.0), cgmath::Rad::zero());
                  //self.camera2d.rotate (cgmath::Rad (-PI / 12.0));
                }
                glutin::VirtualKeyCode::I => {
                  if modifiers.alt && modifiers.shift {
                    self.camera2d_zoom_shift (1.0);
                  } else if modifiers.alt {
                    self.camera3d_orthographic_zoom_scale (1.1);
                  } else {
                    self.camera3d_perspective_fovy_scale (1.0 / 1.1);
                  }
                }
                glutin::VirtualKeyCode::O => {
                  if modifiers.alt  && modifiers.shift {
                    self.camera2d_zoom_shift (-1.0);
                  } else if modifiers.alt {
                    self.camera3d_orthographic_zoom_scale (1.0 / 1.1);
                  } else {
                    self.camera3d_perspective_fovy_scale (1.1);
                  }
                }
                // toggle 4-viewport mode
                glutin::VirtualKeyCode::X => {
                  self.demo_toggle_quad_viewports();
                }
                // end camera controls
                _ => {}
              }
            // handle scancodes
            } else if scancode == 99 { // Printscreen
              self.screenshot();
            }
          } // end keyboard input
          _ => {}
        }
      } // end window event
      // unhandled: device events and others
      _ => {}
    } // end match event
  }

  /// Switch between single (perspective) and quad viewport modes (perspective
  /// + three ortho viewports).
  ///
  /// Generally should be called from a render context that was initialized
  /// with `demo_init`.
  ///
  /// # Panics
  ///
  /// If there is a single viewport it must be `MAIN_VIEWPORT`.
  ///
  /// If there are multiple viewports, they must be exactly the first
  /// four viewports only.
  // TODO: doctests, make safe to call from any state?
  pub fn demo_toggle_quad_viewports (&mut self) {
    if self.viewports.len() == 1 {
      // switch to four viewports from single viewport
      // main viewport becomes "lower right"
      let (left_width, right_width, upper_height, lower_height,
        position, zoom_2d
      ) = {
        let lower_right
          = &mut self.viewports[MAIN_VIEWPORT];
        let window_width  = lower_right.rect.width;
        let window_height = lower_right.rect.height;
        let left_width    = left_width   (window_width);
        let right_width   = right_width  (window_width);
        let upper_height  = upper_height (window_height);
        let lower_height  = lower_height (window_height);
        lower_right.set_rect (glium::Rect {
          width:  right_width,
          height: lower_height,
          left:   left_width,
          bottom: 0
        });
        ( left_width, right_width, upper_height, lower_height,
          lower_right.camera3d.position, lower_right.camera2d.zoom
        )
      };

      let upper_left  = render::viewport::Builder::new (glium::Rect {
        width:  left_width,
        height: upper_height,
        left:   0,
        bottom: lower_height
      }).with_zoom_2d (zoom_2d).orthographic_3d (1.0).with_pose_3d (
        graphics::Pose3d {
          position,
          // looking down positive Y axis
          yaw:   cgmath::Rad (0.0),
          pitch: cgmath::Rad (0.0)
        }
      ).build();

      let upper_right = render::viewport::Builder::new (glium::Rect {
        width:  right_width,
        height: upper_height,
        left:   left_width,
        bottom: lower_height,
      }).with_zoom_2d (zoom_2d).orthographic_3d (1.0).with_pose_3d (
        graphics::Pose3d {
          position,
          // looking down positive X axis
          yaw:   cgmath::Deg (-90.0).into(),
          pitch: cgmath::Rad (0.0)
        }
      ).build();

      let lower_left  = render::viewport::Builder::new (glium::Rect {
        width:  left_width,
        height: lower_height,
        left:   0,
        bottom: 0,
      }).with_zoom_2d (zoom_2d).orthographic_3d (1.0).with_pose_3d (
        graphics::Pose3d {
          position,
          // looking down negative Z axis
          yaw:   cgmath::Rad (0.0),
          pitch: cgmath::Deg (-90.0).into()
        }
      ).build();

      assert!(self.viewports.insert (UPPER_LEFT_VIEWPORT, upper_left)
        .is_none());
      assert!(self.viewports.insert (UPPER_RIGHT_VIEWPORT, upper_right)
        .is_none());
      assert!(self.viewports.insert (LOWER_LEFT_VIEWPORT, lower_left)
        .is_none());
    } else {
      // switch to single viewport from four viewports
      assert_eq!(self.viewports.len(), 4);
      assert!(self.viewports.remove (UPPER_LEFT_VIEWPORT) .is_some());
      assert!(self.viewports.remove (UPPER_RIGHT_VIEWPORT).is_some());
      assert!(self.viewports.remove (LOWER_LEFT_VIEWPORT) .is_some());
      let main_viewport = &mut self.viewports[MAIN_VIEWPORT];
      let (width, height)
        = self.glium_display.gl_window().get_inner_size().unwrap();
      main_viewport.set_rect (glium::Rect {
        width,
        height,
        left:   0,
        bottom: 0
      });
    }
    self.update_viewport_line_loops();
  } // end fn toggle_quad_viewports

  /// Updates vertex and index buffers for viewport line loops.
  ///
  /// Should be called whenever viewport sizes or 2D camera zoom changes.
  fn update_viewport_line_loops (&mut self) {
    const VERTS_PER_VIEWPORT : usize = 4;
    let num_vertices = VERTS_PER_VIEWPORT * self.viewports.len();
    let vertices = {
      let mut vertices = Vec::<vertex::Vert2d>::with_capacity (num_vertices);
      for (_, viewport) in self.viewports.iter() {
        // pixels are centered on 0.5 unit centers
        let pixel_radius = 0.5 / viewport.camera2d.zoom;
        let ortho        = &viewport.camera2d.ortho;
        vertices.append (&mut vec![
          vertex::Vert2d {
            position: [ortho.left  + pixel_radius, ortho.bottom + pixel_radius] },
          vertex::Vert2d {
            position: [ortho.left  + pixel_radius, ortho.top    - pixel_radius] },
          vertex::Vert2d {
            position: [ortho.right - pixel_radius, ortho.top    - pixel_radius] },
          vertex::Vert2d {
            position: [ortho.right - pixel_radius, ortho.bottom + pixel_radius] }
        ]);
      }
      vertices
    };
    self.resource.viewport_line_loop_vertices =
      glium::VertexBuffer::dynamic (
        &self.glium_display,
        &vertices.as_slice()
      ).unwrap();
  }
}

impl Default for ViewportTileData {
  fn default() -> Self {
    ViewportTileData {
      vertex_range:   0..0, // empty range
      margin_px_left: 0,
      margin_px_top:  0
    }
  }
}

//
//  private functions
//

// some functions to compute viewport widths for odd window dimensions:
// right viewports will be 1 pixel wider on odd width windows and bottom
// viewports will be 1 pixel taller on odd height windows

#[inline]
fn left_width (window_width : u32) -> u32 {
  window_width / 2
}
#[inline]
fn right_width (window_width : u32) -> u32 {
  window_width / 2 + window_width % 2
}
#[inline]
fn upper_height (window_height : u32) -> u32 {
  window_height / 2
}
#[inline]
fn lower_height (window_height : u32) -> u32 {
  window_height / 2 + window_height % 2
}