Project

General

Profile

Download (39.6 KB) Statistics
| Branch: | Revision:

library / src / main / java / org / distorted / library / main / DistortedLibrary.java @ b5be333a

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// Distorted is free software: you can redistribute it and/or modify                             //
7
// it under the terms of the GNU General Public License as published by                          //
8
// the Free Software Foundation, either version 2 of the License, or                             //
9
// (at your option) any later version.                                                           //
10
//                                                                                               //
11
// Distorted is distributed in the hope that it will be useful,                                  //
12
// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
14
// GNU General Public License for more details.                                                  //
15
//                                                                                               //
16
// You should have received a copy of the GNU General Public License                             //
17
// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.library.main;
21

    
22
import android.app.ActivityManager;
23
import android.content.Context;
24
import android.content.pm.ConfigurationInfo;
25
import android.content.res.Resources;
26
import android.opengl.GLES30;
27
import android.opengl.GLES31;
28
import android.util.Log;
29

    
30
import org.distorted.library.R;
31
import org.distorted.library.effect.Effect;
32
import org.distorted.library.effectqueue.EffectQueue;
33
import org.distorted.library.effectqueue.EffectQueuePostprocess;
34
import org.distorted.library.effect.EffectType;
35
import org.distorted.library.effect.FragmentEffect;
36
import org.distorted.library.effect.PostprocessEffect;
37
import org.distorted.library.effect.VertexEffect;
38
import org.distorted.library.mesh.MeshBase;
39
import org.distorted.library.message.EffectMessageSender;
40
import org.distorted.library.program.DistortedProgram;
41
import org.distorted.library.program.VertexCompilationException;
42

    
43
import java.io.InputStream;
44
import java.nio.ByteBuffer;
45
import java.nio.ByteOrder;
46
import java.nio.FloatBuffer;
47
import java.nio.IntBuffer;
48

    
49
///////////////////////////////////////////////////////////////////////////////////////////////////
50
/**
51
 * A singleton class used to control various global dialog_settings.
52
 */
53
public class DistortedLibrary
54
  {
55
  private static int mGLSL;
56
  private static String mGLSL_VERSION;
57
  private static boolean mOITCompilationSuccessful;
58
  /**
59
   * When creating an instance of a DistortedTexture from another instance, clone the Bitmap that's
60
   * backing up our DistortedTexture.
61
   * <p>
62
   * This way we can have two DistortedTextures, both backed up by the same Bitmap, to which we can
63
   * apply different effects. Used in the copy constructor.
64
   */
65
  public static final int CLONE_SURFACE = 0x1;
66
  /**
67
   * When creating an instance of a DistortedEffects from another instance, clone the Matrix Effects.
68
   * <p>
69
   * This way we can have two different DistortedEffects sharing the MATRIX queue.
70
   */
71
  public static final int CLONE_MATRIX = 0x2;
72
  /**
73
   * When creating an instance of a DistortedEffects from another instance, clone the Vertex Effects.
74
   * <p>
75
   * This way we can have two different DistortedEffects sharing the VERTEX queue.
76
   */
77
  public static final int CLONE_VERTEX  = 0x4;
78
  /**
79
   * When creating an instance of a DistortedEffects from another instance, clone the Fragment Effects.
80
   * <p>
81
   * This way we can have two different DistortedEffects sharing the FRAGMENT queue.
82
   */
83
  public static final int CLONE_FRAGMENT= 0x8;
84
   /**
85
   * When creating an instance of a DistortedEffects from another instance, clone the PostProcess Effects.
86
   * <p>
87
   * This way we can have two different DistortedEffects sharing the POSTPROCESS queue.
88
   */
89
  public static final int CLONE_POSTPROCESS= 0x10;
90
  /**
91
   * When creating an instance of a DistortedNode from another instance, clone the children Nodes.
92
   * <p>
93
   * This is mainly useful for creating many similar sub-trees and rendering then at different places
94
   * on the screen with (optionally) different Effects.
95
   */
96
  public static final int CLONE_CHILDREN= 0x20;
97

    
98
  /**
99
   * Work around bugs in ARM Mali driver by, instead to a single FBO, rendering to a circular queue
100
   * of FBO_QUEUE_SIZE FBOs. (otherwise we sometimes get a 'full pipeline flush' and the end result
101
   * might be missing part of the Objects)
102
   *
103
   * This bug only exists on Mali driver r12.
104
   *
105
   * https://community.arm.com/graphics/f/discussions/10285/opengl-es-3-1-on-mali-t880-flashes
106
   */
107
  static final int FBO_QUEUE_SIZE = 4;
108

    
109
  private static boolean mInitialized=false;
110

    
111
  //////////////////////////////////////////////////////////////////////////////////////////////
112
  /// MAIN PROGRAM ///
113
  private static DistortedProgram mMainProgram;
114
  private static int mMainTextureH;
115

    
116
  /// NORMAL PROGRAM /////
117
  private static DistortedProgram mNormalProgram;
118
  private static int mNormalMVPMatrixH;
119

    
120
  /// MAIN OIT PROGRAM ///
121
  private static DistortedProgram mMainOITProgram;
122
  private static int mMainOITTextureH;
123
  private static int mMainOITSizeH;
124
  private static int mMainOITNumRecordsH;
125

    
126
  /// BLIT PROGRAM ///
127
  private static DistortedProgram mBlitProgram;
128
  private static int mBlitTextureH;
129
  private static int mBlitDepthH;
130
  private static final FloatBuffer mQuadPositions;
131

    
132
  /// FULL PROGRAM ///
133
  private static DistortedProgram mFullProgram;
134

    
135
  static
136
    {
137
    float[] positionData= { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
138
    mQuadPositions = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()).asFloatBuffer();
139
    mQuadPositions.put(positionData).position(0);
140
    }
141

    
142
  /// BLIT DEPTH PROGRAM ///
143
  private static DistortedProgram mBlitDepthProgram;
144
  private static int mBlitDepthTextureH;
145
  private static int mBlitDepthDepthTextureH;
146
  private static int mBlitDepthDepthH;
147
  private static int mBlitDepthTexCorrH;
148

    
149
  /// OIT SSBO BUFFER ///
150
  private static int[] mLinkedListSSBO = new int[1];
151
  private static int[] mAtomicCounter = new int[DistortedLibrary.FBO_QUEUE_SIZE];
152
  private static int   mCurrBuffer;
153

    
154
  static
155
    {
156
    mLinkedListSSBO[0]= -1;
157
    mCurrBuffer       =  0;
158

    
159
    for(int i = 0; i< DistortedLibrary.FBO_QUEUE_SIZE; i++)  mAtomicCounter[i] = -1;
160
    }
161

    
162
  ///////////////////////////////////////////////////////////////
163
  // meaning: allocate 1.0 screenful of places for transparent
164
  // fragments in the SSBO backing up the OIT render method.
165
  private static float mBufferSize=1.0f;
166

    
167
  /// OIT CLEAR PROGRAM ///
168
  private static DistortedProgram mOITClearProgram;
169
  private static int mOITClearDepthH;
170
  private static int mOITClearTexCorrH;
171
  private static int mOITClearSizeH;
172

    
173
  /// OIT BUILD PROGRAM ///
174
  private static DistortedProgram mOITBuildProgram;
175
  private static int mOITBuildTextureH;
176
  private static int mOITBuildDepthTextureH;
177
  private static int mOITBuildDepthH;
178
  private static int mOITBuildTexCorrH;
179
  private static int mOITBuildSizeH;
180
  private static int mOITBuildNumRecordsH;
181

    
182
  /// OIT COLLAPSE PROGRAM ///
183
  private static DistortedProgram mOITCollapseProgram;
184
  private static int mOITCollapseDepthTextureH;
185
  private static int mOITCollapseDepthH;
186
  private static int mOITCollapseTexCorrH;
187
  private static int mOITCollapseSizeH;
188

    
189
  /// OIT RENDER PROGRAM ///
190
  private static DistortedProgram mOITRenderProgram;
191
  private static int mOITRenderDepthH;
192
  private static int mOITRenderTexCorrH;
193
  private static int mOITRenderSizeH;
194

    
195
  /// END PROGRAMS //////
196

    
197
///////////////////////////////////////////////////////////////////////////////////////////////////
198
// private: hide this from Javadoc
199

    
200
  private DistortedLibrary()
201
    {
202

    
203
    }
204

    
205
///////////////////////////////////////////////////////////////////////////////////////////////////
206

    
207
  private static void createPrograms(Resources resources)
208
    {
209
    // MAIN PROGRAM ////////////////////////////////////
210
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
211
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
212

    
213
    int numF = FragmentEffect.getNumEnabled();
214
    int numV = VertexEffect.getNumEnabled();
215

    
216
    String mainVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n");
217
    String mainFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n");
218
    String enabledEffectV= VertexEffect.getGLSL();
219
    String enabledEffectF= FragmentEffect.getGLSL();
220

    
221
    String[] feedback = { "v_Position", "v_endPosition" };
222

    
223
    try
224
      {
225
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
226
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
227
      }
228
    catch(Exception e)
229
      {
230
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
231
      throw new RuntimeException(e.getMessage());
232
      }
233

    
234
    int mainProgramH = mMainProgram.getProgramHandle();
235
    EffectQueue.getUniforms(mainProgramH,0);
236
    mMainTextureH= GLES30.glGetUniformLocation( mainProgramH, "u_Texture");
237

    
238
    // BLIT PROGRAM ////////////////////////////////////
239
    final InputStream blitVertStream = resources.openRawResource(R.raw.blit_vertex_shader);
240
    final InputStream blitFragStream = resources.openRawResource(R.raw.blit_fragment_shader);
241

    
242
    try
243
      {
244
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
245
      }
246
    catch(Exception e)
247
      {
248
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
249
      throw new RuntimeException(e.getMessage());
250
      }
251

    
252
    int blitProgramH = mBlitProgram.getProgramHandle();
253
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
254
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
255

    
256
    // BLIT DEPTH PROGRAM ////////////////////////////////////
257
    final InputStream blitDepthVertStream = resources.openRawResource(R.raw.blit_depth_vertex_shader);
258
    final InputStream blitDepthFragStream = resources.openRawResource(R.raw.blit_depth_fragment_shader);
259

    
260
    try
261
      {
262
      mBlitDepthProgram = new DistortedProgram(blitDepthVertStream,blitDepthFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
263
      }
264
    catch(Exception e)
265
      {
266
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH program: "+e.getMessage());
267
      throw new RuntimeException(e.getMessage());
268
      }
269

    
270
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
271
    mBlitDepthTextureH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Texture");
272
    mBlitDepthDepthTextureH = GLES30.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
273
    mBlitDepthDepthH        = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Depth");
274
    mBlitDepthTexCorrH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
275

    
276
    // NORMAL PROGRAM //////////////////////////////////////
277
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
278
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
279

    
280
    try
281
      {
282
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
283
      }
284
    catch(Exception e)
285
      {
286
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
287
      throw new RuntimeException(e.getMessage());
288
      }
289

    
290
    int normalProgramH = mNormalProgram.getProgramHandle();
291
    mNormalMVPMatrixH  = GLES30.glGetUniformLocation( normalProgramH, "u_MVPMatrix");
292
    }
293

    
294
///////////////////////////////////////////////////////////////////////////////////////////////////
295

    
296
  private static void createFullProgram(Resources resources)
297
    {
298
    final InputStream fullVertStream = resources.openRawResource(R.raw.main_vertex_shader);
299
    final InputStream fullFragStream = resources.openRawResource(R.raw.main_fragment_shader);
300

    
301
    int numV = VertexEffect.getAllEnabled();
302

    
303
    String fullVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX ) : 0 ) + "\n");
304
    String fullFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " +                                         0   + "\n");
305
    String enabledEffectV= VertexEffect.getAllGLSL();
306
    String enabledEffectF= "{}";
307

    
308
    String[] feedback = { "v_Position", "v_endPosition" };
309

    
310
    try
311
      {
312
      mFullProgram = new DistortedProgram(fullVertStream, fullFragStream, fullVertHeader, fullFragHeader,
313
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
314
      }
315
    catch(Exception e)
316
      {
317
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile FULL program: "+e.getMessage());
318
      throw new RuntimeException(e.getMessage());
319
      }
320

    
321
    int fullProgramH = mFullProgram.getProgramHandle();
322
    EffectQueue.getUniforms(fullProgramH,3);
323
    }
324

    
325
///////////////////////////////////////////////////////////////////////////////////////////////////
326

    
327
  private static void createProgramsOIT(Resources resources)
328
    {
329
    // MAIN OIT PROGRAM ////////////////////////////////
330
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
331
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
332

    
333
    int numF = FragmentEffect.getNumEnabled();
334
    int numV = VertexEffect.getNumEnabled();
335

    
336
    String mainVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n") + ("#define OIT\n");
337
    String mainFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n") + ("#define OIT\n");
338

    
339
    String enabledEffectV= VertexEffect.getGLSL();
340
    String enabledEffectF= FragmentEffect.getGLSL();
341

    
342
    try
343
      {
344
      mMainOITProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
345
                                             enabledEffectV, enabledEffectF, mGLSL, null);
346
      }
347
    catch(Exception e)
348
      {
349
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN OIT program: "+e.getMessage());
350
      throw new RuntimeException(e.getMessage());
351
      }
352

    
353
    int mainOITProgramH = mMainOITProgram.getProgramHandle();
354
    EffectQueue.getUniforms(mainOITProgramH,1);
355
    mMainOITTextureH    = GLES30.glGetUniformLocation( mainOITProgramH, "u_Texture");
356
    mMainOITSizeH       = GLES30.glGetUniformLocation( mainOITProgramH, "u_Size");
357
    mMainOITNumRecordsH = GLES30.glGetUniformLocation( mainOITProgramH, "u_numRecords");
358

    
359
    // OIT CLEAR PROGRAM ////////////////////////////////////
360
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
361
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
362

    
363
    try
364
      {
365
      mOITClearProgram = new DistortedProgram(oitClearVertStream,oitClearFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
366
      }
367
    catch(Exception e)
368
      {
369
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT CLEAR program: "+e.getMessage());
370
      throw new RuntimeException(e.getMessage());
371
      }
372

    
373
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
374
    mOITClearDepthH        = GLES30.glGetUniformLocation( oitClearProgramH, "u_Depth");
375
    mOITClearTexCorrH      = GLES30.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
376
    mOITClearSizeH         = GLES30.glGetUniformLocation( oitClearProgramH, "u_Size");
377

    
378
    // OIT BUILD PROGRAM ////////////////////////////////////
379
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
380
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
381

    
382
    try
383
      {
384
      mOITBuildProgram = new DistortedProgram(oitBuildVertStream,oitBuildFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
385
      }
386
    catch(Exception e)
387
      {
388
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT BUILD program: "+e.getMessage());
389
      throw new RuntimeException(e.getMessage());
390
      }
391

    
392
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
393
    mOITBuildTextureH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Texture");
394
    mOITBuildDepthTextureH = GLES30.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
395
    mOITBuildDepthH        = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Depth");
396
    mOITBuildTexCorrH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
397
    mOITBuildSizeH         = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Size");
398
    mOITBuildNumRecordsH   = GLES30.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
399

    
400
    // OIT COLLAPSE PROGRAM ///////////////////////////
401
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
402
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
403

    
404
    try
405
      {
406
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
407
      }
408
    catch(Exception e)
409
      {
410
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
411
      throw new RuntimeException(e.getMessage());
412
      }
413

    
414
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
415
    mOITCollapseDepthTextureH = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
416
    mOITCollapseDepthH        = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
417
    mOITCollapseTexCorrH      = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
418
    mOITCollapseSizeH         = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Size");
419

    
420
    // OIT RENDER PROGRAM ///////////////////////////
421
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
422
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
423

    
424
    try
425
      {
426
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
427
      }
428
    catch(Exception e)
429
      {
430
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
431
      throw new RuntimeException(e.getMessage());
432
      }
433

    
434
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
435
    mOITRenderDepthH        = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Depth");
436
    mOITRenderTexCorrH      = GLES30.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
437
    mOITRenderSizeH         = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Size");
438
    }
439

    
440
///////////////////////////////////////////////////////////////////////////////////////////////////
441

    
442
  private static void displayNormals(EffectQueue[] queues, MeshBase mesh)
443
    {
444
    int num = mesh.getNumVertices();
445
    int tfo = mesh.getTFO();
446

    
447
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
448
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
449
    InternalRenderState.switchOffDrawing();
450
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
451
    InternalRenderState.restoreDrawing();
452
    GLES30.glEndTransformFeedback();
453
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
454

    
455
    mNormalProgram.useProgram();
456
    GLES30.glUniformMatrix4fv(mNormalMVPMatrixH, 1, false, EffectQueue.getMVP(queues) , 0);
457
    mesh.bindTransformAttribs(mNormalProgram);
458
    GLES30.glLineWidth(8.0f);
459
    GLES30.glDrawArrays(GLES30.GL_LINES, 0, 2*num);
460
    }
461

    
462
///////////////////////////////////////////////////////////////////////////////////////////////////
463
// execute all VertexEffects and adjust all vertices
464

    
465
  public static void adjustVertices(MeshBase mesh)
466
    {
467
    if( mFullProgram!=null )
468
      {
469
      GLES30.glViewport(0, 0, 500, 500 ); // TODO ???
470

    
471
      int num = mesh.getNumVertices();
472
      int tfo = mesh.getTFO();
473

    
474
      mFullProgram.useProgram();
475
      mesh.bindVertexAttribs(mFullProgram);
476
      mesh.computeQueue();
477
      mesh.sendQueue();
478

    
479
      GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
480
      GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
481
      InternalRenderState.switchOffDrawing();
482
      GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
483
      InternalRenderState.restoreDrawing();
484
      GLES30.glEndTransformFeedback();
485
      mesh.copyTransformToVertex();
486
      GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
487
      }
488
    }
489

    
490
///////////////////////////////////////////////////////////////////////////////////////////////////
491

    
492
  static void drawPrivOIT(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
493
    {
494
    EffectQueue[] queues = effects.getQueues();
495

    
496
    EffectQueue.compute(queues, currTime);
497
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
498

    
499
    DistortedLibrary.mMainOITProgram.useProgram();
500
    GLES30.glUniform1i(DistortedLibrary.mMainOITTextureH, 0);
501
    GLES30.glUniform2ui(DistortedLibrary.mMainOITSizeH, surface.mWidth, surface.mHeight);
502
    GLES30.glUniform1ui(DistortedLibrary.mMainOITNumRecordsH, (int)(DistortedLibrary.mBufferSize*surface.mWidth*surface.mHeight) );
503
    mesh.bindVertexAttribs(DistortedLibrary.mMainOITProgram);
504

    
505
    float inflate     = mesh.getInflate();
506
    float distance    = surface.mDistance;
507
    float mipmap      = surface.mMipmap;
508
    float[] projection= surface.mProjectionMatrix;
509

    
510
    EffectQueue.send(queues, distance, mipmap, projection, inflate, mesh, 1 );
511
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
512

    
513
    if( mesh.getShowNormals() )
514
      {
515
      DistortedLibrary.mMainProgram.useProgram();
516
      EffectQueue.send(queues, distance, mipmap, projection, inflate, mesh, 0 );
517
      displayNormals(queues,mesh);
518
      }
519
    }
520

    
521
///////////////////////////////////////////////////////////////////////////////////////////////////
522

    
523
  static void drawPriv(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
524
    {
525
    if( mMainProgram!=null )
526
      {
527
      EffectQueue[] queues = effects.getQueues();
528

    
529
      EffectQueue.compute(queues, currTime);
530
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
531

    
532
      mMainProgram.useProgram();
533
      GLES30.glUniform1i(DistortedLibrary.mMainTextureH, 0);
534
      mesh.bindVertexAttribs(DistortedLibrary.mMainProgram);
535

    
536
      float inflate     = mesh.getInflate();
537
      float distance    = surface.mDistance;
538
      float mipmap      = surface.mMipmap;
539
      float[] projection= surface.mProjectionMatrix;
540

    
541
      EffectQueue.send(queues, distance, mipmap, projection, inflate, mesh, 0 );
542
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
543

    
544
      if( mesh.getShowNormals() ) displayNormals(queues,mesh);
545
      }
546
    }
547

    
548
///////////////////////////////////////////////////////////////////////////////////////////////////
549

    
550
  static void blitPriv(InternalOutputSurface surface)
551
    {
552
    if( mBlitProgram!=null )
553
      {
554
      mBlitProgram.useProgram();
555

    
556
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
557
      GLES30.glUniform1i(mBlitTextureH, 0);
558
      GLES30.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
559
      GLES30.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
560
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
561
      }
562
    }
563

    
564
///////////////////////////////////////////////////////////////////////////////////////////////////
565

    
566
  static void blitDepthPriv(InternalOutputSurface surface, float corrW, float corrH)
567
    {
568
    if( mBlitDepthProgram!=null )
569
      {
570
      mBlitDepthProgram.useProgram();
571

    
572
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
573
      GLES30.glUniform1i(mBlitDepthTextureH, 0);
574
      GLES30.glUniform1i(mBlitDepthDepthTextureH, 1);
575
      GLES30.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
576
      GLES30.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
577
      GLES30.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
578
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
579
      }
580
    }
581

    
582
///////////////////////////////////////////////////////////////////////////////////////////////////
583
// yes it is safe to be mixing 3.0 and 3.1 like that, senior members of the OpenGL discussions forum assert
584

    
585
  private static int printPreviousBuffer()
586
    {
587
    int counter = 0;
588

    
589
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
590
                                                                GLES30.GL_MAP_READ_BIT);
591
    if( atomicBuf!=null )
592
      {
593
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
594
      counter = atomicIntBuf.get(0);
595
      }
596
    else
597
      {
598
      Log.e("effects", "print: failed to map atomic buffer");
599
      }
600

    
601
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
602

    
603
    return counter;
604
    }
605

    
606
///////////////////////////////////////////////////////////////////////////////////////////////////
607

    
608
  private static void zeroBuffer()
609
    {
610
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
611
        GLES30.GL_MAP_WRITE_BIT|GLES30.GL_MAP_INVALIDATE_BUFFER_BIT);
612
    if( atomicBuf!=null )
613
      {
614
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
615
      atomicIntBuf.put(0,0);
616
      }
617
    else
618
      {
619
      Log.e("effects", "zero: failed to map atomic buffer");
620
      }
621

    
622
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
623
    }
624

    
625
///////////////////////////////////////////////////////////////////////////////////////////////////
626
// reset atomic counter to 0
627

    
628
  static int zeroOutAtomic()
629
    {
630
    int counter = 0;
631

    
632
    if( mAtomicCounter[0]<0 )
633
      {
634
      GLES30.glGenBuffers(DistortedLibrary.FBO_QUEUE_SIZE,mAtomicCounter,0);
635

    
636
      for(int i = 0; i< DistortedLibrary.FBO_QUEUE_SIZE; i++)
637
        {
638
        GLES30.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
639
        GLES30.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES30.GL_DYNAMIC_DRAW);
640
        zeroBuffer();
641
        }
642
      }
643

    
644
    // reading the value of the buffer on every frame would slow down rendering by
645
    // dialog_about 3%; doing it only once every 5 frames affects speed by less than 1%.
646
    if( mCurrBuffer==0 )
647
      {
648
      GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
649
      counter = printPreviousBuffer();
650
      }
651

    
652
    if( ++mCurrBuffer>= DistortedLibrary.FBO_QUEUE_SIZE ) mCurrBuffer = 0;
653

    
654
    GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
655
    zeroBuffer();
656

    
657
    return counter;
658
    }
659

    
660
///////////////////////////////////////////////////////////////////////////////////////////////////
661
// Pass1 of the OIT algorithm. Clear per-pixel head-pointers.
662

    
663
  static void oitClear(InternalOutputSurface surface, int counter)
664
    {
665
    if( mOITClearProgram!=null )
666
      {
667
      if( mLinkedListSSBO[0]<0 )
668
        {
669
        GLES30.glGenBuffers(1,mLinkedListSSBO,0);
670

    
671
        int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
672
        GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
673
        GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
674
        GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
675

    
676
        GLES30.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
677
        }
678

    
679
      // See if we have overflown the SSBO in one of the previous frames.
680
      // If yes, assume we need to make the SSBO larger.
681
      float overflow = counter/(mBufferSize*surface.mWidth*surface.mHeight);
682

    
683
      if( overflow>1.0f )
684
        {
685
        //android.util.Log.e("effects", "previous frame rendered "+counter+
686
        //                   " fragments, but there was only "+(mBufferSize*surface.mWidth*surface.mHeight)+" space");
687

    
688
        mBufferSize *= (int)(overflow+1.0f);
689
        int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
690
        GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
691
        GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
692
        GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
693
        }
694

    
695
      mOITClearProgram.useProgram();
696

    
697
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
698
      GLES30.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
699
      GLES30.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
700
      GLES30.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
701
      GLES30.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
702
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
703
      }
704
    }
705

    
706
///////////////////////////////////////////////////////////////////////////////////////////////////
707
// Pass2 of the OIT algorithm - build per-pixel linked lists.
708

    
709
  static void oitBuild(InternalOutputSurface surface, float corrW, float corrH)
710
    {
711
    if( mOITBuildProgram!=null )
712
      {
713
      mOITBuildProgram.useProgram();
714

    
715
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
716
      GLES30.glUniform1i(mOITBuildTextureH, 0);
717
      GLES30.glUniform1i(mOITBuildDepthTextureH, 1);
718
      GLES30.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
719
      GLES30.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
720
      GLES30.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
721
      GLES30.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
722
      GLES30.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
723
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
724
      }
725
    }
726

    
727
///////////////////////////////////////////////////////////////////////////////////////////////////
728
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
729

    
730
  static void oitCollapse(InternalOutputSurface surface, float corrW, float corrH)
731
    {
732
    if( mOITCollapseProgram!=null )
733
      {
734
      mOITCollapseProgram.useProgram();
735

    
736
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
737
      GLES30.glUniform1i(mOITCollapseDepthTextureH, 1);
738
      GLES30.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
739
      GLES30.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
740
      GLES30.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
741
      GLES30.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
742
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
743
      }
744
    }
745

    
746
///////////////////////////////////////////////////////////////////////////////////////////////////
747
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
748

    
749
  static void oitRender(InternalOutputSurface surface, float corrW, float corrH)
750
    {
751
    if( mOITRenderProgram!=null )
752
      {
753
      mOITRenderProgram.useProgram();
754

    
755
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
756
      GLES30.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
757
      GLES30.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
758
      GLES30.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
759
      GLES30.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
760
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
761
      }
762
    }
763

    
764
///////////////////////////////////////////////////////////////////////////////////////////////////
765

    
766
  static void setSSBOSize(float size)
767
    {
768
    mBufferSize = size;
769
    }
770

    
771
///////////////////////////////////////////////////////////////////////////////////////////////////
772
// ARM Mali driver r12 has problems when we keep swapping many FBOs (fixed in r22)
773
// PowerVR GE8100 / GE8300 compiler fails to compile OIT programs.
774

    
775
  private static void detectBuggyDrivers()
776
    {
777
    String vendor  = GLES30.glGetString(GLES30.GL_VENDOR);
778
    String version = GLES30.glGetString(GLES30.GL_VERSION);
779
    String renderer= GLES30.glGetString(GLES30.GL_RENDERER);
780

    
781
    /*
782
    android.util.Log.e("DISTORTED", "GLSL Version "+GLES30.glGetString(GLES31.GL_SHADING_LANGUAGE_VERSION));
783
    android.util.Log.e("DISTORTED", "GL Version "  +GLES30.glGetString(GLES31.GL_VERSION));
784
    android.util.Log.e("DISTORTED", "GL Vendor "   +GLES30.glGetString(GLES31.GL_VENDOR));
785
    android.util.Log.e("DISTORTED", "GL Renderer " +GLES30.glGetString(GLES31.GL_RENDERER));
786
    */
787

    
788
    if( vendor.contains("ARM") )
789
      {
790
      if( version.contains("r12") )
791
        {
792
        Log.e("DISTORTED", "You are running this on a ARM Mali driver r12.\nThis is a buggy driver, please update to r22. Problems with flashing expected.");
793
        }
794
      }
795
    else if( vendor.contains("Imagination") )
796
      {
797
      if( renderer.contains("GE8") )
798
        {
799
        Log.e("DISTORTED", "You are running this on a PowerVR GE8XXX.\nDue to a buggy compiler OIT rendering will not work");
800
        }
801
      }
802
    }
803

    
804
///////////////////////////////////////////////////////////////////////////////////////////////////
805
/**
806
 * Return OpenGL ES version supported by the hardware we are running on.
807
 * There are only two possibilities: 300 (OpenGL ES 3.0) or 310 (at least OpenGL ES 3.1)
808
 */
809
  static int getGLSL()
810
    {
811
    return mGLSL;
812
    }
813

    
814
///////////////////////////////////////////////////////////////////////////////////////////////////
815
/**
816
 * Have we successfully managed to compile the OIT programs?
817
 * Some hardware ( Imagination GE8100 / 8300, driver build 1.8@4490469 present in my HTC phone and,
818
 * sadly, Amazon Fire Stick 4K ) fails to compile the shaders. See relevant thread in Imagination's
819
 * support forum:
820
 *
821
 * https://forums.imgtec.com/t/ge8100-in-htc-desire-12-android-7-1-1-fragment-shader-fails-to-compile/2708
822
 */
823
  public static boolean OITCompilationSuccessful()
824
    {
825
    return mOITCompilationSuccessful;
826
    }
827

    
828
///////////////////////////////////////////////////////////////////////////////////////////////////
829
/**
830
 * Have we called onCreate yet, ie have we initialized the library?
831
 * @return <code>true</code> if the library is initialized and ready for action.
832
 */
833
  public static boolean isInitialized()
834
    {
835
    return mInitialized;
836
    }
837

    
838
///////////////////////////////////////////////////////////////////////////////////////////////////
839
/**
840
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
841
 * I.e. best called from GLSurfaceView.onCreate().
842
 * <p>
843
 * Needs to be called from a thread holding the OpenGL context.
844
 *   
845
 * @param context Context of the App using the library - used to open up Resources and read Shader code.
846
 */
847
  public static void onCreate(final Context context) throws Exception
848
    {
849
    final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
850
    final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
851

    
852
    int glESversion = configurationInfo.reqGlEsVersion;
853
    int major = glESversion >> 16;
854
    int minor = glESversion & 0xff;
855

    
856
    if( major< 3 )
857
      {
858
      mGLSL = 100*major + 10*minor;
859
      throw new VertexCompilationException("at least OpenGL ES 3.0 required, this device supports only "+major+"."+minor);
860
      }
861
    else
862
      {
863
      mGLSL = (major==3 && minor==0) ? 300 : 310;
864
      }
865

    
866
    android.util.Log.e("DISTORTED", "Using OpenGL ES "+major+"."+minor);
867
    mGLSL_VERSION = "#version "+mGLSL+" es\n";
868

    
869
    mInitialized = true;
870
    mOITCompilationSuccessful = false;
871

    
872
    detectBuggyDrivers();
873

    
874
    EffectMessageSender.startSending();
875

    
876
    final Resources resources = context.getResources();
877

    
878
    Exception exception=null;
879

    
880
    try
881
      {
882
      createPrograms(resources);
883
      }
884
    catch(Exception ex)
885
      {
886
      exception = ex;
887
      }
888

    
889
    try
890
      {
891
      createFullProgram(resources);
892
      }
893
    catch(Exception ex)
894
      {
895
      exception = ex;
896
      }
897

    
898
    if( mGLSL>=310)
899
      {
900
      try
901
        {
902
        createProgramsOIT(resources);
903
        mOITCompilationSuccessful = true;
904
        }
905
      catch(Exception ex)
906
        {
907
        exception = ex;
908
        }
909
      }
910

    
911
    try
912
      {
913
      EffectQueuePostprocess.createPrograms(resources, mGLSL);
914
      }
915
    catch(Exception ex)
916
      {
917
      exception = ex;
918
      }
919

    
920
    try
921
      {
922
      PostprocessEffect.createPrograms(mGLSL);
923
      }
924
    catch(Exception ex)
925
      {
926
      exception = ex;
927
      }
928

    
929
    if( exception!=null)
930
      {
931
      throw exception;
932
      }
933
    }
934

    
935
///////////////////////////////////////////////////////////////////////////////////////////////////
936
/**
937
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
938
 * Must be called from Activity.onPause().
939
 */
940
  public static void onPause()
941
    {
942
    InternalObject.onPause();
943

    
944
    mLinkedListSSBO[0]= -1;
945

    
946
    for(int i = 0; i< DistortedLibrary.FBO_QUEUE_SIZE; i++) mAtomicCounter[i] = -1;
947
    }
948

    
949
///////////////////////////////////////////////////////////////////////////////////////////////////
950
/**
951
 * Call this so that the Library can release its internal data structures.
952
 * Must be called from Activity.onDestroy(). 
953
 */
954
  public static void onDestroy()
955
    {
956
    InternalObject.onDestroy();
957
    InternalNodeData.onDestroy();
958
    InternalMaster.onDestroy();
959
    InternalOutputSurface.onDestroy();
960
    DistortedEffects.onDestroy();
961
    EffectQueue.onDestroy();
962
    Effect.onDestroy();
963
    EffectMessageSender.stopSending();
964

    
965
    mInitialized = false;
966
    }
967

    
968
///////////////////////////////////////////////////////////////////////////////////////////////////
969
/**
970
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
971
 * single (InputSurface,MeshBase) combo.
972
 *
973
 * @param type {@link EffectType}
974
 * @return The maximum number of effects of a given type.
975
 */
976
  @SuppressWarnings("unused")
977
  public static int getMax(EffectType type)
978
    {
979
    return EffectQueue.getMax(type.ordinal());
980
    }
981

    
982
///////////////////////////////////////////////////////////////////////////////////////////////////
983
/**
984
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
985
 * This can fail if:
986
 * <ul>
987
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
988
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
989
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link DistortedLibrary#onCreate}. After this
990
 *     time only decreasing the value of 'max' is permitted.
991
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
992
 * </ul>
993
 *
994
 * @param type {@link EffectType}
995
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
996
 *            than Byte.MAX_VALUE
997
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
998
 */
999
  @SuppressWarnings("unused")
1000
  public static boolean setMax(EffectType type, int max)
1001
    {
1002
    return EffectQueue.setMax(type.ordinal(),max);
1003
    }
1004
  }
(3-3/14)