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
use std::mem;
use std::rc::Rc;

#[cfg(not(target_arch = "wasm32"))]
use std::ffi::c_void;

use fnv::FnvHashMap;
use imgref::ImgVec;
use rgb::RGBA8;

use crate::{
    renderer::{ImageId, Vertex},
    BlendFactor, Color, CompositeOperationState, ErrorKind, FillRule, ImageInfo, ImageSource, ImageStore,
};

use glow::HasContext;

use super::{Command, CommandType, Params, RenderTarget, Renderer};

mod program;
use program::MainProgram;

mod gl_texture;
use gl_texture::GlTexture;

mod framebuffer;
use framebuffer::Framebuffer;

mod uniform_array;
use uniform_array::UniformArray;

pub struct OpenGl {
    debug: bool,
    antialias: bool,
    is_opengles_2_0: bool,
    view: [f32; 2],
    screen_view: [f32; 2],
    main_program: MainProgram,
    vert_arr: Option<<glow::Context as glow::HasContext>::VertexArray>,
    vert_buff: Option<<glow::Context as glow::HasContext>::Buffer>,
    framebuffers: FnvHashMap<ImageId, Result<Framebuffer, ErrorKind>>,
    context: Rc<glow::Context>,
    screen_target: Option<Framebuffer>
}

impl OpenGl {
    #[cfg(not(target_arch = "wasm32"))]
    pub fn new<F>(load_fn: F) -> Result<Self, ErrorKind>
    where
        F: FnMut(&str) -> *const c_void,
    {
        Self::new_from_context(unsafe { glow::Context::from_loader_function(load_fn) }, false)
    }

    #[cfg(target_arch = "wasm32")]
    pub fn new_from_html_canvas(canvas: &web_sys::HtmlCanvasElement) -> Result<Self, ErrorKind> {
        let mut attrs = web_sys::WebGlContextAttributes::new();
        attrs.stencil(true);
        attrs.antialias(false);

        use wasm_bindgen::JsCast;
        let webgl1_context = canvas
            .get_context_with_context_options("webgl", attrs.as_ref())
            .map_err(|_| ErrorKind::GeneralError("Canvas::getContext failed to retrieve WebGL 1 context".to_owned()))?
            .unwrap()
            .dyn_into::<web_sys::WebGlRenderingContext>()
            .unwrap();

        let context = glow::Context::from_webgl1_context(webgl1_context);
        Self::new_from_context(context, true)
    }

    fn new_from_context(context: glow::Context, is_opengles_2_0: bool) -> Result<Self, ErrorKind> {
        let debug = cfg!(debug_assertions);
        let antialias = true;

        let context = Rc::new(context);

        let main_program = MainProgram::new(&context, antialias)?;

        let mut opengl = OpenGl {
            debug: debug,
            antialias: antialias,
            is_opengles_2_0: false,
            view: [0.0, 0.0],
            screen_view: [0.0, 0.0],
            main_program: main_program,
            vert_arr: Default::default(),
            vert_buff: Default::default(),
            framebuffers: Default::default(),
            context: context.clone(),
            screen_target: None
        };

        unsafe {
            opengl.is_opengles_2_0 = is_opengles_2_0;

            opengl.vert_arr = opengl.context.create_vertex_array().ok();
            opengl.vert_buff = opengl.context.create_buffer().ok();
        }

        Ok(opengl)
    }

    pub fn is_opengles(&self) -> bool {
        self.is_opengles_2_0
    }

    fn check_error(&self, label: &str) {
        if !self.debug {
            return;
        }

        let err = unsafe { self.context.get_error() };

        if err == glow::NO_ERROR {
            return;
        }

        let message = match err {
            glow::INVALID_ENUM => "Invalid enum",
            glow::INVALID_VALUE => "Invalid value",
            glow::INVALID_OPERATION => "Invalid operation",
            glow::OUT_OF_MEMORY => "Out of memory",
            glow::INVALID_FRAMEBUFFER_OPERATION => "Invalid framebuffer operation",
            _ => "Unknown error",
        };

        eprintln!("({}) Error on {} - {}", err, label, message);
    }

    fn gl_factor(factor: BlendFactor) -> u32 {
        match factor {
            BlendFactor::Zero => glow::ZERO,
            BlendFactor::One => glow::ONE,
            BlendFactor::SrcColor => glow::SRC_COLOR,
            BlendFactor::OneMinusSrcColor => glow::ONE_MINUS_SRC_COLOR,
            BlendFactor::DstColor => glow::DST_COLOR,
            BlendFactor::OneMinusDstColor => glow::ONE_MINUS_DST_COLOR,
            BlendFactor::SrcAlpha => glow::SRC_ALPHA,
            BlendFactor::OneMinusSrcAlpha => glow::ONE_MINUS_SRC_ALPHA,
            BlendFactor::DstAlpha => glow::DST_ALPHA,
            BlendFactor::OneMinusDstAlpha => glow::ONE_MINUS_DST_ALPHA,
            BlendFactor::SrcAlphaSaturate => glow::SRC_ALPHA_SATURATE,
        }
    }

    fn set_composite_operation(&self, blend_state: CompositeOperationState) {
        unsafe {
            self.context.blend_func_separate(
                Self::gl_factor(blend_state.src_rgb),
                Self::gl_factor(blend_state.dst_rgb),
                Self::gl_factor(blend_state.src_alpha),
                Self::gl_factor(blend_state.dst_alpha),
            );
        }
    }

    fn convex_fill(&self, images: &ImageStore<GlTexture>, cmd: &Command, gpu_paint: &Params) {
        self.set_uniforms(images, gpu_paint, cmd.image, cmd.alpha_mask);

        for drawable in &cmd.drawables {
            if let Some((start, count)) = drawable.fill_verts {
                unsafe {
                    self.context.draw_arrays(glow::TRIANGLE_FAN, start as i32, count as i32);
                }
            }

            if let Some((start, count)) = drawable.stroke_verts {
                unsafe {
                    self.context
                        .draw_arrays(glow::TRIANGLE_STRIP, start as i32, count as i32);
                }
            }
        }

        self.check_error("convex_fill");
    }

    fn concave_fill(&self, images: &ImageStore<GlTexture>, cmd: &Command, stencil_paint: &Params, fill_paint: &Params) {
        unsafe {
            self.context.enable(glow::STENCIL_TEST);
            self.context.stencil_mask(0xff);
            self.context.stencil_func(glow::ALWAYS, 0, 0xff);
            self.context.color_mask(false, false, false, false);
            //glow::DepthMask(glow::FALSE);
        }

        self.set_uniforms(images, stencil_paint, None, None);

        unsafe {
            self.context
                .stencil_op_separate(glow::FRONT, glow::KEEP, glow::KEEP, glow::INCR_WRAP);
            self.context
                .stencil_op_separate(glow::BACK, glow::KEEP, glow::KEEP, glow::DECR_WRAP);
            self.context.disable(glow::CULL_FACE);
        }

        for drawable in &cmd.drawables {
            if let Some((start, count)) = drawable.fill_verts {
                unsafe {
                    self.context.draw_arrays(glow::TRIANGLE_FAN, start as i32, count as i32);
                }
            }
        }

        unsafe {
            self.context.enable(glow::CULL_FACE);
            // Draw anti-aliased pixels
            self.context.color_mask(true, true, true, true);
            //glow::DepthMask(glow::TRUE);
        }

        self.set_uniforms(images, fill_paint, cmd.image, cmd.alpha_mask);

        if self.antialias {
            unsafe {
                match cmd.fill_rule {
                    FillRule::NonZero => self.context.stencil_func(glow::EQUAL, 0x0, 0xff),
                    FillRule::EvenOdd => self.context.stencil_func(glow::EQUAL, 0x0, 0x1),
                }

                self.context.stencil_op(glow::KEEP, glow::KEEP, glow::KEEP);
            }

            // draw fringes
            for drawable in &cmd.drawables {
                if let Some((start, count)) = drawable.stroke_verts {
                    unsafe {
                        self.context
                            .draw_arrays(glow::TRIANGLE_STRIP, start as i32, count as i32);
                    }
                }
            }
        }

        unsafe {
            match cmd.fill_rule {
                FillRule::NonZero => self.context.stencil_func(glow::NOTEQUAL, 0x0, 0xff),
                FillRule::EvenOdd => self.context.stencil_func(glow::NOTEQUAL, 0x0, 0x1),
            }

            self.context.stencil_op(glow::ZERO, glow::ZERO, glow::ZERO);

            if let Some((start, count)) = cmd.triangles_verts {
                self.context
                    .draw_arrays(glow::TRIANGLE_STRIP, start as i32, count as i32);
            }

            self.context.disable(glow::STENCIL_TEST);
        }

        self.check_error("concave_fill");
    }

    fn stroke(&self, images: &ImageStore<GlTexture>, cmd: &Command, paint: &Params) {
        self.set_uniforms(images, paint, cmd.image, cmd.alpha_mask);

        for drawable in &cmd.drawables {
            if let Some((start, count)) = drawable.stroke_verts {
                unsafe {
                    self.context
                        .draw_arrays(glow::TRIANGLE_STRIP, start as i32, count as i32);
                }
            }
        }

        self.check_error("stroke");
    }

    fn stencil_stroke(&self, images: &ImageStore<GlTexture>, cmd: &Command, paint1: &Params, paint2: &Params) {
        unsafe {
            self.context.enable(glow::STENCIL_TEST);
            self.context.stencil_mask(0xff);

            // Fill the stroke base without overlap
            self.context.stencil_func(glow::EQUAL, 0x0, 0xff);
            self.context.stencil_op(glow::KEEP, glow::KEEP, glow::INCR);
        }

        self.set_uniforms(images, paint2, cmd.image, cmd.alpha_mask);

        for drawable in &cmd.drawables {
            if let Some((start, count)) = drawable.stroke_verts {
                unsafe {
                    self.context
                        .draw_arrays(glow::TRIANGLE_STRIP, start as i32, count as i32);
                }
            }
        }

        // Draw anti-aliased pixels.
        self.set_uniforms(images, paint1, cmd.image, cmd.alpha_mask);

        unsafe {
            self.context.stencil_func(glow::EQUAL, 0x0, 0xff);
            self.context.stencil_op(glow::KEEP, glow::KEEP, glow::KEEP);
        }

        for drawable in &cmd.drawables {
            if let Some((start, count)) = drawable.stroke_verts {
                unsafe {
                    self.context
                        .draw_arrays(glow::TRIANGLE_STRIP, start as i32, count as i32);
                }
            }
        }

        unsafe {
            // Clear stencil buffer.
            self.context.color_mask(false, false, false, false);
            self.context.stencil_func(glow::ALWAYS, 0x0, 0xff);
            self.context.stencil_op(glow::ZERO, glow::ZERO, glow::ZERO);
        }

        for drawable in &cmd.drawables {
            if let Some((start, count)) = drawable.stroke_verts {
                unsafe {
                    self.context
                        .draw_arrays(glow::TRIANGLE_STRIP, start as i32, count as i32);
                }
            }
        }

        unsafe {
            self.context.color_mask(true, true, true, true);
            self.context.disable(glow::STENCIL_TEST);
        }

        self.check_error("stencil_stroke");
    }

    fn triangles(&self, images: &ImageStore<GlTexture>, cmd: &Command, paint: &Params) {
        self.set_uniforms(images, paint, cmd.image, cmd.alpha_mask);

        if let Some((start, count)) = cmd.triangles_verts {
            unsafe {
                self.context.draw_arrays(glow::TRIANGLES, start as i32, count as i32);
            }
        }

        self.check_error("triangles");
    }

    fn set_uniforms(
        &self,
        images: &ImageStore<GlTexture>,
        paint: &Params,
        image_tex: Option<ImageId>,
        alpha_tex: Option<ImageId>,
    ) {
        let arr = UniformArray::from(paint);
        self.main_program.set_config(arr.as_slice());
        self.check_error("set_uniforms uniforms");

        let tex = image_tex
            .and_then(|id| images.get(id))
            .map_or(None, |tex| Some(tex.id()));

        unsafe {
            self.context.active_texture(glow::TEXTURE0);
            self.context.bind_texture(glow::TEXTURE_2D, tex);
        }

        let masktex = alpha_tex
            .and_then(|id| images.get(id))
            .map_or(None, |tex| Some(tex.id()));

        unsafe {
            self.context.active_texture(glow::TEXTURE0 + 1);
            self.context.bind_texture(glow::TEXTURE_2D, masktex);
        }

        self.check_error("set_uniforms texture");
    }

    fn clear_rect(&self, x: u32, y: u32, width: u32, height: u32, color: Color) {
        unsafe {
            self.context.enable(glow::SCISSOR_TEST);
            self.context.scissor(
                x as i32,
                self.view[1] as i32 - (height as i32 + y as i32),
                width as i32,
                height as i32,
            );
            self.context.clear_color(color.r, color.g, color.b, color.a);
            self.context.clear(glow::COLOR_BUFFER_BIT | glow::STENCIL_BUFFER_BIT);
            self.context.disable(glow::SCISSOR_TEST);
        }
    }

    fn set_target(&mut self, images: &ImageStore<GlTexture>, target: RenderTarget) {
        match (target, &self.screen_target) {
            (RenderTarget::Screen, None) => unsafe {
                Framebuffer::unbind(&self.context);
                self.view = self.screen_view;
                self.context.viewport(0, 0, self.view[0] as i32, self.view[1] as i32);
            },
            (RenderTarget::Screen, Some(framebuffer)) => {
                framebuffer.bind();
                self.view = self.screen_view;
                unsafe {
                    self.context.viewport(0, 0, self.view[0] as i32, self.view[1] as i32);
                }
            },
            (RenderTarget::Image(id), _) => {
                let context = self.context.clone();
                if let Some(texture) = images.get(id) {
                    if let Ok(fb) = self
                        .framebuffers
                        .entry(id)
                        .or_insert_with(|| Framebuffer::new(&context, texture))
                    {
                        fb.bind();

                        self.view[0] = texture.info().width() as f32;
                        self.view[1] = texture.info().height() as f32;

                        unsafe {
                            self.context
                                .viewport(0, 0, texture.info().width() as i32, texture.info().height() as i32);
                        }
                    }
                }
            }
        }
    }

    /// Make the "Screen" RenderTarget actually render to a framebuffer object. This is useful when
    /// embedding femtovg into another program where final composition is handled by an external task.
    /// The given `framebuffer_object` must refer to a Framebuffer Object created on the current OpenGL
    /// Context, and must have a depth & stencil attachment.
    ///
    /// Pass `None` to clear any previous Framebuffer Object ID that was passed and target rendering to
    /// the default target (normally the window).
    pub fn set_screen_target(&mut self, framebuffer_object: Option<<glow::Context as glow::HasContext>::Framebuffer>) {
        match framebuffer_object {
            Some(fbo_id) => self.screen_target = Some(Framebuffer::from_external(&self.context, fbo_id)),
            None => self.screen_target = None
        }
    }
}

impl Renderer for OpenGl {
    type Image = GlTexture;

    fn set_size(&mut self, width: u32, height: u32, _dpi: f32) {
        self.view[0] = width as f32;
        self.view[1] = height as f32;

        self.screen_view = self.view;

        unsafe {
            self.context.viewport(0, 0, width as i32, height as i32);
        }
    }

    fn render(&mut self, images: &ImageStore<Self::Image>, verts: &[Vertex], commands: &[Command]) {
        self.main_program.bind();

        unsafe {
            self.context.enable(glow::CULL_FACE);

            self.context.cull_face(glow::BACK);
            self.context.front_face(glow::CCW);
            self.context.enable(glow::BLEND);
            self.context.disable(glow::DEPTH_TEST);
            self.context.disable(glow::SCISSOR_TEST);
            self.context.color_mask(true, true, true, true);
            self.context.stencil_mask(0xffff_ffff);
            self.context.stencil_op(glow::KEEP, glow::KEEP, glow::KEEP);
            self.context.stencil_func(glow::ALWAYS, 0, 0xffff_ffff);
            self.context.active_texture(glow::TEXTURE0);
            self.context.bind_texture(glow::TEXTURE_2D, None);
            self.context.active_texture(glow::TEXTURE0 + 1);
            self.context.bind_texture(glow::TEXTURE_2D, None);

            self.context.bind_vertex_array(self.vert_arr);

            let vertex_size = mem::size_of::<Vertex>();

            self.context.bind_buffer(glow::ARRAY_BUFFER, self.vert_buff);
            self.context
                .buffer_data_u8_slice(glow::ARRAY_BUFFER, verts.align_to().1, glow::STREAM_DRAW);

            self.context.enable_vertex_attrib_array(0);
            self.context.enable_vertex_attrib_array(1);

            self.context
                .vertex_attrib_pointer_f32(0, 2, glow::FLOAT, false, vertex_size as i32, 0);
            self.context.vertex_attrib_pointer_f32(
                1,
                2,
                glow::FLOAT,
                false,
                vertex_size as i32,
                2 * mem::size_of::<f32>() as i32,
            );
        }

        // Bind the two uniform samplers to texture units
        self.main_program.set_tex(0);
        self.main_program.set_masktex(1);

        self.check_error("render prepare");

        for cmd in commands {
            self.set_composite_operation(cmd.composite_operation);

            match &cmd.cmd_type {
                CommandType::ConvexFill { params } => self.convex_fill(images, cmd, params),
                CommandType::ConcaveFill {
                    stencil_params,
                    fill_params,
                } => self.concave_fill(images, cmd, stencil_params, fill_params),
                CommandType::Stroke { params } => self.stroke(images, cmd, params),
                CommandType::StencilStroke { params1, params2 } => self.stencil_stroke(images, cmd, params1, params2),
                CommandType::Triangles { params } => self.triangles(images, cmd, params),
                CommandType::ClearRect {
                    x,
                    y,
                    width,
                    height,
                    color,
                } => {
                    self.clear_rect(*x, *y, *width, *height, *color);
                }
                CommandType::SetRenderTarget(target) => {
                    self.set_target(images, *target);
                    self.main_program.set_view(self.view);
                }
            }
        }

        unsafe {
            self.context.disable_vertex_attrib_array(0);
            self.context.disable_vertex_attrib_array(1);
            self.context.bind_vertex_array(None);

            self.context.disable(glow::CULL_FACE);
            self.context.bind_buffer(glow::ARRAY_BUFFER, None);
            self.context.bind_texture(glow::TEXTURE_2D, None);
        }

        self.main_program.unbind();

        self.check_error("render done");
    }

    fn alloc_image(&mut self, info: ImageInfo) -> Result<Self::Image, ErrorKind> {
        Self::Image::new(&self.context, info, self.is_opengles_2_0)
    }

    fn update_image(
        &mut self,
        image: &mut Self::Image,
        data: ImageSource,
        x: usize,
        y: usize,
    ) -> Result<(), ErrorKind> {
        image.update(data, x, y, self.is_opengles_2_0)
    }

    fn delete_image(&mut self, image: Self::Image) {
        image.delete();
    }

    fn screenshot(&mut self) -> Result<ImgVec<RGBA8>, ErrorKind> {
        //let mut image = image::RgbaImage::new(self.view[0] as u32, self.view[1] as u32);
        let w = self.view[0] as usize;
        let h = self.view[1] as usize;

        let mut image = ImgVec::new(
            vec![
                RGBA8 {
                    r: 255,
                    g: 255,
                    b: 255,
                    a: 255
                };
                w * h
            ],
            w,
            h,
        );

        unsafe {
            self.context.read_pixels(
                0,
                0,
                self.view[0] as i32,
                self.view[1] as i32,
                glow::RGBA,
                glow::UNSIGNED_BYTE,
                glow::PixelPackData::Slice(image.buf_mut().align_to_mut().1),
            );
        }

        let mut flipped = Vec::with_capacity(w * h);

        for row in image.rows().rev() {
            flipped.extend_from_slice(row);
        }

        Ok(ImgVec::new(flipped, w, h))
    }
}

impl Drop for OpenGl {
    fn drop(&mut self) {
        if let Some(vert_arr) = self.vert_arr {
            unsafe {
                self.context.delete_vertex_array(vert_arr);
            }
        }

        if let Some(vert_buff) = self.vert_buff {
            unsafe {
                self.context.delete_buffer(vert_buff);
            }
        }
    }
}