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

use graphics::{self, Mesh, PrimitiveType, CoordinateOrigin, path::LineCap};
use color::ToRgba;
use glin::{Context,Program,SimpleVao,texture,fbo,buffer_object,cubemap,program,vao,simple_vao};
use ::Material;
use gl;
use na::*;
use std::f32;
use math::*;
use window;
//use video;
//use video::Video;
use std::cell::{RefCell, UnsafeCell};
use std::rc::Rc;
use std::ops::Deref;
use std::path::Path;
use ::traits::ToSimpleVao;
use shadow_mapping;
use ttf;
use vao_mesh;
use autoload;
use util;
use BasicMaterial;
use densevec::DenseVec;
use pbr_material;
use skybox;
use image_based_light;
use vao_path;
// use offscreen_buffer::*;
use glin::RenderSurface;

use glin::{self, Result, VertexFormat};
use glin::CreationContext as GlinCreationContext;
use std::collections::{HashMap, hash_map::Entry};
use std::any::{TypeId, Any};
use object;

thread_local!(static NEXT_ID: RefCell<usize> = RefCell::new(0));

pub struct RendererData{
    vaos_cache: UnsafeCell<HashMap<TypeId, Box<Any>>>,
    material_thick_lines: ::ShaderMaterial,
    bitmap_font: ::BitmapFont,
    resolution_factor: f32,
    id: usize,
    uniforms_cache: RefCell<DenseVec<graphics::mvp::UniformsLocationCache>>,
}

#[must_use = "Calling with on a renderer doesn't change that renderer, it returns a new one with the properties applied. Instead of calling `gl.with(...)` do `let gl = gl.with(...)`"]
pub struct Renderer<'c, R: RenderSurface + 'c = glin::Screen>{
    data: Rc<RendererData>,
    context: Context<'c, R>,
    mvp: graphics::Mvp,
    properties: Vec<glin::Property>,
}

impl<'c> Renderer<'c>{
    pub fn new<'w, W: window::WindowT + glin::GlWindow>(window: &'w mut W) -> Result<Renderer<'static>>{
        Renderer::with_default_properties(window, &[])
    }

    pub fn with_default_properties<'w, W: window::WindowT + glin::GlWindow>(window: &'w mut W, default_properties: &[glin::Property]) -> Result<Renderer<'static>>{
        let window_w = window.width() as u32;
        let window_h = window.height() as u32;
        let resolution_factor = window.resolution_factor();
        let default_mvp = graphics::Mvp::ortho_top_left(window.viewport());

        let context = glin::Context::from_properties(window, default_properties)?;
        let program_thick_lines = Renderer::allocate_program_thicklines(&context)?;
        Ok(Renderer{
            data: Rc::new(RendererData{
    			 vaos_cache: UnsafeCell::new(HashMap::new()),
    			 material_thick_lines: ::ShaderMaterial::new(program_thick_lines),
    			 bitmap_font: ::BitmapFont::new(&context),
    			 resolution_factor: resolution_factor,
                 id: NEXT_ID.with(|id| { let ret = *id.borrow(); *id.borrow_mut()+=1; ret }),
                 uniforms_cache: RefCell::new(DenseVec::new()),
             }),
            context,
            properties: default_properties.to_owned(),
            mvp: default_mvp,
        })
    }

    #[cfg(feature = "gles")]
    fn allocate_program_thicklines(gl: &Context) -> Result<Program>{
        gl.new_program().from_src_bindings(&[
                (gl::VERTEX_SHADER, shaders::VERTEX_SHADER_DEFAULT),
                (gl::FRAGMENT_SHADER, shaders::FRAGMENT_SHADER_THICK_LINES),
            ], &::default_attribute_bindings())
    }

    #[cfg(not(feature = "gles"))]
    fn allocate_program_thicklines(gl: &Context) -> Result<Program>{
        gl.new_program().from_src_bindings(&[
                (gl::VERTEX_SHADER, shaders::VERTEX_SHADER_DEFAULT),
                (gl::GEOMETRY_SHADER, shaders::GEOM_SHADER_THICK_LINES),
                (gl::FRAGMENT_SHADER, shaders::FRAGMENT_SHADER_THICK_LINES),
            ], &::default_attribute_bindings())
    }
}

impl<'c, R: RenderSurface + 'c> Renderer<'c, R>{
    pub fn resolution_factor(&self) -> f32{
        self.data.resolution_factor
    }

	pub fn clear_color<C:ToRgba>(&self, color: &C){
        self.context.clear_color(&color.to_rgba::<f32>());
	}

    pub fn clear_depth(&self){
        self.context.clear_depth()
    }

    pub fn clear_stencil(&self){
        self.context.clear_stencil()
    }

    pub fn mvp(&self) -> &graphics::Mvp{
        &self.mvp
    }

    #[inline]
    pub fn with_camera_viewport<C: graphics::CameraT>(&self, camera: &C, viewport: &Rect<i32>) -> Renderer<R>{
        self.with_mvp(graphics::Mvp::with_camera_viewport(camera, viewport))
    }


    #[inline]
    pub fn with_mvp<M: Into<graphics::Mvp>>(&self, mvp: M) -> Renderer<R>{
        let mvp = mvp.into();
        Renderer{
            data: self.data.clone(),
            context: self.context.with(&[]),
            properties: self.properties.clone(),
            mvp,
        }
    }

    #[inline]
    pub fn with_model<M: Into<graphics::Model>>(&self, model: M) -> Renderer<R>{
        let model = model.into();
        let mvp = self.mvp.for_model(model.matrix());
        Renderer{
            data: self.data.clone(),
            properties: self.properties.clone(),
            mvp,
            context: self.context.with(&[]),
        }
    }

    #[inline]
    pub fn with_properties(&self, properties: &[glin::Property]) -> Renderer<R>{
        let mut props = self.properties.clone();
        props.extend_from_slice(properties);
        Renderer{
            data: self.data.clone(),
            context: self.context.with(&props),
            properties: props,
            mvp: self.mvp.clone(),
        }
    }

    pub fn id(&self) -> usize{
        self.data.id
    }

    pub fn context(&self) -> &glin::Context<R>{
        &self.context
    }

    pub fn new_texture(&self) -> texture::Builder{
        self.context.new_texture()
    }

    pub fn new_cubemap(&self) -> cubemap::Builder{
        self.context.new_cubemap()
    }

    pub fn new_buffer(&self) -> buffer_object::Builder{
        self.context.new_buffer()
    }

    pub fn new_shared_buffer(&self) -> buffer_object::SharedBuilder{
        self.context.new_shared_buffer()
    }

    pub fn new_vao(&self) -> vao::Builder{
        self.context.new_vao()
    }

    pub fn new_simple_vao(&self) -> simple_vao::Builder{
        self.context.new_simple_vao()
    }

    pub fn new_program(&self) -> program::Builder{
        self.context.new_program()
    }

    pub fn new_shadow_map(&self) -> shadow_mapping::Builder{
        shadow_mapping::Builder(self.creation_proxy())
    }

    pub fn new_ttf<'a>(&'a self, path: &'a str, pt_height: f32) -> ttf::Builder<'a>{
        ttf::Builder::new(self.creation_proxy(), path, pt_height)
    }

    pub fn new_vao_mesh(&self) -> vao_mesh::Builder{
        vao_mesh::Builder(self.creation_proxy())
    }

    pub fn new_vao_path(&self) -> vao_path::Builder{
        vao_path::Builder(self.creation_proxy())
    }

    pub fn new_auto_program<P: AsRef<Path> + Clone + 'static>(&self, settings: autoload::ProgramSettings<P>) -> util::AutoLoader<glin::Program>{
        autoload::new_program(self.creation_proxy(), settings)
    }

    pub fn new_pbr_material(&self) -> pbr_material::Builder{
        pbr_material::Builder{gl: self.creation_proxy()}
    }

    pub fn new_skybox(&self) -> skybox::Builder{
        skybox::Builder{gl: self.creation_proxy()}
    }

    pub fn new_ibl(&self) -> image_based_light::Builder{
        image_based_light::Builder{gl: self.creation_proxy()}
    }

    pub fn new_object(&self) -> object::Builder{
        object::Builder{gl: self.creation_proxy()}
    }

    // pub fn new_object(&self) -> ObjectBuilder{
    //     ObjectBuilder{
    //         gl: self.creation_proxy()
    //     }
    // }

    pub fn to_simple_vao<T, U, M: ToSimpleVao<T,U>>(&self, mesh: &M) -> Result<SimpleVao<T>>{
        mesh.to_simple_vao(self, &::default_attribute_bindings(), gl::STATIC_DRAW)
    }

    pub fn creation_proxy(&self) -> ::CreationProxy{
        CreationProxy{ context: self.context.creation_proxy().clone() }
    }

    fn get_vao<T>(&self, mesh: &Mesh<T>) -> &glin::SimpleVao<T>
        where T: VertexFormat + Clone + 'static
    {
        let cache = unsafe{ &mut *self.data.vaos_cache.get() };
        match cache.entry(::std::any::TypeId::of::<T>()){
            Entry::Occupied(mut entry) => {
                let entry = entry.get_mut();
                let vao: &mut glin::SimpleVao<T> = entry.downcast_mut().unwrap();
                vao.load(mesh, gl::STATIC_DRAW);
                unsafe{ mem::transmute(vao) } // TODO: Why do we need to transmute the lifetime here?
            }

            Entry::Vacant(entry) => {
                let vao = entry.insert(Box::new(self.to_simple_vao(mesh).unwrap()))
                    .downcast_ref()
                    .unwrap();
                vao
            }
        }
    }
}

impl<'c> Renderer<'c> {
    #[inline]
    pub fn with_fbo<'f, F: glin::OffscreenBuffer>(&'f self, fbo: &'f F) -> Renderer<'f, F> {
        Renderer{
            data: self.data.clone(),
            properties: self.properties.clone(),
            context: self.context.with_fbo(fbo),
            mvp: self.mvp.clone(),
        }
    }

    pub fn new_fbo(&self) -> fbo::Builder{
        self.context.new_fbo()
    }

    pub fn new_fbo_color_attachment(&self) -> fbo::ColorAttachmentBuilder{
        self.context.new_fbo_color_attachment()
    }

    pub fn new_fbo_depth_attachment(&self) -> fbo::DepthAttachmentBuilder{
        self.context.new_fbo_depth_attachment()
    }

    pub fn new_render_buffer(&self) -> fbo::RenderBufferBuilder{
        self.context.new_render_buffer()
    }

    pub fn new_simple_fbo(&self, w: u32, h: u32, format: glin::fbo::ColorFormat) -> Result<::SimpleFbo>{
        ::SimpleFbo::new(self, w, h, 0, format)
    }

    pub fn new_simple_fbo_multisampled(&self, w: u32, h: u32, samples: u32, format: glin::fbo::ColorFormat) -> Result<::SimpleFbo>{
        ::SimpleFbo::new(self, w, h, samples, format)
    }
}


#[derive(Clone)]
pub struct CreationProxy{
    context: Rc<glin::CreationProxy>,
}

pub trait CreationContext: GlinCreationContext{
    fn new_shadow_map(&self) -> shadow_mapping::Builder;
    fn new_ttf<'a>(&'a self, path: &'a str, pt_height: f32) -> ttf::Builder<'a>;
    fn new_vao_mesh(&self) -> vao_mesh::Builder;
    fn new_vao_path(&self) -> vao_path::Builder;
    fn new_auto_program<P: AsRef<Path> + Clone + 'static>(&self, settings: autoload::ProgramSettings<P>) -> util::AutoLoader<glin::Program>;
    fn to_simple_vao<T, U, M: ToSimpleVao<T,U>>(&self, mesh: &M) -> Result<SimpleVao<T>>;
}

impl GlinCreationContext for CreationProxy{
    fn new_texture(&self) -> texture::Builder{
        self.context.new_texture()
    }

    fn new_cubemap(&self) -> cubemap::Builder{
        self.context.new_cubemap()
    }

    fn new_buffer(&self) -> buffer_object::Builder{
        self.context.new_buffer()
    }

    fn new_shared_buffer(&self) -> buffer_object::SharedBuilder{
        self.context.new_shared_buffer()
    }

    fn new_vao(&self) -> vao::Builder{
        self.context.new_vao()
    }

    fn new_simple_vao(&self) -> simple_vao::Builder{
        self.context.new_simple_vao()
    }

    fn new_program(&self) -> program::Builder{
        self.context.new_program()
    }

    fn creation_proxy(&self) -> &Rc<glin::CreationProxy>{
        &self.context
    }
}

impl glin::SurfaceCreationContext for CreationProxy {
    fn new_fbo(&self) -> fbo::Builder{
        self.context.new_fbo()
    }

    fn new_fbo_color_attachment(&self) -> fbo::ColorAttachmentBuilder{
        self.context.new_fbo_color_attachment()
    }

    fn new_fbo_depth_attachment(&self) -> fbo::DepthAttachmentBuilder{
        self.context.new_fbo_depth_attachment()
    }

    fn new_render_buffer(&self) -> fbo::RenderBufferBuilder{
        self.context.new_render_buffer()
    }
}


impl CreationContext for CreationProxy{
    fn new_shadow_map(&self) -> shadow_mapping::Builder{
        shadow_mapping::Builder(self.clone())
    }

    fn new_ttf<'a>(&'a self, path: &'a str, pt_height: f32) -> ttf::Builder<'a>{
        ttf::Builder::new(self.clone(), path, pt_height)
    }

    fn new_vao_mesh(&self) -> vao_mesh::Builder{
        vao_mesh::Builder(self.clone())
    }

    fn new_vao_path(&self) -> vao_path::Builder{
        vao_path::Builder(self.clone())
    }

    fn new_auto_program<P: AsRef<Path> + Clone + 'static>(&self, settings: autoload::ProgramSettings<P>) -> util::AutoLoader<glin::Program>{
        autoload::new_program(self.clone(), settings)
    }

    fn to_simple_vao<T, U, M: ToSimpleVao<T,U>>(&self, mesh: &M) -> Result<SimpleVao<T>>{
        mesh.to_simple_vao(self, &::default_attribute_bindings(), gl::STATIC_DRAW)
    }
}


impl<'c, C: CreationContext> CreationContext for &'c C{
    fn new_shadow_map(&self) -> shadow_mapping::Builder{
        (*self).new_shadow_map()
    }

    fn new_ttf<'a>(&'a self, path: &'a str, pt_height: f32) -> ttf::Builder<'a>{
        (*self).new_ttf(path, pt_height)
    }

    fn new_vao_mesh(&self) -> vao_mesh::Builder{
        (*self).new_vao_mesh()
    }

    fn new_vao_path(&self) -> vao_path::Builder{
        (*self).new_vao_path()
    }

    fn new_auto_program<P: AsRef<Path> + Clone + 'static>(&self, settings: autoload::ProgramSettings<P>) -> util::AutoLoader<glin::Program>{
        (*self).new_auto_program(settings)
    }

    fn to_simple_vao<T, U, M: ToSimpleVao<T,U>>(&self, mesh: &M) -> Result<SimpleVao<T>>{
        (*self).to_simple_vao(mesh)
    }
}


impl<'c, R: RenderSurface> CreationContext for Renderer<'c, R>{
    fn new_shadow_map(&self) -> shadow_mapping::Builder{
        shadow_mapping::Builder(self.creation_proxy())
    }

    fn new_ttf<'a>(&'a self, path: &'a str, pt_height: f32) -> ttf::Builder<'a>{
        ttf::Builder::new(self.creation_proxy(), path, pt_height)
    }

    fn new_vao_mesh(&self) -> vao_mesh::Builder{
        vao_mesh::Builder(self.creation_proxy())
    }

    fn new_vao_path(&self) -> vao_path::Builder{
        vao_path::Builder(self.creation_proxy())
    }

    fn new_auto_program<P: AsRef<Path> + Clone + 'static>(&self, settings: autoload::ProgramSettings<P>) -> util::AutoLoader<glin::Program>{
        autoload::new_program(self.creation_proxy(), settings)
    }

    fn to_simple_vao<T, U, M: ToSimpleVao<T,U>>(&self, mesh: &M) -> Result<SimpleVao<T>>{
        mesh.to_simple_vao(self, &::default_attribute_bindings(), gl::STATIC_DRAW)
    }
}

impl<'c, R: RenderSurface> glin::CreationContext for Renderer<'c, R>{
    fn new_texture(&self) -> texture::Builder{
        self.context.new_texture()
    }

    fn new_cubemap(&self) -> cubemap::Builder{
        self.context.new_cubemap()
    }

    fn new_buffer(&self) -> buffer_object::Builder{
        self.context.new_buffer()
    }

    fn new_shared_buffer(&self) -> buffer_object::SharedBuilder{
        self.context.new_shared_buffer()
    }

    fn new_vao(&self) -> vao::Builder{
        self.context.new_vao()
    }

    fn new_simple_vao(&self) -> simple_vao::Builder{
        self.context.new_simple_vao()
    }

    fn new_program(&self) -> program::Builder{
        self.context.new_program()
    }

    fn creation_proxy(&self) -> &Rc<glin::CreationProxy>{
        self.context.creation_proxy()
    }
}

impl<'c> glin::SurfaceCreationContext for Renderer<'c>{
    fn new_fbo(&self) -> fbo::Builder{
        self.context.new_fbo()
    }

    fn new_fbo_color_attachment(&self) -> fbo::ColorAttachmentBuilder{
        self.context.new_fbo_color_attachment()
    }

    fn new_fbo_depth_attachment(&self) -> fbo::DepthAttachmentBuilder{
        self.context.new_fbo_depth_attachment()
    }

    fn new_render_buffer(&self) -> fbo::RenderBufferBuilder{
        self.context.new_render_buffer()
    }
}

pub trait Renderer2d: Renderer3d{
    fn draw_mesh_with_material<T, M: ::Material>(&self, mesh: &graphics::Mesh<T>, material: &M)
        where T: VertexFormat + Clone + 'static;

    fn draw_pos<M: ::Material, R: Render2d<Material=M>>(&self, obj: R, pos: &Pnt2);

    fn draw_size<M: ::Material, R: Render2d<Material=M>>(&self, obj: R, pos: &Pnt2, size: &Vec2);

    fn draw_rect<M: ::Material, R: Render2d<Material=M>>(&self, obj: R, rect: &Rect<f32>);

    fn draw_pos_with_material<M: ::Material, M2: ::Material, R: Render2d<Material=M>>(&self, obj: R, pos: &Pnt2, mat: &M2);

    fn draw_size_with_material<M: ::Material, M2: ::Material, R: Render2d<Material=M>>(&self, obj: R, pos: &Pnt2, size: &Vec2, mat: &M2);

    fn draw_rect_with_material<M: ::Material, M2: ::Material, R: Render2d<Material=M>>(&self, obj: R, rect: &Rect<f32>, mat: &M2);
}

impl<'c, R: RenderSurface + 'c> Renderer2d for Renderer<'c, R>{
    fn draw_mesh_with_material<T, M: ::Material>(&self, mesh: &graphics::Mesh<T>, material: &M)
        where T: VertexFormat + Clone + 'static
    {
        self.draw_vao(self.get_vao(mesh).full_range(), &material.program(self), &material.uniforms(self));
    }

    fn draw_pos<M: ::Material, O: Render2d<Material=M>>(&self, obj: O, pos: &Pnt2){
        //self.reset_state();
        obj.render(self, pos);
    }

    fn draw_size<M: ::Material, O: Render2d<Material=M>>(&self, obj: O, pos: &Pnt2, size: &Vec2){
        //self.reset_state();
        obj.render_size(self, pos, size);
    }

    fn draw_rect<M: ::Material, O: Render2d<Material=M>>(&self, obj: O, rect: &Rect<f32>){
        //self.reset_state();
        obj.render_size(self, &rect.pos, &vec2(rect.width,rect.height));
    }

    fn draw_pos_with_material<M: ::Material, M2: ::Material, O: Render2d<Material=M>>(&self, obj: O, pos: &Pnt2, mat: &M2){
        //self.reset_state();
        obj.render_with_material(self, pos, mat);
    }

    fn draw_size_with_material<M: ::Material, M2: ::Material, O: Render2d<Material=M>>(&self, obj: O, pos: &Pnt2, size: &Vec2, mat: &M2){
        //self.reset_state();
        obj.render_size_with_material(self, pos, size, mat);
    }

    fn draw_rect_with_material<M: ::Material, M2: ::Material, O: Render2d<Material=M>>(&self, obj: O, rect: &Rect<f32>, mat: &M2){
        //self.reset_state();
        obj.render_size_with_material(self, &rect.pos, &vec2(rect.width,rect.height), mat);
    }
}

pub trait Renderer3d{
    fn draw<R: ::Render3d>(&self, obj: &R);

    fn draw_with_material<V,M>(&self, obj: &::Object<V>, material: &M)
        where for<'a> &'a V: ::VaoDraw,
              M: ::Material;

    fn draw_vao_with_material<V, M>(&self, obj: V, material: &M)
        where V: ::VaoDraw,
              M: ::Material;

    fn draw_vao<V: ::VaoDraw>(&self, vao_range: V, program: &Program, uniforms: &[glin::program::Uniform]);
}

impl<'c, R: RenderSurface + 'c> Renderer3d for Renderer<'c, R>{
    fn draw<O: ::Render3d>(&self, obj: &O){
        obj.render(self);
    }

    #[inline]
    fn draw_with_material<V,M>(&self, obj: &::Object<V>, material: &M)
        where for<'a> &'a V: ::VaoDraw,
              M: ::Material
    {
        self.with_model(obj).draw_vao_with_material(obj.geometry(), material)
    }

    #[inline]
    fn draw_vao_with_material<V, M>(&self, vao: V, material: &M)
        where V: ::VaoDraw,
              M: ::Material
    {
        let program = material.program(self);
        let uniforms = material.uniforms(self);
        let properties = material.properties();
        let gl = self.with_properties(&properties);
        gl.draw_vao(vao, program, &uniforms);
    }

    #[inline]
    fn draw_vao<V: ::VaoDraw>(&self, vao_range: V, program: &Program, uniforms: &[glin::program::Uniform]){
        let normal = self.mvp.normal(); // TODO: Otherwise normal matrix is not updated, chek why
        let mvp_uniforms = self.data.uniforms_cache.borrow_mut()
            .entry(program.id() as usize)
            .or_insert_with(|| graphics::Mvp::from_program_non_strict(&program))
            .uniforms(&self.mvp);
        program.set_uniforms(&mvp_uniforms);
            // self.properties.mvp.uniforms();
        // mvp_uniforms.extend_from_slice(uniforms);
        self.context.draw(vao_range, program, &uniforms);
    }
}

impl<'c, R: RenderSurface + 'c> ::traits::Renderer for Renderer<'c, R>{
    fn clear<C:ToRgba>(&self, color: &C){
        self.clear_color(color);
        self.clear_depth();
    }

    fn draw_mesh<T>(&self, mesh: &graphics::Mesh<T>)
        where T: VertexFormat + Clone + 'static
    {
        let material = BasicMaterial::default();
        /*let vao = gl::Vao::from_data_bindings(
            mesh,
            &gl::default_attribute_bindings(),
            gl::STATIC_DRAW
        ).unwrap();
        self.draw_vao(&vao, &material.program(), &material.uniforms());*/
        self.draw_vao(self.get_vao(mesh).deref(), &material.program(self), &material.uniforms(self));
    }

    fn draw_string<C: ToRgba>(&self, font: &::Ttf, string: &str, x: f32, y: f32, color: &C){
        let material = font.material(color);
        let text = font.mesh(string,x,y,self.origin());
        let vao_text = self.get_vao(&text);
        self.draw_vao(vao_text, &material.program(self), &material.uniforms(self));
    }

    fn draw_string_box<C: ToRgba>(&self, font: &::Ttf, string: &str, x: f32, y: f32, w: f32, h: f32, color: &C){
        let material = font.material(color);
	    let text = font.box_mesh(string,x,y,w,h,self.origin());
        let vao_text = self.get_vao(&text);
        self.draw_vao(vao_text, &material.program(self), &material.uniforms(self));
    }

    fn draw_bitmap_string<C: ToRgba>(&self, string: &str, x: f32, y: f32, color: &C){
    	let material = self.data.bitmap_font.material(color);
    	let text = self.data.bitmap_font.mesh(string, x, y, self.origin());
        let vao_text = self.get_vao(&text);
        self.draw_vao(vao_text, &material.program(self), &material.uniforms(self));
    }

    fn draw_line<C: ToRgba>(&self, from: &Pnt2, to: &Pnt2, color:&C ){
        self.draw_mesh(&graphics::line_color(from,to,color));
    }

    fn draw_rectangle_fill<C: ToRgba>(&self, pos: &Pnt2, w: f32, h:f32, color:&C ){
        self.draw_mesh(&graphics::rectangle_color(pos.x,pos.y,w,h,color));
    }

    fn draw_rectangle_lines<C: ToRgba>(&self, pos: &Pnt2, w: f32, h:f32, color:&C ){
        let mut mesh = graphics::rectangle_color(pos.x,pos.y,w,h,color);
        mesh.set_primitive_type(PrimitiveType::LineLoop);
        self.draw_mesh(&mesh);
    }

    fn draw_circle_fill<C: ToRgba>(&self, x: f32, y: f32, r: f32, color:&C ){
        self.draw_mesh(&graphics::circle_color(x,y,r,20,color));
    }

    fn draw_circle_lines<C: ToRgba>(&self, x: f32, y: f32, r: f32, color:&C ){
        self.draw_mesh(&graphics::circle_color(x,y,r,20,color));
    }

    fn draw_ellipse_fill<C: ToRgba>(&self, x: f32, y: f32, w: f32, h: f32, color:&C ){
        self.draw_mesh(&graphics::ellipse_color(x,y,w,h,20,color));
    }

    fn draw_ellipse_lines<C: ToRgba>(&self, x: f32, y: f32, w: f32, h: f32, color:&C ){
        self.draw_mesh(&graphics::ellipse_color(x,y,w,h,20,color));
    }

    fn origin(&self) -> CoordinateOrigin{
		self.mvp.origin()
	}
}

pub trait Render3d{
    fn render<R: RenderSurface>(&self, renderer: &Renderer<R>) where Self: Sized;
}

impl<T:Clone + ::VertexFormat + 'static> Render3d for ::VaoMesh<T>{
    fn render<R: RenderSurface>(&self, gl: &Renderer<R>){
        let material = BasicMaterial::default();
        gl.draw_vao(self.vao().deref(), &material.program(gl), &material.uniforms(gl));
    }
}

impl<'a> Render3d for ::VaoPathFill<'a>{
    fn render<R: RenderSurface>(&self, gl: &Renderer<R>){
        let mat = BasicMaterial::default();
        gl.clear_stencil();

        let program = mat.program(gl);
        gl.with_properties(&[
                glin::Property::ColorMask([false, false, false, false]),
                glin::Property::StencilTest(true),
                glin::Property::StencilFunc(gl::ALWAYS, 0x0, 0x1),
                glin::Property::StencilOp(gl::KEEP,gl::INVERT,gl::INVERT),
            ])
          .draw_vao(self.vao_mesh().deref(), program, &mat.uniforms(gl));

        let bb_vao = gl.get_vao(&bounding_box_mesh(self.vao_mesh().mesh(), &self.color()));
        gl.with_properties(&[
                glin::Property::ColorMask([true, true, true, true]),
                glin::Property::StencilTest(true),
                glin::Property::StencilFunc(gl::EQUAL, 0x1, 0x1),
                glin::Property::StencilOp(gl::KEEP,gl::KEEP,gl::KEEP),
            ]).draw_vao(bb_vao.full_range(), program, &mat.uniforms(gl));
    }
}

impl<'a> Render3d for ::VaoPathContour<'a>{
    fn render<R: RenderSurface>(&self, gl: &Renderer<R>){
        let material = &gl.data.material_thick_lines;
        let mut uniforms = material.uniforms(gl);
        let viewport = *gl.context.state().viewport();
        let width = match self.line_cap(){
            LineCap::Square =>
                self.line_width().abs(),
            LineCap::Triangular =>
                -self.line_width().abs(),
        };
        uniforms.extend_from_slice(&uniforms!{
            viewportSize: vec2(viewport.width() as f32, viewport.height() as f32),
            lineWidth: width
        });

        gl.draw_vao(self.vao_mesh().deref(), &material.program(gl), &uniforms);
    }
}

pub trait Render2d{
    type Material: ::Material;
    fn default_material(&self) -> Self::Material;
    fn render<R: RenderSurface>(&self, renderer: &Renderer<R>, pos: &Pnt2){
        self.render_with_material(renderer, pos, &self.default_material());
    }
    fn render_size<R: RenderSurface>(&self, renderer: &Renderer<R>, pos: &Pnt2, size: &Vec2){
        self.render_size_with_material(renderer, pos, size, &self.default_material());
    }
    fn render_with_material<R: RenderSurface, M: ::Material>(&self, renderer: &Renderer<R>, pos: &Pnt2, material: &M);
    fn render_size_with_material<R: RenderSurface, M: ::Material>(&self, renderer: &Renderer<R>, pos: &Pnt2, size: &Vec2, material: &M);
}

fn bounding_box_mesh<C: ToRgba>(mesh: &graphics::Mesh<Vec2>, color: &C) -> graphics::Mesh<graphics::Vertex2DColor>{
    let mut min = Vec2::new(f32::MAX,f32::MAX);
    let mut max = Vec2::new(f32::MIN,f32::MIN);
    for v in mesh.iter(){
        if min.x > v.x { min.x = v.x; }
        if min.y > v.y { min.y = v.y; }
        if max.x < v.x { max.x = v.x; }
        if max.y < v.y { max.y = v.y; }
    }
    let size = max-min;
    graphics::rectangle_color(min.x, min.y, size.x, size.y, color)
}

// shaders default

#[cfg(not(any(target_os="android", target_os="emscripten")))]
mod shaders{
    pub static VERTEX_SHADER_DEFAULT: &'static str = include_str!("shaders/vertex.glsl");

    pub static GEOM_SHADER_THICK_LINES: &'static str = include_str!("shaders/geom_thick_lines.glsl");
    pub static FRAGMENT_SHADER_THICK_LINES: &'static str = include_str!("shaders/frag_thick_lines.glsl");
}


#[cfg(any(target_os="android", target_os="emscripten"))]
mod shaders{
    pub static VERTEX_SHADER_DEFAULT: &'static str = include_str!("shaders/vertex_gles.glsl");
    pub static FRAGMENT_SHADER_THICK_LINES: &'static str = include_str!("shaders/fragment_color_coords_gles.glsl");
}