rsx_lib_gl.cpp 95.8 KB
Newer Older
ggdrt's avatar
ggdrt committed
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
#include "rsx_lib_gl.h"

#include <stdint.h>
#include <string.h>
#include <stdlib.h> /* exit() */
#include <stddef.h> /* offsetof() */

#include <stdexcept>

#include <glsm/glsmsym.h>

#include <boolean.h>

#include <glsm/glsmsym.h>
#include <vector>
#include <cstdio>
#include <stdint.h>

#include <map>
#include <string>
#include <algorithm>

#include "mednafen/mednafen.h"
#include "mednafen/psx/gpu.h"
#include "libretro.h"
#include "libretro_options.h"

#include "rsx/rsx_intf.h" //enums

#define DRAWBUFFER_IS_EMPTY(x)           ((x)->map_index == 0)
#define DRAWBUFFER_REMAINING_CAPACITY(x) ((x)->capacity - (x)->map_index)
#define DRAWBUFFER_NEXT_INDEX(x)         ((x)->map_start + (x)->map_index)

#ifndef GL_MAP_INVALIDATE_RANGE_BIT
#define GL_MAP_INVALIDATE_RANGE_BIT       0x000
#endif

#include "shaders_gl/command_vertex.glsl.h"
#include "shaders_gl/command_fragment.glsl.h"
#define FILTER_XBR
#include "shaders_gl/command_fragment.glsl.h"
#include "shaders_gl/command_vertex.glsl.h"
#undef FILTER_XBR
#define FILTER_SABR
#include "shaders_gl/command_fragment.glsl.h"
#undef FILTER_SABR
#define FILTER_BILINEAR
#include "shaders_gl/command_fragment.glsl.h"
#undef FILTER_BILINEAR
#define FILTER_3POINT
#include "shaders_gl/command_fragment.glsl.h"
#undef FILTER_3POINT
#define FILTER_JINC2
#include "shaders_gl/command_fragment.glsl.h"
#undef FILTER_JINC2
#include "shaders_gl/output_vertex.glsl.h"
#include "shaders_gl/output_fragment.glsl.h"
#include "shaders_gl/image_load_vertex.glsl.h"
#include "shaders_gl/image_load_fragment.glsl.h"

#include "libretro.h"
#include "libretro_options.h"

#if 0 || defined(__APPLE__)
#define NEW_COPY_RECT
static const GLushort indices[6] = {0, 1, 2, 2, 1, 3};
#else
static const GLushort indices[6] = {0, 1, 2, 1, 2, 3};
#endif

#define VRAM_WIDTH_PIXELS 1024
#define VRAM_HEIGHT 512
#define VRAM_PIXELS (VRAM_WIDTH_PIXELS * VRAM_HEIGHT)

extern retro_log_printf_t log_cb;

/* How many vertices we buffer before forcing a draw. Since the
 * indexes are stored on 16bits we need to make sure that the length
 * multiplied by 3 (for triple buffering) doesn't overflow 0xffff. */
static const unsigned int VERTEX_BUFFER_LEN = 0x4000;

/* Maximum number of indices for a vertex buffer. Since quads have
 * two duplicated vertices it can be up to 3/2 the vertex buffer
 * length */
static const unsigned int INDEX_BUFFER_LEN = ((VERTEX_BUFFER_LEN * 3 + 1) / 2);

typedef std::map<std::string, GLint> UniformMap;

enum VideoClock {
   VideoClock_Ntsc,
   VideoClock_Pal
};

enum FilterMode {
   FILTER_MODE_NEAREST,
   FILTER_MODE_SABR,
   FILTER_MODE_XBR,
   FILTER_MODE_BILINEAR,
   FILTER_MODE_3POINT,
   FILTER_MODE_JINC2
};

/* State machine dealing with OpenGL context
 * destruction/reconstruction */
enum GlState
{
   /* OpenGL context is ready */
   GlState_Valid,
   /* OpenGL context has been destroyed (or is not created yet) */
   GlState_Invalid
};

enum SemiTransparencyMode {
   /* Source / 2 + destination / 2 */
   SemiTransparencyMode_Average = 0,
   /* Source + destination */
   SemiTransparencyMode_Add = 1,
   /* Destination - source */
   SemiTransparencyMode_SubtractSource = 2,
   /* Destination + source / 4 */
   SemiTransparencyMode_AddQuarterSource = 3,
};

struct Program
{
   GLuint id;
   /* Hash map of all the active uniforms in this program */
   UniformMap uniforms;
   char *info_log;
};

struct Shader
{
   GLuint id;
   char *info_log;
};

struct Attribute
{
   char name[32];
   size_t offset;
   /* Attribute type (BYTE, UNSIGNED_SHORT, FLOAT etc...) */
   GLenum type;
   GLint components;
};

struct CommandVertex {
   /* Position in PlayStation VRAM coordinates */
   float position[4];
   /* RGB color, 8bits per component */
   uint8_t color[3];
   /* Texture coordinates within the page */
   uint16_t texture_coord[2];
   /* Texture page (base offset in VRAM used for texture lookup) */
   uint16_t texture_page[2];
   /* Color Look-Up Table (palette) coordinates in VRAM */
   uint16_t clut[2];
   /* Blending mode: 0: no texture, 1: raw-texture, 2: texture-blended */
   uint8_t texture_blend_mode;
   /* Right shift from 16bits: 0 for 16bpp textures, 1 for 8bpp, 2
    * for 4bpp */
   uint8_t depth_shift;
   /* True if dithering is enabled for this primitive */
   uint8_t dither;
   /* 0: primitive is opaque, 1: primitive is semi-transparent */
   uint8_t semi_transparent;
   /* Texture limits of primtive */
   uint16_t texture_limits[4];
   /* Texture window mask/OR values */
   uint8_t texture_window[4];


   static std::vector<Attribute> attributes();
};

struct OutputVertex {
   /* Vertex position on the screen */
   float position[2];
   /* Corresponding coordinate in the framebuffer */
   uint16_t fb_coord[2];

   static std::vector<Attribute> attributes();
};

struct ImageLoadVertex {
   /* Vertex position in VRAM */
   uint16_t position[2];

   static std::vector<Attribute> attributes();
};

struct GlDisplayRect
{
   /* Analogous to DisplayRect in the Vulkan
    * renderer,but specified in native unscaled
    * glViewport coordinates. */
   int32_t x;
   int32_t y;
   uint32_t width;
   uint32_t height;
};

struct DrawConfig
{
   uint16_t display_top_left[2];
   uint16_t display_resolution[2];
   bool     display_24bpp;
   bool     display_off;
   int16_t  draw_offset[2];
   uint16_t draw_area_top_left[2];
   uint16_t draw_area_bot_right[2];
   uint16_t display_area_hrange[2];
   uint16_t display_area_vrange[2];
   bool     is_pal;
   bool     is_480i;
};

struct Texture
{
   GLuint id;
   uint32_t width;
   uint32_t height;
};

struct Framebuffer
{
   GLuint id;
   struct Texture _color_texture;
};

struct PrimitiveBatch {
   SemiTransparencyMode transparency_mode;
   /* GL_TRIANGLES or GL_LINES */
   GLenum draw_mode;
   bool opaque;
   bool set_mask;
   bool mask_test;
   /* First index */
   unsigned first;
   /* Count of indices */
   unsigned count;
};

template<typename T>
struct DrawBuffer
{
   /* OpenGL name for this buffer */
   GLuint id;
   /* Vertex Array Object containing the bindings for this
    * buffer. I'm assuming that each VAO will only use a single
    * buffer for simplicity. */
   GLuint vao;
   /* Program used to draw this buffer */
   Program* program;
   /* Currently mapped buffer range (write-only) */
   T *map;
   /* Number of elements T mapped at once in 'map' */
   size_t capacity;
   /* Index one-past the last element stored in 'map', relative to
    * the first element in 'map' */
   size_t map_index;
   /* Absolute offset of the 1st mapped element in the current
    * buffer relative to the beginning of the GL storage. */
   size_t map_start;
};

struct GlRenderer {
   /* Buffer used to handle PlayStation GPU draw commands */
   DrawBuffer<CommandVertex>* command_buffer;
   /* Buffer used to draw to the frontend's framebuffer */
   DrawBuffer<OutputVertex>* output_buffer;
   /* Buffer used to copy textures from 'fb_texture' to 'fb_out' */
   DrawBuffer<ImageLoadVertex>* image_load_buffer;

   GLushort vertex_indices[INDEX_BUFFER_LEN];
   /* Primitive type for the vertices in the command buffers
    * (TRIANGLES or LINES) */
   GLenum command_draw_mode;
   unsigned vertex_index_pos;
   std::vector<PrimitiveBatch> batches;
   /* Whether we're currently pushing opaque primitives or not */
   bool opaque;
   /* Current semi-transparency mode */
   SemiTransparencyMode semi_transparency_mode;
   /* Polygon mode (for wireframe) */
   GLenum command_polygon_mode;
   /* Texture used to store the VRAM for texture mapping */
   DrawConfig config;
   /* Framebuffer used as a shader input for texturing draw commands */
   Texture fb_texture;
   /* Framebuffer used as an output when running draw commands */
   Texture fb_out;
   /* Depth buffer for fb_out */
   Texture fb_out_depth;
   /* Current resolution of the frontend's framebuffer */
   uint32_t frontend_resolution[2];
   /* Current internal resolution upscaling factor */
   uint32_t internal_upscaling;
   /* Current internal color depth */
   uint8_t internal_color_depth;
   /* Counter for preserving primitive draw order in the z-buffer
    * since we draw semi-transparent primitives out-of-order. */
   int16_t primitive_ordering;
   /* Texture window mask/OR values */
   uint8_t tex_x_mask;
   uint8_t tex_x_or;
   uint8_t tex_y_mask;
   uint8_t tex_y_or;

   bool set_mask;
   bool mask_test;

   uint8_t filter_type;

   /* When true we display the entire VRAM buffer instead of just
    * the visible area */
   bool display_vram;

   /* Display Mode - GP1(08h) */
   enum width_modes curr_width_mode;

   /* When true we perform no horizontal padding */
   bool crop_overscan;

   /* Experimental offset feature */
   int32_t image_offset_cycles;

328
329
330
   /* Image Crop option */
   unsigned image_crop;

ggdrt's avatar
ggdrt committed
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
   /* Scanline core options */
   int32_t initial_scanline;
   int32_t initial_scanline_pal;
   int32_t last_scanline;
   int32_t last_scanline_pal;
};

struct RetroGl
{
   GlRenderer *state_data;
   GlState state;
   VideoClock video_clock;
   bool inited;
};

static DrawConfig persistent_config = {
   {0, 0},         /* display_top_left */
   {MEDNAFEN_CORE_GEOMETRY_MAX_W, MEDNAFEN_CORE_GEOMETRY_MAX_H}, /* display_resolution */
   false,          /* display_24bpp */
   true,           /* display_off */
   {0, 0},         /* draw_area_top_left */
   {0, 0},         /* draw_area_dimensions */
   {0, 0},         /* draw_offset */
   {0x200, 0xC00}, /* display_area_hrange (hardware reset values)*/
   {0x10, 0x100},  /* display_area_vrange (hardware reset values)*/ 
   false,          /* is_pal */
   false,          /* is_480i */
};

static RetroGl static_renderer;

static bool has_software_fb = false;

extern "C" unsigned char widescreen_hack;
365
extern "C" unsigned char widescreen_hack_aspect_ratio_setting;
366
367
extern "C" bool content_is_pal;
extern "C" int aspect_ratio_setting;
ggdrt's avatar
ggdrt committed
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

#ifdef __cplusplus
extern "C"
{
#endif
   extern retro_environment_t environ_cb;
   extern retro_video_refresh_t video_cb;
#ifdef __cplusplus
}
#endif


#ifdef DEBUG
static void get_error(const char *msg)
{
   GLenum error = glGetError();
   switch (error)
   {
      case GL_NO_ERROR:
         log_cb(RETRO_LOG_INFO, "GL error flag: GL_NO_ERROR [%s]\n", msg);
         return;
      case GL_INVALID_ENUM:
         log_cb(RETRO_LOG_ERROR, "GL error flag: GL_INVALID_ENUM [%s]\n", msg);
         break;
      case GL_INVALID_VALUE:
         log_cb(RETRO_LOG_ERROR, "GL error flag: GL_INVALID_VALUE [%s]\n", msg);
         break;
      case GL_INVALID_FRAMEBUFFER_OPERATION:
         log_cb(RETRO_LOG_ERROR, "GL error flag: GL_INVALID_FRAMEBUFFER_OPERATION [%s]\n", msg);
         break;
      case GL_OUT_OF_MEMORY:
         log_cb(RETRO_LOG_ERROR, "GL error flag: GL_OUT_OF_MEMORY [%s]\n", msg);
         break;
      case GL_STACK_UNDERFLOW:
         log_cb(RETRO_LOG_ERROR, "GL error flag: GL_STACK_UNDERFLOW [%s]\n", msg);
         break;
      case GL_STACK_OVERFLOW:
         log_cb(RETRO_LOG_ERROR, "GL error flag: GL_STACK_OVERFLOW [%s]\n", msg);
         break;
      case GL_INVALID_OPERATION:
         log_cb(RETRO_LOG_ERROR, "GL error flag: GL_INVALID_OPERATION [%s]\n", msg);
         break;
      default:
         log_cb(RETRO_LOG_ERROR, "GL error flag: %d [%s]\n", (int) error, msg);
         break;
   }

   /* glGetError should always be called in a loop, until
    * it returns GL_NO_ERROR, if all error flags are to be reset. */
   while (error != GL_NO_ERROR)
      error = glGetError();
}
#endif

static bool Shader_init(
      struct Shader *shader,
      const char* source,
      GLenum shader_type)
{
   GLint status;
   GLint log_len = 0;
   GLuint id;

   shader->info_log = NULL;
   id               = glCreateShader(shader_type);

   if (id == 0)
   {
      log_cb(RETRO_LOG_ERROR, "An error occured creating the shader object\n");
      return false;
   }

   glShaderSource( id,
         1,
         &source,
         NULL);
   glCompileShader(id);

   status = (GLint) GL_FALSE;
   glGetShaderiv(id, GL_COMPILE_STATUS, &status);
   glGetShaderiv(id, GL_INFO_LOG_LENGTH, &log_len);

   if (log_len > 0)
   {
      GLsizei len;

      shader->info_log = (char*)malloc(log_len);
      len              = (GLsizei) log_len;

      glGetShaderInfoLog(id,
            len,
            &log_len,
            (char*)shader->info_log);

      if (log_len > 0)
         shader->info_log[log_len - 1] = '\0';
   }

   if (status == GL_FALSE)
   {
      log_cb(RETRO_LOG_ERROR, "Shader_init() - Shader compilation failed:\n%s\n", source);


Libretro-Admin's avatar
Libretro-Admin committed
471
      log_cb(RETRO_LOG_DEBUG, "Shader info log:\n%s\n", shader->info_log);
ggdrt's avatar
ggdrt committed
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

      return false;
   }

   shader->id = id;

   return true;
}

static void get_program_info_log(Program *pg, GLuint id)
{
   GLsizei len;
   GLint log_len = 0;

   glGetProgramiv(id, GL_INFO_LOG_LENGTH, &log_len);

   if (log_len <= 0)
      return;

   pg->info_log = (char*)malloc(log_len);
   len          = (GLsizei) log_len;

   glGetProgramInfoLog(id,
         len,
         &log_len,
         (char*)pg->info_log);

   if (log_len <= 0)
      return;

   pg->info_log[log_len - 1] = '\0';
}

static UniformMap load_program_uniforms(GLuint program)
{
   size_t u;
   UniformMap uniforms;
   /* Figure out how long a uniform name can be */
   GLint max_name_len = 0;
   GLint n_uniforms   = 0;

   glGetProgramiv( program,
         GL_ACTIVE_UNIFORMS,
         &n_uniforms );

   glGetProgramiv( program,
         GL_ACTIVE_UNIFORM_MAX_LENGTH,
         &max_name_len);

   for (u = 0; u < n_uniforms; ++u)
   {
      char name[256];
      size_t name_len = max_name_len;
      GLsizei len     = 0;
      GLint size      = 0;
      GLenum ty       = 0;

      glGetActiveUniform( program,
            (GLuint) u,
            (GLsizei) name_len,
            &len,
            &size,
            &ty,
            (char*) name);

      if (len <= 0)
      {
         log_cb(RETRO_LOG_WARN, "Ignoring uniform name with size %d\n", len);
         continue;
      }

      /* Retrieve the location of this uniform */
      GLint location = glGetUniformLocation(program, (const char*) name);

      if (location < 0)
      {
         log_cb(RETRO_LOG_WARN, "Uniform \"%s\" doesn't have a location", name);
         continue;
      }

      uniforms[name] = location;
   }

   return uniforms;
}


static bool Program_init(
      Program *program,
      Shader* vertex_shader,
      Shader* fragment_shader)
{
   GLint status;
   GLuint id;

   program->info_log = NULL;

   id                = glCreateProgram();

   if (id == 0)
   {
      log_cb(RETRO_LOG_ERROR, "Program_init() - glCreateProgram() returned 0\n");
      return false;
   }

   glAttachShader(id, vertex_shader->id);
   glAttachShader(id, fragment_shader->id);

   glLinkProgram(id);

   glDetachShader(id, vertex_shader->id);
   glDetachShader(id, fragment_shader->id);

   /* Check if the program linking was successful */
   status = GL_FALSE;
   glGetProgramiv(id, GL_LINK_STATUS, &status);
   get_program_info_log(program, id);

   if (status == GL_FALSE)
   {
      log_cb(RETRO_LOG_ERROR, "Program_init() - glLinkProgram() returned GL_FALSE\n");
      log_cb(RETRO_LOG_ERROR, "Program info log:\n%s\n", program->info_log);

      return false;
   }

   UniformMap uniforms = load_program_uniforms(id);

   program->id       = id;
   program->uniforms = uniforms;

Libretro-Admin's avatar
Libretro-Admin committed
603
   log_cb(RETRO_LOG_DEBUG, "Binding program for first time: %d\n", id);
ggdrt's avatar
ggdrt committed
604
605
606

   glUseProgram(id);

Libretro-Admin's avatar
Libretro-Admin committed
607
   log_cb(RETRO_LOG_DEBUG, "Unbinding program for first time: %d\n", id);
ggdrt's avatar
ggdrt committed
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

   glUseProgram(0);

   return true;
}

static void Program_free(Program *program)
{
   if (!program)
      return;

   if (glIsProgram(program->id))
      glDeleteProgram(program->id);
   if (program->info_log)
      free(program->info_log);
}

template<typename T>
static void DrawBuffer_enable_attribute(DrawBuffer<T> *drawbuffer, const char* attr)
{
   GLint index = glGetAttribLocation(drawbuffer->program->id, attr);

   if (index < 0)
      return;

   glBindVertexArray(drawbuffer->vao);
   glEnableVertexAttribArray(index);
}

template<typename T>
static void DrawBuffer_disable_attribute(DrawBuffer<T> *drawbuffer, const char* attr)
{
   GLint index = glGetAttribLocation(drawbuffer->program->id, attr);

   if (index < 0)
      return;

   glBindVertexArray(drawbuffer->vao);
   glDisableVertexAttribArray(index);
}

#ifdef DEBUG
#define DrawBuffer_push_slice(drawbuffer, slice, n, len) \
   assert(n <= DRAWBUFFER_REMAINING_CAPACITY(drawbuffer)); \
   assert(drawbuffer->map != NULL); \
   memcpy(drawbuffer->map + drawbuffer->map_index, slice, n * len); \
   drawbuffer->map_index += n;
#else
#define DrawBuffer_push_slice(drawbuffer, slice, n, len) \
   memcpy(drawbuffer->map + drawbuffer->map_index, slice, n * len); \
   drawbuffer->map_index += n;
#endif

template<typename T>
static void DrawBuffer_draw(DrawBuffer<T> *drawbuffer, GLenum mode)
{
   glBindBuffer(GL_ARRAY_BUFFER, drawbuffer->id);
   /* Unmap the active buffer */
   glUnmapBuffer(GL_ARRAY_BUFFER);

   drawbuffer->map = NULL;

   /* The VAO needs to be bound now or else glDrawArrays
    * errors out on some systems */
   glBindVertexArray(drawbuffer->vao);
   glUseProgram(drawbuffer->program->id);

   /* Length in number of vertices */
   glDrawArrays(mode, drawbuffer->map_start, drawbuffer->map_index);

   drawbuffer->map_start += drawbuffer->map_index;
   drawbuffer->map_index  = 0;

   DrawBuffer_map__no_bind(drawbuffer);
}

/* Map the buffer for write-only access */
template<typename T>
static void DrawBuffer_map__no_bind(DrawBuffer<T> *drawbuffer)
{
   GLintptr offset_bytes;
   void *m                = NULL;
   size_t element_size    = sizeof(T);
   GLsizeiptr buffer_size = drawbuffer->capacity * element_size;

   glBindBuffer(GL_ARRAY_BUFFER, drawbuffer->id);

   /* If we're already mapped something's wrong */
   assert(drawbuffer->map == NULL);

   /* We don't have enough room left to remap 'capacity',
    * start back from the beginning of the buffer. */
   if (drawbuffer->map_start > 2 * drawbuffer->capacity)
      drawbuffer->map_start = 0;

   offset_bytes = drawbuffer->map_start * element_size;

   m = glMapBufferRange(GL_ARRAY_BUFFER,
         offset_bytes,
         buffer_size,
         GL_MAP_WRITE_BIT |
         GL_MAP_INVALIDATE_RANGE_BIT);

   assert(m != NULL);

   drawbuffer->map = reinterpret_cast<T *>(m);
}

template<typename T>
static void DrawBuffer_free(DrawBuffer<T> *drawbuffer)
{
   if (!drawbuffer)
      return;

   /* Unmap the active buffer */
   glBindBuffer(GL_ARRAY_BUFFER, drawbuffer->id);
   glUnmapBuffer(GL_ARRAY_BUFFER);

   Program_free(drawbuffer->program);
   glDeleteBuffers(1, &drawbuffer->id);
   glDeleteVertexArrays(1, &drawbuffer->vao);

   delete drawbuffer->program;

   drawbuffer->map       = NULL;
   drawbuffer->id        = 0;
   drawbuffer->vao       = 0;
   drawbuffer->program   = NULL;
   drawbuffer->capacity  = 0;
   drawbuffer->map_index = 0;
   drawbuffer->map_start = 0;
}

template<typename T>
static void DrawBuffer_bind_attributes(DrawBuffer<T> *drawbuffer)
{
   unsigned i;
   GLint nVertexAttribs;

   glBindVertexArray(drawbuffer->vao);

   /* ARRAY_BUFFER is captured by VertexAttribPointer */
   glBindBuffer(GL_ARRAY_BUFFER, drawbuffer->id);

   std::vector<Attribute> attrs = T::attributes();
   GLint element_size = (GLint) sizeof( T );

   /* speculative: attribs enabled on VAO=0 (disabled) get applied to the VAO when created initially
    * as a core, we don't control the state entirely at this point. frontend may have enabled attribs.
    * we need to make sure they're all disabled before then re-enabling the attribs we want
    * (solves crashes on some drivers/compilers due to accidentally enabled attribs) */
   glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &nVertexAttribs);

   for (i = 0; i < nVertexAttribs; i++)
      glDisableVertexAttribArray(i);

   for (std::vector<Attribute>::iterator it(attrs.begin()); it != attrs.end(); ++it)
   {
      Attribute& attr = *it;
      GLint index     = glGetAttribLocation(drawbuffer->program->id, attr.name);

      /* Don't error out if the shader doesn't use this
       * attribute, it could be caused by shader
       * optimization if the attribute is unused for
       * some reason. */
      if (index < 0)
         continue;

      glEnableVertexAttribArray((GLuint) index);

      /* This captures the buffer so that we don't have to bind it
       * when we draw later on, we'll just have to bind the vao */
      switch (attr.type)
      {
         case GL_BYTE:
         case GL_UNSIGNED_BYTE:
         case GL_SHORT:
         case GL_UNSIGNED_SHORT:
         case GL_INT:
         case GL_UNSIGNED_INT:
            glVertexAttribIPointer( index,
                  attr.components,
                  attr.type,
                  element_size,
                  (GLvoid*)attr.offset);
            break;
         case GL_FLOAT:
            glVertexAttribPointer(  index,
                  attr.components,
                  attr.type,
                  GL_FALSE,
                  element_size,
                  (GLvoid*)attr.offset);
            break;
         case GL_DOUBLE:
            glVertexAttribLPointer( index,
                  attr.components,
                  attr.type,
                  element_size,
                  (GLvoid*)attr.offset);
            break;
      }
   }
}

template<typename T>
static void DrawBuffer_new(DrawBuffer<T> *drawbuffer,
      const char *vertex_shader, const char *fragment_shader, size_t capacity)
{
   GLuint id = 0;
   size_t element_size = sizeof(T);
   Shader vs, fs;
   Program* program    = new Program;

   Shader_init(&vs, vertex_shader, GL_VERTEX_SHADER);
   Shader_init(&fs, fragment_shader, GL_FRAGMENT_SHADER);

   if (!Program_init(program, &vs, &fs))
Libretro-Admin's avatar
Libretro-Admin committed
826
827
   {
      delete program;
ggdrt's avatar
ggdrt committed
828
      return;
Libretro-Admin's avatar
Libretro-Admin committed
829
   }
ggdrt's avatar
ggdrt committed
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
1244
1245
1246
1247

   /* Program owns the two pointers, so we clean them up now */
   glDeleteShader(fs.id);
   glDeleteShader(vs.id);
   if (fs.info_log)
      free(fs.info_log);
   if (vs.info_log)
      free(vs.info_log);

   glGenVertexArrays(1, &id);

   drawbuffer->map       = NULL;
   drawbuffer->vao       = id;

   id                    = 0;

   /* Generate the buffer object */
   glGenBuffers(1, &id);

   drawbuffer->program  = program;
   drawbuffer->capacity = capacity;
   drawbuffer->id       = id;

   /* Create and map the buffer */
   glBindBuffer(GL_ARRAY_BUFFER, id);

   /* We allocate enough space for 3 times the buffer space and
    * we only remap one third of it at a time */
   GLsizeiptr storage_size = drawbuffer->capacity * element_size * 3;

   /* Since we store indexes in unsigned shorts we want to make
    * sure the entire buffer is indexable. */
   assert(drawbuffer->capacity * 3 <= 0xffff);

   glBufferData(GL_ARRAY_BUFFER, storage_size, NULL, GL_DYNAMIC_DRAW);

   DrawBuffer_bind_attributes<T>(drawbuffer);

   drawbuffer->map_index = 0;
   drawbuffer->map_start = 0;

   DrawBuffer_map__no_bind(drawbuffer);
}

static void Framebuffer_init(struct Framebuffer *fb,
      struct Texture* color_texture)
{
   GLuint id = 0;
   glGenFramebuffers(1, &id);

   fb->id                    = id;

   fb->_color_texture.id     = color_texture->id;
   fb->_color_texture.width  = color_texture->width;
   fb->_color_texture.height = color_texture->height;

   glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fb->id);

   glFramebufferTexture(   GL_DRAW_FRAMEBUFFER,
                           GL_COLOR_ATTACHMENT0,
                           color_texture->id,
                           0);

   GLenum col_attach_0 = GL_COLOR_ATTACHMENT0;

   glDrawBuffers(1, &col_attach_0);
   glViewport( 0,
               0,
               (GLsizei) color_texture->width,
               (GLsizei) color_texture->height);
}

static void Texture_init(
      struct Texture *tex,
      uint32_t width,
      uint32_t height,
      GLenum internal_format)
{
   GLuint id = 0;

   glGenTextures(1, &id);
   glBindTexture(GL_TEXTURE_2D, id);
   glTexStorage2D(GL_TEXTURE_2D,
                  1,
                  internal_format,
                  (GLsizei) width,
                  (GLsizei) height);

   tex->id     = id;
   tex->width  = width;
   tex->height = height;
}

static void Texture_set_sub_image_window(
      struct Texture *tex,
      uint16_t top_left[2],
      uint16_t resolution[2],
      size_t row_len,
      GLenum format,
      GLenum ty,
      uint16_t* data)
{
   uint16_t x         = top_left[0];
   uint16_t y         = top_left[1];

   size_t index       = ((size_t) y) * row_len + ((size_t) x);

   /* TODO - Am I indexing data out of bounds? */
   uint16_t* sub_data = &( data[index] );

   glPixelStorei(GL_UNPACK_ROW_LENGTH, (GLint) row_len);
   glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
   glBindTexture(GL_TEXTURE_2D, tex->id);
   glTexSubImage2D(  GL_TEXTURE_2D,
                     0,
                     (GLint) top_left[0],
                     (GLint) top_left[1],
                     (GLsizei) resolution[0],
                     (GLsizei) resolution[1],
                     format,
                     ty,
                     (void*)sub_data);
   glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
}

template<typename T>
static DrawBuffer<T>* DrawBuffer_build( const char* vertex_shader,
      const char* fragment_shader,
      size_t capacity)
{
   DrawBuffer<T> *t = new DrawBuffer<T>;
   DrawBuffer_new<T>(t, vertex_shader, fragment_shader, capacity);

   return t;
}

static void GlRenderer_draw(GlRenderer *renderer)
{
   if (!renderer || static_renderer.state == GlState_Invalid)
      return;

   Framebuffer _fb;
   int16_t x = renderer->config.draw_offset[0];
   int16_t y = renderer->config.draw_offset[1];

   if (renderer->command_buffer->program)
   {
      glUseProgram(renderer->command_buffer->program->id);
      glUniform2i(renderer->command_buffer->program->uniforms["offset"], (GLint)x, (GLint)y);
      /* We use texture unit 0 */
      glUniform1i(renderer->command_buffer->program->uniforms["fb_texture"], 0);
   }

   /* Bind the out framebuffer */
   Framebuffer_init(&_fb, &renderer->fb_out);

   glFramebufferTexture(   GL_DRAW_FRAMEBUFFER,
         GL_DEPTH_STENCIL_ATTACHMENT,
         renderer->fb_out_depth.id,
         0);

   glClear(GL_DEPTH_BUFFER_BIT);

   glStencilMask(1);
   glEnable(GL_STENCIL_TEST);

   /* Bind and unmap the command buffer */
   glBindBuffer(GL_ARRAY_BUFFER, renderer->command_buffer->id);
   glUnmapBuffer(GL_ARRAY_BUFFER);

   /* The VAO needs to be bound here or the glDrawElements calls
    * will error out on some systems */
   glBindVertexArray(renderer->command_buffer->vao);

   renderer->command_buffer->map = NULL;

   if (!renderer->batches.empty())
      renderer->batches.back().count = renderer->vertex_index_pos
         - renderer->batches.back().first;

   for (std::vector<PrimitiveBatch>::iterator it =
         renderer->batches.begin();
         it != renderer->batches.end();
         ++it)
   {
      /* Mask bits */
      if (it->set_mask)
         glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
      else
         glStencilOp(GL_KEEP, GL_KEEP, GL_ZERO);

      if (it->mask_test)
         glStencilFunc(GL_NOTEQUAL, 1, 1);
      else
         glStencilFunc(GL_ALWAYS, 1, 1);

      /* Blending */
      bool opaque = it->opaque;
      if (renderer->command_buffer->program)
         glUniform1ui(renderer->command_buffer->program->uniforms["draw_semi_transparent"], !opaque);
      if (opaque)
         glDisable(GL_BLEND);
      else
      {
         glEnable(GL_BLEND);

         GLenum blend_func = GL_FUNC_ADD;
         GLenum blend_src = GL_CONSTANT_ALPHA;
         GLenum blend_dst = GL_CONSTANT_ALPHA;

         switch (it->transparency_mode)
         {
            /* 0.5xB + 0.5 x F */
            case SemiTransparencyMode_Average:
               blend_func = GL_FUNC_ADD;
               /* Set to 0.5 with glBlendColor */
               blend_src = GL_CONSTANT_ALPHA;
               blend_dst = GL_CONSTANT_ALPHA;
               break;
            /* 1.0xB + 1.0 x F */
            case SemiTransparencyMode_Add:
               blend_func = GL_FUNC_ADD;
               blend_src = GL_ONE;
               blend_dst = GL_ONE;
               break;
            /* 1.0xB - 1.0 x F */
            case SemiTransparencyMode_SubtractSource:
               blend_func = GL_FUNC_REVERSE_SUBTRACT;
               blend_src = GL_ONE;
               blend_dst = GL_ONE;
               break;
            case SemiTransparencyMode_AddQuarterSource:
               blend_func = GL_FUNC_ADD;
               blend_src = GL_CONSTANT_COLOR;
               blend_dst = GL_ONE;
               break;
         }

         glBlendFuncSeparate(blend_src, blend_dst, GL_ONE, GL_ZERO);
         glBlendEquationSeparate(blend_func, GL_FUNC_ADD);
      }

      /* Drawing */
      if (!DRAWBUFFER_IS_EMPTY(renderer->command_buffer))
      {
         /* This method doesn't call prepare_draw/finalize_draw itself, it
          * must be handled by the caller. This is because this command
          * can be called several times on the same buffer (i.e. multiple
          * draw calls between the prepare/finalize) */
         glDrawElements(it->draw_mode, it->count, GL_UNSIGNED_SHORT, &renderer->vertex_indices[it->first]);
      }
   }

   glDisable(GL_STENCIL_TEST);

   renderer->command_buffer->map_start += renderer->command_buffer->map_index;
   renderer->command_buffer->map_index  = 0;
   DrawBuffer_map__no_bind(renderer->command_buffer);

   renderer->primitive_ordering = 0;
   renderer->batches.clear();
   renderer->opaque = false;
   renderer->vertex_index_pos = 0;
   renderer->mask_test = false;
   renderer->set_mask = false;

   glDeleteFramebuffers(1, &_fb.id);
}

static void GlRenderer_upload_textures(
      GlRenderer *renderer,
      uint16_t top_left[2],
      uint16_t dimensions[2],
      uint16_t pixel_buffer[VRAM_PIXELS])
{
   if (!renderer)
      return;

   if (!DRAWBUFFER_IS_EMPTY(renderer->command_buffer))
      GlRenderer_draw(renderer);

   glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
   glBindTexture(GL_TEXTURE_2D, renderer->fb_texture.id);
   glTexSubImage2D(  GL_TEXTURE_2D,
         0,
         (GLint) top_left[0],
         (GLint) top_left[1],
         (GLsizei) dimensions[0],
         (GLsizei) dimensions[1],
         GL_RGBA,
         GL_UNSIGNED_SHORT_1_5_5_5_REV,
         (void*)pixel_buffer);

   uint16_t x_start    = top_left[0];
   uint16_t x_end      = x_start + dimensions[0];
   uint16_t y_start    = top_left[1];
   uint16_t y_end      = y_start + dimensions[1];

   ImageLoadVertex slice[4] =
   {
      {   {x_start,   y_start }   },
      {   {x_end,     y_start }   },
      {   {x_start,   y_end   }   },
      {   {x_end,     y_end   }   }
   };

   if (renderer->image_load_buffer)
   {
      DrawBuffer_push_slice(renderer->image_load_buffer, &slice, 4,
            sizeof(ImageLoadVertex));

      if (renderer->image_load_buffer->program)
      {
         /* fb_texture is always at 1x */
         glUseProgram(renderer->image_load_buffer->program->id);
         glUniform1i(renderer->image_load_buffer->program->uniforms["fb_texture"], 0);
         glUniform1ui(renderer->image_load_buffer->program->uniforms["internal_upscaling"], 1);

         glUseProgram(renderer->command_buffer->program->id);
         glUniform1i(renderer->command_buffer->program->uniforms["fb_texture"], 0);
      }
   }

   glDisable(GL_SCISSOR_TEST);
   glDisable(GL_BLEND);
   glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

   /* Bind the output framebuffer */
   Framebuffer _fb;
   Framebuffer_init(&_fb, &renderer->fb_out);

   if (!DRAWBUFFER_IS_EMPTY(renderer->image_load_buffer))
      DrawBuffer_draw(renderer->image_load_buffer, GL_TRIANGLE_STRIP);

   glPolygonMode(GL_FRONT_AND_BACK, renderer->command_polygon_mode);
   glEnable(GL_SCISSOR_TEST);

#ifdef DEBUG
   get_error("GlRenderer_upload_textures");
#endif
   glDeleteFramebuffers(1, &_fb.id);
}

static void get_variables(uint8_t *upscaling, bool *display_vram)
{
   struct retro_variable var = {0};

   var.key = BEETLE_OPT(internal_resolution);
   if (upscaling)
   {
      if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
      {
         /* Same limitations as libretro.cpp */
         *upscaling = var.value[0] -'0';
         if (var.value[1] != 'x')
         {
            *upscaling  = (var.value[0] - '0') * 10;
            *upscaling += var.value[1] - '0';
         }
      }
   }

   if (display_vram)
   {
      var.key = BEETLE_OPT(display_vram);
      if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
      {
         if (!strcmp(var.value, "enabled"))
            *display_vram = true;
         else
            *display_vram = false;
      }
   }
}

static bool GlRenderer_new(GlRenderer *renderer, DrawConfig config)
{
   DrawBuffer<CommandVertex>* command_buffer;
   uint8_t upscaling         = 1;
   bool display_vram         = false;
   struct retro_variable var = {0};
   uint16_t top_left[2]      = {0, 0};
   uint16_t dimensions[2]    = {
      (uint16_t) VRAM_WIDTH_PIXELS, (uint16_t) VRAM_HEIGHT};

   if (!renderer)
      return false;

   var.key = BEETLE_OPT(renderer_software_fb);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (!strcmp(var.value, "enabled"))
         has_software_fb = true;
      else
         has_software_fb = false;
   }
   else
      has_software_fb = true;

   get_variables(&upscaling, &display_vram);

   var.key = BEETLE_OPT(crop_overscan);
   bool crop_overscan = true;
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (!strcmp(var.value, "enabled"))
         crop_overscan = true;
      else if (!strcmp(var.value, "disabled"))
         crop_overscan = false;
   }

   int32_t image_offset_cycles = 0;
   var.key = BEETLE_OPT(image_offset_cycles);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      image_offset_cycles = atoi(var.value);
   }

1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
   unsigned image_crop = 0;
   var.key = BEETLE_OPT(image_crop);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (strcmp(var.value, "disabled") == 0)
         image_crop = 0;
      else
         image_crop = atoi(var.value);
   }

ggdrt's avatar
ggdrt committed
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
   int32_t initial_scanline = 0;
   var.key = BEETLE_OPT(initial_scanline);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      initial_scanline = atoi(var.value);
   }

   int32_t last_scanline = 239;
   var.key = BEETLE_OPT(last_scanline);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      last_scanline = atoi(var.value);
   }

   int32_t initial_scanline_pal = 0;
   var.key = BEETLE_OPT(initial_scanline_pal);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      initial_scanline_pal = atoi(var.value);
   }

   int32_t last_scanline_pal = 287;
   var.key = BEETLE_OPT(last_scanline_pal);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      last_scanline_pal = atoi(var.value);
   }

   var.key = BEETLE_OPT(filter);
   uint8_t filter = FILTER_MODE_NEAREST;
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (!strcmp(var.value, "nearest"))
         filter = FILTER_MODE_NEAREST;
      else if (!strcmp(var.value, "SABR"))
         filter = FILTER_MODE_SABR;
      else if (!strcmp(var.value, "xBR"))
         filter = FILTER_MODE_XBR;
      else if (!strcmp(var.value, "bilinear"))
         filter = FILTER_MODE_BILINEAR;
      else if (!strcmp(var.value, "3-point"))
         filter = FILTER_MODE_3POINT;
      else if (!strcmp(var.value, "JINC2"))
         filter = FILTER_MODE_JINC2;

      renderer->filter_type = filter;
   }

   var.key = BEETLE_OPT(depth);
   uint8_t depth = 16;
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (!strcmp(var.value, "32bpp"))
         depth = 32;
   }

   var.key = BEETLE_OPT(dither_mode);
   dither_mode dither_mode = DITHER_NATIVE;
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (!strcmp(var.value, "internal resolution"))
         dither_mode = DITHER_UPSCALED;
      else if (!strcmp(var.value, "disabled"))
         dither_mode  = DITHER_OFF;
   }

   var.key = BEETLE_OPT(wireframe);
   bool wireframe = false;
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (!strcmp(var.value, "enabled"))
         wireframe = true;
   }

Libretro-Admin's avatar
Libretro-Admin committed
1332
   log_cb(RETRO_LOG_DEBUG, "Building OpenGL state (%dx internal res., %dbpp)\n", upscaling, depth);
ggdrt's avatar
ggdrt committed
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455

   switch(renderer->filter_type)
   {
      case FILTER_MODE_SABR:
         command_buffer = DrawBuffer_build<CommandVertex>(
               command_vertex_xbr,
               command_fragment_sabr,
               VERTEX_BUFFER_LEN);
         break;
      case FILTER_MODE_XBR:
         command_buffer = DrawBuffer_build<CommandVertex>(
               command_vertex_xbr,
               command_fragment_xbr,
               VERTEX_BUFFER_LEN);
         break;
      case FILTER_MODE_BILINEAR:
         command_buffer = DrawBuffer_build<CommandVertex>(
               command_vertex,
               command_fragment_bilinear,
               VERTEX_BUFFER_LEN);
         break;
      case FILTER_MODE_3POINT:
         command_buffer = DrawBuffer_build<CommandVertex>(
               command_vertex,
               command_fragment_3point,
               VERTEX_BUFFER_LEN);
         break;
      case FILTER_MODE_JINC2:
         command_buffer = DrawBuffer_build<CommandVertex>(
               command_vertex,
               command_fragment_jinc2,
               VERTEX_BUFFER_LEN);
         break;
      case FILTER_MODE_NEAREST:
      default:
         command_buffer = DrawBuffer_build<CommandVertex>(
               command_vertex,
               command_fragment,
               VERTEX_BUFFER_LEN);
   }

   DrawBuffer<OutputVertex>* output_buffer =
      DrawBuffer_build<OutputVertex>(
            output_vertex,
            output_fragment,
            4);

   DrawBuffer<ImageLoadVertex>* image_load_buffer =
      DrawBuffer_build<ImageLoadVertex>(
            image_load_vertex,
            image_load_fragment,
            4);

   uint32_t native_width  = (uint32_t) VRAM_WIDTH_PIXELS;
   uint32_t native_height = (uint32_t) VRAM_HEIGHT;

   /* Texture holding the raw VRAM texture contents. We can't
    * meaningfully upscale it since most games use paletted
    * textures. */
   Texture_init(&renderer->fb_texture, native_width, native_height, GL_RGB5_A1);

   if (dither_mode == DITHER_OFF)
   {
      /* Dithering is superfluous when we increase the internal
      * color depth, but users asked for it */
      DrawBuffer_disable_attribute(command_buffer, "dither");
   }
   else
   {
      DrawBuffer_enable_attribute(command_buffer, "dither");
   }

   GLenum command_draw_mode = wireframe ? GL_LINE : GL_FILL;

   if (command_buffer->program)
   {
      uint32_t dither_scaling = dither_mode == DITHER_UPSCALED ? 1 : upscaling;

      glUseProgram(command_buffer->program->id);
      glUniform1ui(command_buffer->program->uniforms["dither_scaling"], dither_scaling);
   }

   GLenum texture_storage = GL_RGB5_A1;
   switch (depth)
   {
      case 16:
         texture_storage = GL_RGB5_A1;
         break;
      case 32:
         texture_storage = GL_RGBA8;
         break;
      default:
         log_cb(RETRO_LOG_ERROR, "Unsupported depth %d\n", depth);
         exit(EXIT_FAILURE);
   }

   Texture_init(
         &renderer->fb_out,
         native_width  * upscaling,
         native_height * upscaling,
         texture_storage);

   Texture_init(
         &renderer->fb_out_depth,
         renderer->fb_out.width,
         renderer->fb_out.height,
         GL_DEPTH24_STENCIL8);

   renderer->filter_type = filter;
   renderer->command_buffer = command_buffer;
   renderer->vertex_index_pos = 0;
   renderer->command_draw_mode = GL_TRIANGLES;
   renderer->semi_transparency_mode =  SemiTransparencyMode_Average;
   renderer->command_polygon_mode = command_draw_mode;
   renderer->output_buffer = output_buffer;
   renderer->image_load_buffer = image_load_buffer;
   renderer->config = config;
   renderer->frontend_resolution[0] = 0;
   renderer->frontend_resolution[1] = 0;
   renderer->internal_upscaling = upscaling;
   renderer->internal_color_depth = depth;
   renderer->crop_overscan = crop_overscan;
   renderer->image_offset_cycles = image_offset_cycles;
1456
   renderer->image_crop = image_crop;
ggdrt's avatar
ggdrt committed
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
   renderer->curr_width_mode = WIDTH_MODE_320;
   renderer->initial_scanline = initial_scanline;
   renderer->last_scanline = last_scanline;
   renderer->initial_scanline_pal = initial_scanline_pal;
   renderer->last_scanline_pal = last_scanline_pal;
   renderer->primitive_ordering = 0;
   renderer->tex_x_mask = 0;
   renderer->tex_x_or = 0;
   renderer->tex_y_mask = 0;
   renderer->tex_y_or = 0;
   renderer->display_vram = display_vram;
   renderer->set_mask  = false;
   renderer->mask_test = false;

   if (renderer)
      GlRenderer_upload_textures(renderer, top_left, dimensions, GPU_get_vram());

   return true;
}

static void GlRenderer_free(GlRenderer *renderer)
{
   if (!renderer)
      return;

   if (renderer->command_buffer)
   {
      DrawBuffer_free(renderer->command_buffer);
      delete renderer->command_buffer;
   }
   renderer->command_buffer = NULL;

   if (renderer->output_buffer)
   {
      DrawBuffer_free(renderer->output_buffer);
      delete renderer->output_buffer;
   }
   renderer->output_buffer = NULL;

   if (renderer->image_load_buffer)
   {
      DrawBuffer_free(renderer->image_load_buffer);
      delete renderer->image_load_buffer;
   }
   renderer->image_load_buffer = NULL;

   glDeleteTextures(1, &renderer->fb_texture.id);
   renderer->fb_texture.id     = 0;
   renderer->fb_texture.width  = 0;
   renderer->fb_texture.height = 0;

   glDeleteTextures(1, &renderer->fb_out.id);
   renderer->fb_out.id     = 0;
   renderer->fb_out.width  = 0;
   renderer->fb_out.height = 0;

   glDeleteTextures(1, &renderer->fb_out_depth.id);
   renderer->fb_out_depth.id     = 0;
   renderer->fb_out_depth.width  = 0;
   renderer->fb_out_depth.height = 0;

   unsigned i;
   for (i = 0; i < INDEX_BUFFER_LEN; i++)
      renderer->vertex_indices[i] = 0;
}

static inline void apply_scissor(GlRenderer *renderer)
{
   uint16_t _x = renderer->config.draw_area_top_left[0];
   uint16_t _y = renderer->config.draw_area_top_left[1];
   int _w      = renderer->config.draw_area_bot_right[0] - _x;
   int _h      = renderer->config.draw_area_bot_right[1] - _y;

   if (_w < 0)
      _w = 0;

   if (_h < 0)
      _h = 0;

   GLsizei upscale = (GLsizei)renderer->internal_upscaling;

   /* We need to scale those to match the internal resolution if
    * upscaling is enabled */
   GLsizei x = (GLsizei) _x * upscale;
   GLsizei y = (GLsizei) _y * upscale;
   GLsizei w = (GLsizei) _w * upscale;
   GLsizei h = (GLsizei) _h * upscale;

   glScissor(x, y, w, h);
}

static GlDisplayRect compute_gl_display_rect(GlRenderer *renderer)
{
   /* Current function logic mostly backported from Vulkan renderer */

   int32_t clock_div;
   switch (renderer->curr_width_mode)
   {
      case WIDTH_MODE_256:
         clock_div = 10;
         break;

      case WIDTH_MODE_320:
         clock_div = 8;
         break;

      case WIDTH_MODE_512:
         clock_div = 5;
         break;

      case WIDTH_MODE_640:
         clock_div = 4;
         break;

      /* The unusual case: 368px mode. Width is 364 px for
       * typical 368 mode games but often times something
       * different, which necessitates checking width mode 
       * rather than calculated pixel width */
      case WIDTH_MODE_368:
         clock_div = 7;
         break;

      default: //should never be here -- if we're here, something is terribly wrong
         break;
   }

   uint32_t width;
   int32_t x;
   if (renderer->crop_overscan)
   {
1587
      width = (uint32_t) ((2560/clock_div) - renderer->image_crop);
ggdrt's avatar
ggdrt committed
1588
1589
      int32_t offset_cycles = renderer->image_offset_cycles;
      int32_t h_start = (int32_t) renderer->config.display_area_hrange[0];
1590
      x = floor(((h_start - 608 + offset_cycles) / (double) clock_div) - (renderer->image_crop / 2));
ggdrt's avatar
ggdrt committed
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
   }
   else
   {
      width = (uint32_t) (2800/clock_div);
      int32_t offset_cycles = renderer->image_offset_cycles;
      int32_t h_start = (int32_t) renderer->config.display_area_hrange[0];
      x = floor((h_start - 488 + offset_cycles) / (double) clock_div);
   }

   uint32_t height;
   int32_t y;
   if (renderer->config.is_pal)
   {
      int h = renderer->last_scanline_pal - renderer->initial_scanline_pal + 1;
      height = (h < 0 ? 0 : (uint32_t) h);
      y = (308 - renderer->config.display_area_vrange[1]) + (renderer->last_scanline_pal - 287);
   }
   else
   {
      int h = renderer->last_scanline - renderer->initial_scanline + 1;
      height = (h < 0 ? 0 : (uint32_t) h);
      y = (256 - renderer->config.display_area_vrange[1]) + (renderer->last_scanline - 239);
   }
   height *= (renderer->config.is_480i ? 2 : 1);
   y *= (renderer->config.is_480i ? 2 : 1);

   return {x, y, width, height};
}

static void bind_libretro_framebuffer(GlRenderer *renderer)
{
   if (!renderer)
      return;

   GLuint fbo;
   uint32_t w, h;
   uint32_t upscale   = renderer->internal_upscaling;
   uint32_t f_w       = renderer->frontend_resolution[0];
   uint32_t f_h       = renderer->frontend_resolution[1];
   uint32_t _w        = renderer->config.display_resolution[0];
   uint32_t _h        = renderer->config.display_resolution[1];

   /* vp_w and vp_h currently contingent on rsx_intf_set_display_mode behavior... */
   uint32_t vp_w = renderer->config.display_resolution[0];
   uint32_t vp_h = renderer->config.display_resolution[1];

   int32_t x, y;
   int32_t _x = 0;
   int32_t _y = 0;

   if (renderer->display_vram)
   {
      _x           = 0;
      _y           = 0;
      _w           = VRAM_WIDTH_PIXELS;
      _h           = VRAM_HEIGHT;

      //override vram fb dimensions for viewport
      vp_w = _w;
      vp_h = _h;
   }
   else
   {
      GlDisplayRect disp_rect = compute_gl_display_rect(renderer);
      _x = disp_rect.x;
      _y = disp_rect.y;
      _w = disp_rect.width;
      _h = disp_rect.height;
   }

   x       = _x * (int32_t) upscale;
   y       = _y * (int32_t) upscale;
   w       = (uint32_t) _w * upscale;
   h       = (uint32_t) _h * upscale;
   vp_w   *= upscale;
   vp_h   *= upscale;

   if (w != f_w || h != f_h)
   {
      /* We need to change the frontend's resolution */
      struct retro_game_geometry geometry;
      geometry.base_width  = MEDNAFEN_CORE_GEOMETRY_BASE_W;
      geometry.base_height = MEDNAFEN_CORE_GEOMETRY_BASE_H;

      /* Max parameters are ignored by this call */
      geometry.max_width  = MEDNAFEN_CORE_GEOMETRY_MAX_W * upscale;
      geometry.max_height = MEDNAFEN_CORE_GEOMETRY_MAX_H * upscale;

1679
1680
1681
1682
1683
      geometry.aspect_ratio = rsx_common_get_aspect_ratio(content_is_pal, renderer->crop_overscan,
                                                          content_is_pal ? renderer->initial_scanline_pal :
                                                                           renderer->initial_scanline,
                                                          content_is_pal ? renderer->last_scanline_pal :
                                                                           renderer->last_scanline,
1684
1685
                                                          aspect_ratio_setting, renderer->display_vram, widescreen_hack,
                                                          widescreen_hack_aspect_ratio_setting);
ggdrt's avatar
ggdrt committed
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736

      environ_cb(RETRO_ENVIRONMENT_SET_GEOMETRY, &geometry);

      renderer->frontend_resolution[0] = w;
      renderer->frontend_resolution[1] = h;
   }

   /* Bind the output framebuffer provided by the frontend */
   fbo = glsm_get_current_framebuffer();
   glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
   glViewport((GLsizei) x, (GLsizei) y, (GLsizei) vp_w, (GLsizei) vp_h);
}

static bool retro_refresh_variables(GlRenderer *renderer)
{
   uint8_t filter            = FILTER_MODE_NEAREST;
   uint8_t upscaling         = 1;
   bool display_vram         = false;
   struct retro_variable var = {0};

   var.key = BEETLE_OPT(renderer_software_fb);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (!strcmp(var.value, "enabled"))
         has_software_fb = true;
      else
         has_software_fb = false;
   }
   else
      /* If 'BEETLE_OPT(renderer_software_fb)' option is not found, then
       * we are running in software mode */
      has_software_fb = true;

   get_variables(&upscaling, &display_vram);

   var.key = BEETLE_OPT(crop_overscan);
   bool crop_overscan = true;
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (!strcmp(var.value, "enabled"))
         crop_overscan = true;
      else if (!strcmp(var.value, "disabled"))
         crop_overscan = false;
   }

   int32_t image_offset_cycles;
   var.key = BEETLE_OPT(image_offset_cycles);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      image_offset_cycles = atoi(var.value);
   }
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
   
   unsigned image_crop;
   var.key = BEETLE_OPT(image_crop);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (strcmp(var.value, "disabled") == 0)
         image_crop = 0;
      else
         image_crop = atoi(var.value);
   }
ggdrt's avatar
ggdrt committed
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909

   int32_t initial_scanline = 0;
   var.key = BEETLE_OPT(initial_scanline);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      initial_scanline = atoi(var.value);
   }

   int32_t last_scanline = 239;
   var.key = BEETLE_OPT(last_scanline);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      last_scanline = atoi(var.value);
   }

   int32_t initial_scanline_pal = 0;
   var.key = BEETLE_OPT(initial_scanline_pal);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      initial_scanline_pal = atoi(var.value);
   }

   int32_t last_scanline_pal = 287;
   var.key = BEETLE_OPT(last_scanline_pal);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      last_scanline_pal = atoi(var.value);
   }

   var.key = BEETLE_OPT(filter);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (!strcmp(var.value, "nearest"))
         filter = FILTER_MODE_NEAREST;
      else if (!strcmp(var.value, "SABR"))
         filter = FILTER_MODE_SABR;
      else if (!strcmp(var.value, "xBR"))
         filter = FILTER_MODE_XBR;
      else if (!strcmp(var.value, "bilinear"))
         filter = FILTER_MODE_BILINEAR;
      else if (!strcmp(var.value, "3-point"))
         filter = FILTER_MODE_3POINT;
      else if (!strcmp(var.value, "JINC2"))
         filter = FILTER_MODE_JINC2;
   }

   var.key = BEETLE_OPT(depth);
   uint8_t depth = 16;
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (!strcmp(var.value, "32bpp"))
         depth = 32;
   }

   var.key = BEETLE_OPT(dither_mode);
   dither_mode dither_mode = DITHER_NATIVE;
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (!strcmp(var.value, "1x(native)"))
      {
         dither_mode = DITHER_NATIVE;
         DrawBuffer_enable_attribute(renderer->command_buffer, "dither");
      }
      else if (!strcmp(var.value, "internal resolution"))
      {
         dither_mode = DITHER_UPSCALED;
         DrawBuffer_enable_attribute(renderer->command_buffer, "dither");
      }
      else if (!strcmp(var.value, "disabled"))
      {
         dither_mode  = DITHER_OFF;
         DrawBuffer_disable_attribute(renderer->command_buffer, "dither");
      }
   }

   var.key = BEETLE_OPT(wireframe);
   bool wireframe = false;
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (!strcmp(var.value, "enabled"))
         wireframe = true;
   }

   bool rebuild_fb_out =
      upscaling != renderer->internal_upscaling ||
      depth != renderer->internal_color_depth;

   if (rebuild_fb_out)
   {
      if (dither_mode == DITHER_OFF)
         DrawBuffer_disable_attribute(renderer->command_buffer, "dither");
      else
         DrawBuffer_enable_attribute(renderer->command_buffer, "dither");

      uint32_t native_width  = (uint32_t) VRAM_WIDTH_PIXELS;
      uint32_t native_height = (uint32_t) VRAM_HEIGHT;

      uint32_t w = native_width  * upscaling;
      uint32_t h = native_height * upscaling;

      GLenum texture_storage = GL_RGB5_A1;
      switch (depth)
      {
         case 16:
            texture_storage = GL_RGB5_A1;
            break;
         case 32:
            texture_storage = GL_RGBA8;
            break;
         default:
            log_cb(RETRO_LOG_ERROR, "Unsupported depth %d\n", depth);
            exit(EXIT_FAILURE);
      }

      glDeleteTextures(1, &renderer->fb_out.id);
      renderer->fb_out.id     = 0;
      renderer->fb_out.width  = 0;
      renderer->fb_out.height = 0;
      Texture_init(&renderer->fb_out, w, h, texture_storage);

      /* This is a bit wasteful since it'll re-upload the data
       * to 'fb_texture' even though we haven't touched it but
       * this code is not very performance-critical anyway. */

      uint16_t top_left[2]   = {0, 0};
      uint16_t dimensions[2] = {(uint16_t) VRAM_WIDTH_PIXELS, (uint16_t) VRAM_HEIGHT};

      if (renderer)
         GlRenderer_upload_textures(renderer, top_left, dimensions, GPU_get_vram());

      glDeleteTextures(1, &renderer->fb_out_depth.id);
      renderer->fb_out_depth.id     = 0;
      renderer->fb_out_depth.width  = 0;
      renderer->fb_out_depth.height = 0;
      Texture_init(&renderer->fb_out_depth, w, h, GL_DEPTH24_STENCIL8);
   }

   if (renderer->command_buffer->program)
   {
      uint32_t dither_scaling = dither_mode == DITHER_UPSCALED ? 1 : upscaling;

      glUseProgram(renderer->command_buffer->program->id);
      glUniform1ui(renderer->command_buffer->program->uniforms["dither_scaling"], dither_scaling);
   }

   renderer->command_polygon_mode = wireframe ? GL_LINE : GL_FILL;

   glLineWidth((GLfloat) upscaling);

   /* If the scaling factor has changed the frontend should be
   *  reconfigured. We can't do that here because it could
   *  destroy the OpenGL context which would destroy 'this' */
   bool reconfigure_frontend =
      renderer->internal_upscaling != upscaling ||
      renderer->display_vram != display_vram ||
      renderer->filter_type != filter;

   renderer->internal_upscaling     = upscaling;
   renderer->display_vram           = display_vram;
   renderer->internal_color_depth   = depth;
   renderer->filter_type            = filter;
   renderer->crop_overscan          = crop_overscan;
   renderer->image_offset_cycles    = image_offset_cycles;
1910
   renderer->image_crop             = image_crop;
ggdrt's avatar
ggdrt committed
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
   renderer->initial_scanline       = initial_scanline;
   renderer->last_scanline          = last_scanline;
   renderer->initial_scanline_pal   = initial_scanline_pal;
   renderer->last_scanline_pal      = last_scanline_pal;

   return reconfigure_frontend;
}

static void vertex_preprocessing(
      GlRenderer *renderer,
      CommandVertex *v,
      unsigned count,
      GLenum mode,
      SemiTransparencyMode stm,
      bool mask_test,
      bool set_mask)
{
   if (!renderer)
      return;

   bool is_semi_transparent = v[0].semi_transparent == 1;
   bool is_textured         = v[0].texture_blend_mode != 0;
   /* Textured semi-transparent polys can contain opaque texels (when
    * bit 15 of the color is set to 0). Therefore they're drawn twice,
    * once for the opaque texels and once for the semi-transparent
    * ones. Only untextured semi-transparent triangles don't need to be
    * drawn as opaque. */
   bool is_opaque = !is_semi_transparent || is_textured;

   bool buffer_full         = DRAWBUFFER_REMAINING_CAPACITY(renderer->command_buffer) < count;

   if (buffer_full)
   {
      if (!DRAWBUFFER_IS_EMPTY(renderer->command_buffer))
         GlRenderer_draw(renderer);
   }

   int16_t z = renderer->primitive_ordering;
   renderer->primitive_ordering += 1;

   for (unsigned i = 0; i < count; i++)
   {
      v[i].position[2] = z;
      v[i].texture_window[0] = renderer->tex_x_mask;
      v[i].texture_window[1] = renderer->tex_x_or;
      v[i].texture_window[2] = renderer->tex_y_mask;
      v[i].texture_window[3] = renderer->tex_y_or;
   }

   if (renderer->batches.empty()
       || mode != renderer->command_draw_mode
       || is_opaque != renderer->opaque
       || (is_semi_transparent &&
           stm != renderer->semi_transparency_mode)
       || renderer->set_mask != set_mask
       || renderer->mask_test != mask_test)
   {
      if (!renderer->batches.empty())
      {
         PrimitiveBatch& last_batch = renderer->batches.back();
         last_batch.count = renderer->vertex_index_pos - last_batch.first;
      }
      PrimitiveBatch batch;
      batch.opaque = is_opaque;
      batch.draw_mode = mode;
      batch.transparency_mode = stm;
      batch.set_mask = set_mask;
      batch.mask_test = mask_test;
      batch.first = renderer->vertex_index_pos;
      batch.count = 0;
      renderer->batches.push_back(batch);

      renderer->semi_transparency_mode = stm;
      renderer->command_draw_mode = mode;
      renderer->opaque = is_opaque;
      renderer->set_mask = set_mask;
      renderer->mask_test = mask_test;
   }
}

static void vertex_add_blended_pass(
      GlRenderer *renderer, int vertex_index)
{
   if (!renderer->batches.empty())
   {
      PrimitiveBatch& last_batch = renderer->batches.back();
      last_batch.count = renderer->vertex_index_pos - last_batch.first;

      PrimitiveBatch batch;
      batch.opaque = false;
      batch.draw_mode = last_batch.draw_mode;
      batch.transparency_mode = last_batch.transparency_mode;
      batch.set_mask = true;
      batch.mask_test = last_batch.mask_test;
      batch.first = vertex_index;
      batch.count = 0;
      renderer->batches.push_back(batch);

      renderer->opaque = false;
      renderer->set_mask = true;
   }
}

static void push_primitive(
      GlRenderer *renderer,
      CommandVertex *v,
      unsigned count,
      GLenum mode,
      SemiTransparencyMode stm,
      bool mask_test,
      bool set_mask)
{
   if (!renderer)
      return;

   bool is_semi_transparent = v[0].semi_transparent   == 1;
   bool is_textured         = v[0].texture_blend_mode != 0;

   vertex_preprocessing(renderer, v, count, mode, stm, mask_test, set_mask);

   unsigned index     = DRAWBUFFER_NEXT_INDEX(renderer->command_buffer);
   unsigned index_pos = renderer->vertex_index_pos;

   for (unsigned i = 0; i < count; i++)
      renderer->vertex_indices[renderer->vertex_index_pos++] = index + i;

   /* Add transparent pass if needed */
   if (is_semi_transparent && is_textured)
      vertex_add_blended_pass(renderer, index_pos);

   DrawBuffer_push_slice(renderer->command_buffer, v, count,
         sizeof(CommandVertex)
         );
}

std::vector<Attribute> CommandVertex::attributes()
{
   std::vector<Attribute> result;
   Attribute attr;

   strcpy(attr.name, "position");
   attr.offset     = offsetof(CommandVertex, position);
   attr.type       = GL_FLOAT;
   attr.components = 4;

   result.push_back(attr);

   strcpy(attr.name, "color");
   attr.offset     = offsetof(CommandVertex, color);
   attr.type       = GL_UNSIGNED_BYTE;
   attr.components = 3;

   result.push_back(attr);

   strcpy(attr.name, "texture_coord");
   attr.offset     = offsetof(CommandVertex, texture_coord);
   attr.type       = GL_UNSIGNED_SHORT;
   attr.components = 2;

   result.push_back(attr);

   strcpy(attr.name, "texture_page");
   attr.offset     = offsetof(CommandVertex, texture_page);
   attr.type       = GL_UNSIGNED_SHORT;
   attr.components = 2;

   result.push_back(attr);

   strcpy(attr.name, "clut");
   attr.offset     = offsetof(CommandVertex, clut);
   attr.type       = GL_UNSIGNED_SHORT;
   attr.components = 2;

   result.push_back(attr);

   strcpy(attr.name, "texture_blend_mode");
   attr.offset     = offsetof(CommandVertex, texture_blend_mode);
   attr.type       = GL_UNSIGNED_BYTE;
   attr.components = 1;

   result.push_back(attr);

   strcpy(attr.name, "depth_shift");
   attr.offset     = offsetof(CommandVertex, depth_shift);
   attr.type       = GL_UNSIGNED_BYTE;
   attr.components = 1;

   result.push_back(attr);

   strcpy(attr.name, "dither");
   attr.offset     = offsetof(CommandVertex, dither);
   attr.type       = GL_UNSIGNED_BYTE;
   attr.components = 1;

   result.push_back(attr);

   strcpy(attr.name, "semi_transparent");
   attr.offset     = offsetof(CommandVertex, semi_transparent);
   attr.type       = GL_UNSIGNED_BYTE;
   attr.components = 1;

   result.push_back(attr);

   strcpy(attr.name, "texture_window");
   attr.offset     = offsetof(CommandVertex, texture_window);
   attr.type       = GL_UNSIGNED_BYTE;
   attr.components = 4;

   result.push_back(attr);

   strcpy(attr.name, "texture_limits");
   attr.offset     = offsetof(CommandVertex, texture_limits);
   attr.type       = GL_UNSIGNED_SHORT;
   attr.components = 4;

   result.push_back(attr);

   return result;
}

std::vector<Attribute> OutputVertex::attributes()
{
   std::vector<Attribute> result;
   Attribute attr;

   strcpy(attr.name, "position");
   attr.offset     = offsetof(OutputVertex, position);
   attr.type       = GL_FLOAT;
   attr.components = 2;

   result.push_back(attr);

   strcpy(attr.name, "fb_coord");
   attr.offset     = offsetof(OutputVertex, fb_coord);
   attr.type       = GL_UNSIGNED_SHORT;
   attr.components = 2;

   result.push_back(attr);

   return result;
}

std::vector<Attribute> ImageLoadVertex::attributes()
{
   std::vector<Attribute> result;
   Attribute attr;

   strcpy(attr.name, "position");
   attr.offset     = offsetof(ImageLoadVertex, position);
   attr.type       = GL_UNSIGNED_SHORT;
   attr.components = 2;

   result.push_back(attr);

   return result;
}

static void cleanup_gl_state(void)
{
   /* Cleanup OpenGL context before returning to the frontend */
   /* All of these GL calls are also done in glsm_ctl(UNBIND) */
   glDisable(GL_BLEND);
   glBlendColor(0.0, 0.0, 0.0, 0.0);
   glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
   glBlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_ZERO);
   glActiveTexture(GL_TEXTURE0);
   glBindTexture(GL_TEXTURE_2D, 0);
   glUseProgram(0);
   glBindVertexArray(0);
   glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
   glLineWidth(1.0);
   glClearColor(0.0, 0.0, 0.0, 0.0);
}

extern void GPU_RestoreStateP1(bool val);
extern void GPU_RestoreStateP2(bool val);
extern void GPU_RestoreStateP3(void);

static void gl_context_reset(void)
{
Libretro-Admin's avatar
Libretro-Admin committed
2191
   log_cb(RETRO_LOG_DEBUG, "gl_context_reset called.\n");
ggdrt's avatar
ggdrt committed
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
   glsm_ctl(GLSM_CTL_STATE_CONTEXT_RESET, NULL);

   if (!glsm_ctl(GLSM_CTL_STATE_SETUP, NULL))
      return;

   static_renderer.state_data = new GlRenderer();

   if (GlRenderer_new(static_renderer.state_data, persistent_config))
   {
      static_renderer.inited = true;
      static_renderer.state  = GlState_Valid;

      GPU_RestoreStateP1(true);
      GPU_RestoreStateP2(true);
      GPU_RestoreStateP3();
   }
   else
   {
      log_cb(RETRO_LOG_WARN, "[gl_context_reset] GlRenderer_new failed. State will be invalid.\n");
   }
}

static void gl_context_destroy(void)
{
   glsm_ctl(GLSM_CTL_STATE_CONTEXT_DESTROY, NULL);

Libretro-Admin's avatar
Libretro-Admin committed
2218
   log_cb(RETRO_LOG_DEBUG, "gl_context_destroy called.\n");
ggdrt's avatar
ggdrt committed
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235

   if (static_renderer.state_data)
   {
      GlRenderer_free(static_renderer.state_data);
      delete static_renderer.state_data;
   }

   static_renderer.state_data = NULL;
   static_renderer.state      = GlState_Invalid;
   static_renderer.inited     = false;
}

static bool gl_context_framebuffer_lock(void* data)
{
   return false;
}

2236
2237
extern "C" bool currently_interlaced;

ggdrt's avatar
ggdrt committed
2238
2239
2240
static struct retro_system_av_info get_av_info(VideoClock std)
{
   struct retro_system_av_info info;
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
   unsigned int max_width                   = 0;
   unsigned int max_height                  = 0;
   uint8_t upscaling                        = 1;
   bool widescreen_hack                     = false;
   int widescreen_hack_aspect_ratio_setting = 1;
   bool display_vram                        = false;
   bool crop_overscan                       = false;
   int initial_scanline_ntsc                = 0;
   int last_scanline_ntsc                   = 239;
   int initial_scanline_pal                 = 0;
   int last_scanline_pal                    = 287;
2252
2253
2254

   /* This function currently queries core options rather than
      checking GlRenderer state; possible to refactor? */
ggdrt's avatar
ggdrt committed
2255
2256
2257
2258
2259

   get_variables(&upscaling, &display_vram);

   struct retro_variable var = {0};

2260
   var.key = BEETLE_OPT(widescreen_hack);
ggdrt's avatar
ggdrt committed
2261
2262
2263
2264
2265
2266
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (!strcmp(var.value, "enabled"))
         widescreen_hack = true;
   }

2267
2268
2269
2270
2271
2272
2273
   var.key = BEETLE_OPT(widescreen_hack_aspect_ratio);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (!strcmp(var.value, "16:10"))
         widescreen_hack_aspect_ratio_setting = 0;
      else if (!strcmp(var.value, "16:9"))
         widescreen_hack_aspect_ratio_setting = 1;
2274
      else if (!strcmp(var.value, "18:9"))
2275
         widescreen_hack_aspect_ratio_setting = 2;
2276
      else if (!strcmp(var.value, "19:9"))
2277
         widescreen_hack_aspect_ratio_setting = 3;
2278
2279
2280
2281
2282
2283
      else if (!strcmp(var.value, "20:9"))
         widescreen_hack_aspect_ratio_setting = 4;
      else if (!strcmp(var.value, "21:9"))
         widescreen_hack_aspect_ratio_setting = 5;
      else if (!strcmp(var.value, "32:9"))
         widescreen_hack_aspect_ratio_setting = 6;
2284
2285
   }

2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
   var.key = BEETLE_OPT(crop_overscan);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      if (!strcmp(var.value, "enabled"))
         crop_overscan = true;
   }

   var.key = BEETLE_OPT(initial_scanline);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      initial_scanline_ntsc = atoi(var.value);
   }

   var.key = BEETLE_OPT(last_scanline);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      last_scanline_ntsc = atoi(var.value);
   }

   var.key = BEETLE_OPT(initial_scanline_pal);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      initial_scanline_pal = atoi(var.value);
   }

   var.key = BEETLE_OPT(last_scanline_pal);
   if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
   {
      last_scanline_pal = atoi(var.value);
   }

ggdrt's avatar
ggdrt committed
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
   if (display_vram)
   {
      max_width  = VRAM_WIDTH_PIXELS;
      max_height = VRAM_HEIGHT;
   }
   else
   {
      max_width  = MEDNAFEN_CORE_GEOMETRY_MAX_W;
      max_height = MEDNAFEN_CORE_GEOMETRY_MAX_H;
   }

   memset(&info, 0, sizeof(info));

   /* The base resolution will be overriden using
    * ENVIRONMENT_SET_GEOMETRY before rendering a frame so
    * this base value is not really important */
   info.geometry.base_width     = MEDNAFEN_CORE_GEOMETRY_BASE_W;
   info.geometry.base_height    = MEDNAFEN_CORE_GEOMETRY_BASE_H;
   info.geometry.max_width      = max_width  * upscaling;
   info.geometry.max_height     = max_height * upscaling;
2337
2338
2339
   info.geometry.aspect_ratio = rsx_common_get_aspect_ratio(std, crop_overscan,
                                                            std ? initial_scanline_pal : initial_scanline_ntsc,
                                                            std ? last_scanline_pal : last_scanline_ntsc,
2340
2341
                                                            aspect_ratio_setting, display_vram, widescreen_hack,
                                                            widescreen_hack_aspect_ratio_setting);
ggdrt's avatar
ggdrt committed
2342

2343
   info.timing.fps = rsx_common_get_timing_fps();
ggdrt's avatar
ggdrt committed
2344
   info.timing.sample_rate = SOUND_FREQUENCY;
ggdrt's avatar
ggdrt committed
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429

   return info;
}

void rsx_gl_get_system_av_info(struct retro_system_av_info *info)
{
   /* TODO/FIXME - This definition seems very backwards and duplicating work */

   /* This will possibly trigger the frontend to reconfigure itself */
   if (static_renderer.inited)
      rsx_gl_refresh_variables();

   struct retro_system_av_info result = get_av_info(static_renderer.video_clock);
   memcpy(info, &result, sizeof(result));
}

bool rsx_gl_open(bool is_pal)
{
   glsm_ctx_params_t params = {0};
   retro_pixel_format f = RETRO_PIXEL_FORMAT_XRGB8888;
   VideoClock clock = is_pal ? VideoClock_Pal : VideoClock_Ntsc;

   if (!environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &f))
      return false;

   /* glsm related setup */
   params.context_reset         = gl_context_reset;
   params.context_destroy       = gl_context_destroy;
   params.framebuffer_lock      = gl_context_framebuffer_lock;
   params.environ_cb            = environ_cb;
   params.stencil               = false;
   params.imm_vbo_draw          = NULL;
   params.imm_vbo_disable       = NULL;
   params.context_type          = RETRO_HW_CONTEXT_OPENGL_CORE;
   params.major                 = 3;
   params.minor                 = 3;

   if (!glsm_ctl(GLSM_CTL_STATE_CONTEXT_INIT, &params))
      return false;

   /* No context until 'context_reset' is called */
   static_renderer.video_clock  = clock;

   return true;
}

void rsx_gl_close(void)
{
   static_renderer.state       = GlState_Invalid;
   static_renderer.video_clock = VideoClock_Ntsc;
}

void rsx_gl_refresh_variables(void)
{
   GlRenderer* renderer = NULL;
   if (!static_renderer.inited)
      return;

   switch (static_renderer.state)
   {
      case GlState_Valid:
         renderer = static_renderer.state_data;
         break;
      case GlState_Invalid:
         /* Nothing to be done if we don't have a GL context */
         return;
   }

   bool reconfigure_frontend = retro_refresh_variables(renderer);

   if (reconfigure_frontend)
   {
      /* The resolution has changed, we must tell the frontend
       * to change its format */
      struct retro_variable var = {0};

      struct retro_system_av_info av_info = get_av_info(static_renderer.video_clock);

      /* This call can potentially (but not necessarily) call
       * 'context_destroy' and 'context_reset' to reinitialize */
      bool ok = environ_cb(RETRO_ENVIRONMENT_SET_SYSTEM_AV_INFO, &av_info);

      if (!ok)
      {
         log_cb(RETRO_LOG_WARN, "Couldn't change frontend resolution\n");
Libretro-Admin's avatar
Libretro-Admin committed
2430
         log_cb(RETRO_LOG_DEBUG, "Try resetting to enable the new configuration\n");
ggdrt's avatar
ggdrt committed
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
      }
   }
}

void rsx_gl_prepare_frame(void)
{
   if (static_renderer.state == GlState_Invalid)
      return;

   GlRenderer *renderer = static_renderer.state_data;
   if (!renderer)
   {
      log_cb(RETRO_LOG_ERROR, "[rsx_gl_prepare_frame] Renderer state marked as valid but state data is null.\n");
      return;
   }

   /* In case we're upscaling we need to increase the line width
    * proportionally */
   glLineWidth((GLfloat)renderer->internal_upscaling);
   glPolygonMode(GL_FRONT_AND_BACK, renderer->command_polygon_mode);
   glEnable(GL_SCISSOR_TEST);
   glEnable(GL_DEPTH_TEST);
   glDepthFunc(GL_LEQUAL);
   /* Used for PSX GPU command blending */
   glBlendColor(0.25, 0.25, 0.25, 0.5);

   apply_scissor(renderer);

   glActiveTexture(GL_TEXTURE0);
   glBindTexture(GL_TEXTURE_2D, renderer->fb_texture.id);
}

ggdrt's avatar
ggdrt committed
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
static void compute_vram_framebuffer_dimensions(GlRenderer *renderer)
{
   /* Compute native PSX framebuffer dimensions for current frame
      and store results in renderer->config.display_resolution */

   if (!renderer)
      return;

   uint16_t clock_div;
   switch (renderer->curr_width_mode)
   {
      case WIDTH_MODE_256:
         clock_div = 10;
         break;

      case WIDTH_MODE_320:
         clock_div = 8;
         break;

      case WIDTH_MODE_512:
         clock_div = 5;
         break;

      case WIDTH_MODE_640:
         clock_div = 4;
         break;

      case WIDTH_MODE_368:
         clock_div = 7;
         break;

      default: // Should not be here, if we ever get here then log and crash?
         break;
   }

   // First we get the horizontal range in number of pixel clock period
   uint16_t fb_width = (renderer->config.display_area_hrange[1] - renderer->config.display_area_hrange[0]);

   // Then we apply the divider
   fb_width /= clock_div;

   // Then the rounding formula straight outta No$
   fb_width = (fb_width + 2) & ~3;

   uint16_t fb_height = (renderer->config.display_area_vrange[1] - renderer->config.display_area_vrange[0]);
   fb_height *= renderer->config.is_480i ? 2 : 1;

   renderer->config.display_resolution[0] = fb_width;
   renderer->config.display_resolution[1] = fb_height;
}

ggdrt's avatar
ggdrt committed
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
void rsx_gl_finalize_frame(const void *fb, unsigned width,
                           unsigned height, unsigned pitch)
{
   /* Setup 2 triangles that cover the entire framebuffer
      then copy the displayed portion of the screen from fb_out */

   if (static_renderer.state == GlState_Invalid)
      return;

   GlRenderer *renderer = static_renderer.state_data;
   if (!renderer)
      return;

   /* Draw pending commands */
   if (!DRAWBUFFER_IS_EMPTY(renderer->command_buffer))
      GlRenderer_draw(renderer);

ggdrt's avatar
ggdrt committed
2531
2532
2533
2534
   /* Calculate native PSX framebuffer dimensions to update renderer
      state before calling bind_libretro_framebuffer */
   compute_vram_framebuffer_dimensions(renderer);

ggdrt's avatar
ggdrt committed
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
   /* We can now render to the frontend's buffer */
   bind_libretro_framebuffer(renderer);

   glDisable(GL_SCISSOR_TEST);
   glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
   glDisable(GL_DEPTH_TEST);
   glDisable(GL_BLEND);

   /* Clear the screen no matter what: prevents possible leftover 
      pixels from previous frame when loading save state for any 
      games not using standard framebuffer heights */
   glClearColor(0.0, 0.0, 0.0, 0.0);
   glClear(GL_COLOR_BUFFER_BIT);

ggdrt's avatar
ggdrt committed
2549
   if (!renderer->config.display_off || renderer->display_vram)
ggdrt's avatar
ggdrt committed
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
   {
      /* Bind 'fb_out' to texture unit 1 */
      glActiveTexture(GL_TEXTURE1);
      glBindTexture(GL_TEXTURE_2D, renderer->fb_out.id);

      /* First we draw the visible part of fb_out */
      uint16_t fb_x_start = renderer->config.display_top_left[0];
      uint16_t fb_y_start = renderer->config.display_top_left[1];
      uint16_t fb_width   = renderer->config.display_resolution[0];
      uint16_t fb_height  = renderer->config.display_resolution[1];

      GLint depth_24bpp   = (GLint) renderer->config.display_24bpp;

      if (renderer-