Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedLibrary.java @ 178983f4

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski  leszek@koltunski.pl                                          //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// This library is free software; you can redistribute it and/or                                 //
7
// modify it under the terms of the GNU Lesser General Public                                    //
8
// License as published by the Free Software Foundation; either                                  //
9
// version 2.1 of the License, or (at your option) any later version.                            //
10
//                                                                                               //
11
// This library 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 GNU                             //
14
// Lesser General Public License for more details.                                               //
15
//                                                                                               //
16
// You should have received a copy of the GNU Lesser General Public                              //
17
// License along with this library; if not, write to the Free Software                           //
18
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA                //
19
///////////////////////////////////////////////////////////////////////////////////////////////////
20

    
21
package org.distorted.library.main;
22

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

    
31
import org.distorted.library.R;
32
import org.distorted.library.effect.Effect;
33
import org.distorted.library.effectqueue.EffectQueue;
34
import org.distorted.library.effectqueue.EffectQueuePostprocess;
35
import org.distorted.library.effect.EffectType;
36
import org.distorted.library.effect.FragmentEffect;
37
import org.distorted.library.effect.PostprocessEffect;
38
import org.distorted.library.effect.VertexEffect;
39
import org.distorted.library.effectqueue.EffectQueueVertex;
40
import org.distorted.library.mesh.DeferredJobs;
41
import org.distorted.library.mesh.MeshBase;
42
import org.distorted.library.message.EffectMessageSender;
43
import org.distorted.library.program.DistortedProgram;
44
import org.distorted.library.program.VertexCompilationException;
45
import org.distorted.library.type.Dynamic;
46

    
47
import java.io.InputStream;
48
import java.nio.ByteBuffer;
49
import java.nio.ByteOrder;
50
import java.nio.FloatBuffer;
51
import java.nio.IntBuffer;
52
import java.util.regex.Matcher;
53
import java.util.regex.Pattern;
54

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

    
101
  /**
102
   * When creating a DistortedScreen (which needs to have mFBOQueueSize FBOs attached), pass this
103
   * constant for 'numOfFBOs' and the number of backing FBOs will be taken from 'mFBOQueueSize'
104
   * (the value of which is most likely unknown at the time of creation of the Screen)
105
   */
106
  public static final int WAIT_FOR_FBO_QUEUE_SIZE = -1;
107
  /**
108
   * Work around bugs in ARM Mali driver by, instead to a single FBO, rendering to a circular queue
109
   * of mFBOQueueSize FBOs. (otherwise we sometimes get a 'full pipeline flush' and the end result
110
   * might be missing part of the Objects)
111
   *
112
   * This bug only exists on Mali driver r12. (or more precisely it's there in r12 but fixed in r22)
113
   *
114
   * https://community.arm.com/graphics/f/discussions/10285/opengl-es-3-1-on-mali-t880-flashes
115
   */
116
  private static int mFBOQueueSize;
117
  private static int mGLSL;
118
  private static String mGLSL_VERSION;
119
  private static boolean mOITCompilationAttempted, mNeedsTransformFeedback;
120

    
121
  private static int mMaxTextureSize         = Integer.MAX_VALUE;
122
  private static int mMaxNumberOfVerUniforms = Integer.MAX_VALUE;
123
  private static int mMaxNumberOfFraUniforms = Integer.MAX_VALUE;
124

    
125
  private static boolean mBuggyUBOs;
126
  private static String mVendor, mVersion, mRenderer;
127
  private static boolean mFastCompilationTF;
128

    
129
  //////////////////////////////////////////////////////////////////////////////////////////////
130
  /// MAIN PROGRAM ///
131
  private static DistortedProgram mMainProgram;
132
  private static int mMainTextureH;
133
  private static int mTransformFeedbackH;
134

    
135
  /// NORMAL PROGRAM /////
136
  private static DistortedProgram mNormalProgram;
137
  private static int mNormalProjectionH;
138

    
139
  /// MAIN OIT PROGRAM ///
140
  private static DistortedProgram mMainOITProgram;
141
  private static int mMainOITTextureH;
142
  private static int mMainOITSizeH;
143
  private static int mMainOITNumRecordsH;
144

    
145
  /// BLIT PROGRAM ///
146
  private static DistortedProgram mBlitProgram;
147
  private static int mBlitTextureH;
148
  private static int mBlitDepthH;
149
  private static final FloatBuffer mQuadPositions;
150

    
151
  /// FULL PROGRAM ///
152
  private static DistortedProgram mFullProgram;
153

    
154
  static
155
    {
156
    float[] positionData= { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
157
    mQuadPositions = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()).asFloatBuffer();
158
    mQuadPositions.put(positionData).position(0);
159
    }
160

    
161
  /// BLIT DEPTH PROGRAM ///
162
  private static DistortedProgram mBlitDepthProgram;
163
  private static int mBlitDepthTextureH;
164
  private static int mBlitDepthDepthTextureH;
165
  private static int mBlitDepthTexCorrH;
166

    
167
  /// Program Handles ///
168
  private static int mMainProgramH, mFullProgramH, mMainOITProgramH;
169

    
170
  /// OIT SSBO BUFFER ///
171
  private static int[] mLinkedListSSBO = new int[1];
172
  private static int[] mAtomicCounter;
173
  private static int   mCurrBuffer;
174

    
175
  static
176
    {
177
    mLinkedListSSBO[0]= -1;
178
    mCurrBuffer       =  0;
179
    }
180

    
181
  ///////////////////////////////////////////////////////////////
182
  // meaning: allocate 1.0 screenful of places for transparent
183
  // fragments in the SSBO backing up the OIT render method.
184
  private static float mBufferSize=1.0f;
185

    
186
  /// OIT CLEAR PROGRAM ///
187
  private static DistortedProgram mOITClearProgram;
188
  private static int mOITClearDepthH;
189
  private static int mOITClearTexCorrH;
190
  private static int mOITClearSizeH;
191

    
192
  /// OIT BUILD PROGRAM ///
193
  private static DistortedProgram mOITBuildProgram;
194
  private static int mOITBuildTextureH;
195
  private static int mOITBuildDepthTextureH;
196
  private static int mOITBuildDepthH;
197
  private static int mOITBuildTexCorrH;
198
  private static int mOITBuildSizeH;
199
  private static int mOITBuildNumRecordsH;
200

    
201
  /// OIT COLLAPSE PROGRAM ///
202
  private static DistortedProgram mOITCollapseProgram;
203
  private static int mOITCollapseDepthTextureH;
204
  private static int mOITCollapseDepthH;
205
  private static int mOITCollapseTexCorrH;
206
  private static int mOITCollapseSizeH;
207

    
208
  /// OIT RENDER PROGRAM ///
209
  private static DistortedProgram mOITRenderProgram;
210
  private static int mOITRenderDepthH;
211
  private static int mOITRenderTexCorrH;
212
  private static int mOITRenderSizeH;
213

    
214
  /// END PROGRAMS //////
215

    
216
  /**
217
   * Every application using the library must implement this interface so that the library can send
218
   * it exceptions that arise. The exceptions may come at any time, for example the library will
219
   * compile its OIT problem only on the first attempt to use the OIT
220
   * Those will mainly be hardware-related: shaders do not compile on particular hardware, the required
221
   * OpenGL ES 3.0 is not supported, etc.
222
   */
223
  public interface ExceptionListener
224
    {
225
    void distortedException(Exception ex);
226
    }
227

    
228
  private static ExceptionListener mListener;
229
  private static Resources mResources;
230

    
231
///////////////////////////////////////////////////////////////////////////////////////////////////
232
// private: hide this from Javadoc
233

    
234
  private DistortedLibrary()
235
    {
236

    
237
    }
238

    
239
///////////////////////////////////////////////////////////////////////////////////////////////////
240

    
241
  private static void createMainProgram()
242
    {
243
    // MAIN PROGRAM ////////////////////////////////////
244
    final InputStream mainVertStream = mResources.openRawResource(R.raw.main_vertex_shader);
245
    final InputStream mainFragStream = mResources.openRawResource(R.raw.main_fragment_shader);
246

    
247
    int numF = FragmentEffect.getNumEnabled();
248
    int numV = VertexEffect.getNumEnabled();
249

    
250
    String mainVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n");
251
    String mainFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n");
252

    
253
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
254
    if( MeshBase.getUseCenters() ) mainVertHeader += "#define COMP_CENTERS\n";
255
    if( mBuggyUBOs )               mainVertHeader += "#define BUGGY_UBOS\n";
256

    
257
    String enabledEffectV= VertexEffect.getGLSL();
258
    String enabledEffectF= FragmentEffect.getGLSL();
259

    
260
    String[] feedback = { "v_Position", "v_endPosition" };
261

    
262
    try
263
      {
264
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader,
265
                                          mainFragHeader, enabledEffectV, enabledEffectF,
266
                                          mGLSL, mNeedsTransformFeedback ? feedback : null );
267
      }
268
    catch(Exception e)
269
      {
270
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
271
      throw new RuntimeException(e.getMessage());
272
      }
273

    
274
    mMainProgramH = mMainProgram.getProgramHandle();
275
    EffectQueue.getUniforms(mMainProgramH,0);
276
    MeshBase.getUniforms(mMainProgramH,0);
277
    mMainTextureH= GLES30.glGetUniformLocation( mMainProgramH, "u_Texture");
278
    mTransformFeedbackH= GLES30.glGetUniformLocation( mMainProgramH, "u_TransformFeedback");
279

    
280
    // BLIT PROGRAM ////////////////////////////////////
281
    final InputStream blitVertStream = mResources.openRawResource(R.raw.blit_vertex_shader);
282
    final InputStream blitFragStream = mResources.openRawResource(R.raw.blit_fragment_shader);
283

    
284
    try
285
      {
286
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
287
      }
288
    catch(Exception e)
289
      {
290
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
291
      throw new RuntimeException(e.getMessage());
292
      }
293

    
294
    int blitProgramH = mBlitProgram.getProgramHandle();
295
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
296
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
297

    
298
    // BLIT DEPTH PROGRAM ////////////////////////////////////
299
    final InputStream blitDepthVertStream = mResources.openRawResource(R.raw.blit_depth_vertex_shader);
300
    final InputStream blitDepthFragStream = mResources.openRawResource(R.raw.blit_depth_fragment_shader);
301

    
302
    try
303
      {
304
      mBlitDepthProgram = new DistortedProgram(blitDepthVertStream,blitDepthFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
305
      }
306
    catch(Exception e)
307
      {
308
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH program: "+e.getMessage());
309
      throw new RuntimeException(e.getMessage());
310
      }
311

    
312
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
313
    mBlitDepthTextureH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Texture");
314
    mBlitDepthDepthTextureH = GLES30.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
315
    mBlitDepthTexCorrH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
316
    }
317

    
318
///////////////////////////////////////////////////////////////////////////////////////////////////
319

    
320
  private static void createNormalProgram(Resources resources)
321
    {
322
    // NORMAL PROGRAM //////////////////////////////////////
323
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
324
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
325

    
326
    try
327
      {
328
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
329
      }
330
    catch(Exception e)
331
      {
332
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
333
      throw new RuntimeException(e.getMessage());
334
      }
335

    
336
    int normalProgramH = mNormalProgram.getProgramHandle();
337
    mNormalProjectionH = GLES30.glGetUniformLocation( normalProgramH, "u_Projection");
338
    }
339

    
340
///////////////////////////////////////////////////////////////////////////////////////////////////
341

    
342
  private static void createFullProgram(Resources resources)
343
    {
344
    final InputStream fullVertStream = resources.openRawResource(R.raw.main_vertex_shader);
345
    final InputStream fullFragStream = resources.openRawResource(R.raw.main_fragment_shader);
346

    
347
    int numV = VertexEffect.getAllEnabled();
348

    
349
    String fullVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX ) : 0 ) + "\n");
350
    String fullFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " +                                         0   + "\n");
351

    
352
    fullVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
353
    if( MeshBase.getUseCenters() ) fullVertHeader += "#define COMP_CENTERS\n";
354
    if( mBuggyUBOs )               fullVertHeader += "#define BUGGY_UBOS\n";
355

    
356
    String enabledEffectV= VertexEffect.getAllGLSL();
357
    String enabledEffectF= "{}";
358

    
359
    fullVertHeader += "#define PREAPPLY\n";
360

    
361
    String[] feedback = { "v_Position", "v_endPosition" };
362

    
363
    try
364
      {
365
      mFullProgram = new DistortedProgram(fullVertStream, fullFragStream, fullVertHeader, fullFragHeader,
366
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
367
      }
368
    catch(Exception e)
369
      {
370
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile FULL program: "+e.getMessage());
371
      throw new RuntimeException(e.getMessage());
372
      }
373

    
374
    mFullProgramH = mFullProgram.getProgramHandle();
375
    EffectQueue.getUniforms(mFullProgramH,3);
376
    MeshBase.getUniforms(mFullProgramH,3);
377
    }
378

    
379
///////////////////////////////////////////////////////////////////////////////////////////////////
380

    
381
  private static void createOITProgram(Resources resources)
382
    {
383
    // MAIN OIT PROGRAM ////////////////////////////////
384
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
385
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
386

    
387
    int numF = FragmentEffect.getNumEnabled();
388
    int numV = VertexEffect.getNumEnabled();
389

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

    
393
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
394
    if( MeshBase.getUseCenters() ) mainVertHeader += "#define COMP_CENTERS\n";
395
    if( mBuggyUBOs )               mainVertHeader += "#define BUGGY_UBOS\n";
396

    
397
    String enabledEffectV= VertexEffect.getGLSL();
398
    String enabledEffectF= FragmentEffect.getGLSL();
399

    
400
    try
401
      {
402
      mMainOITProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
403
                                             enabledEffectV, enabledEffectF, mGLSL, null);
404
      }
405
    catch(Exception e)
406
      {
407
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN OIT program: "+e.getMessage());
408
      throw new RuntimeException(e.getMessage());
409
      }
410

    
411
    mMainOITProgramH = mMainOITProgram.getProgramHandle();
412
    EffectQueue.getUniforms(mMainOITProgramH,1);
413
    MeshBase.getUniforms(mMainOITProgramH,1);
414
    mMainOITTextureH    = GLES30.glGetUniformLocation( mMainOITProgramH, "u_Texture");
415
    mMainOITSizeH       = GLES30.glGetUniformLocation( mMainOITProgramH, "u_Size");
416
    mMainOITNumRecordsH = GLES30.glGetUniformLocation( mMainOITProgramH, "u_numRecords");
417

    
418
    // OIT CLEAR PROGRAM ////////////////////////////////////
419
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
420
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
421

    
422
    try
423
      {
424
      mOITClearProgram = new DistortedProgram(oitClearVertStream,oitClearFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
425
      }
426
    catch(Exception e)
427
      {
428
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT CLEAR program: "+e.getMessage());
429
      throw new RuntimeException(e.getMessage());
430
      }
431

    
432
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
433
    mOITClearDepthH        = GLES30.glGetUniformLocation( oitClearProgramH, "u_Depth");
434
    mOITClearTexCorrH      = GLES30.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
435
    mOITClearSizeH         = GLES30.glGetUniformLocation( oitClearProgramH, "u_Size");
436

    
437
    // OIT BUILD PROGRAM ////////////////////////////////////
438
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
439
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
440

    
441
    try
442
      {
443
      mOITBuildProgram = new DistortedProgram(oitBuildVertStream,oitBuildFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
444
      }
445
    catch(Exception e)
446
      {
447
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT BUILD program: "+e.getMessage());
448
      throw new RuntimeException(e.getMessage());
449
      }
450

    
451
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
452
    mOITBuildTextureH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Texture");
453
    mOITBuildDepthTextureH = GLES30.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
454
    mOITBuildDepthH        = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Depth");
455
    mOITBuildTexCorrH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
456
    mOITBuildSizeH         = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Size");
457
    mOITBuildNumRecordsH   = GLES30.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
458

    
459
    // OIT COLLAPSE PROGRAM ///////////////////////////
460
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
461
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
462

    
463
    try
464
      {
465
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
466
      }
467
    catch(Exception e)
468
      {
469
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
470
      throw new RuntimeException(e.getMessage());
471
      }
472

    
473
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
474
    mOITCollapseDepthTextureH = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
475
    mOITCollapseDepthH        = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
476
    mOITCollapseTexCorrH      = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
477
    mOITCollapseSizeH         = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Size");
478

    
479
    // OIT RENDER PROGRAM ///////////////////////////
480
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
481
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
482

    
483
    try
484
      {
485
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
486
      }
487
    catch(Exception e)
488
      {
489
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
490
      throw new RuntimeException(e.getMessage());
491
      }
492

    
493
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
494
    mOITRenderDepthH        = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Depth");
495
    mOITRenderTexCorrH      = GLES30.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
496
    mOITRenderSizeH         = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Size");
497
    }
498

    
499
///////////////////////////////////////////////////////////////////////////////////////////////////
500

    
501
  private static void displayNormals(float[] projection, MeshBase mesh)
502
    {
503
    if( mNormalProgram==null )
504
      {
505
      try
506
        {
507
        createNormalProgram(mResources);
508
        }
509
      catch(Exception ex)
510
        {
511
        mListener.distortedException(ex);
512
        return;
513
        }
514
      }
515

    
516
    int num = mesh.getNumVertices();
517
    int tfo = mesh.getTFO();
518

    
519
    GLES30.glUniform1i(DistortedLibrary.mTransformFeedbackH, 1);
520
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
521
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
522
    InternalRenderState.switchOffDrawing();
523
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
524
    InternalRenderState.restoreDrawing();
525
    GLES30.glEndTransformFeedback();
526
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
527
    GLES30.glUniform1i(DistortedLibrary.mTransformFeedbackH, 0);
528

    
529
    mNormalProgram.useProgram();
530
    GLES30.glUniformMatrix4fv(mNormalProjectionH, 1, false, projection, 0);
531
    mesh.bindTransformAttribs(mNormalProgram);
532
    GLES30.glLineWidth(8.0f);
533
    GLES30.glDrawArrays(GLES30.GL_LINES, 0, 2*num);
534
    mNormalProgram.stopUsingProgram();
535
    }
536

    
537
///////////////////////////////////////////////////////////////////////////////////////////////////
538
/**
539
 * Execute all VertexEffects and adjust all vertices
540
 *
541
 * @y.exclude
542
 */
543
  public static void adjustVertices(MeshBase mesh, EffectQueueVertex queue)
544
    {
545
    if( mFullProgram==null )
546
      {
547
      try
548
        {
549
        createFullProgram(mResources);
550
        }
551
      catch(Exception ex)
552
        {
553
        mListener.distortedException(ex);
554
        return;
555
        }
556
      }
557

    
558
    int num = mesh.getNumVertices();
559
    int tfo = mesh.getTFO();
560

    
561
    mFullProgram.useProgram();
562
    mesh.bindVertexAttribs(mFullProgram);
563
    queue.compute(1,0);
564
    queue.send(0.0f,mFullProgramH,3);
565
    mesh.send(mFullProgramH,3);
566

    
567
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
568
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
569
    InternalRenderState.switchOffDrawing();
570
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
571
    InternalRenderState.restoreDrawing();
572
    GLES30.glEndTransformFeedback();
573
    mesh.copyTransformToVertex();
574
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
575
    mFullProgram.stopUsingProgram();
576
    }
577

    
578
///////////////////////////////////////////////////////////////////////////////////////////////////
579

    
580
  static void drawPrivOIT(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime, long step)
581
    {
582
    if( mMainOITProgram!=null )
583
      {
584
      EffectQueue[] queues = effects.getQueues();
585

    
586
      EffectQueue.compute(queues, currTime, step);
587
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
588

    
589
      mMainOITProgram.useProgram();
590
      GLES30.glUniform1i(mMainOITTextureH, 0);
591
      GLES30.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
592
      GLES30.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
593
      mesh.bindVertexAttribs(mMainOITProgram);
594
      mesh.send(mMainOITProgramH,1);
595

    
596
      float inflate     = mesh.getInflate();
597
      float distance    = surface.mDistance;
598
      float mipmap      = surface.mMipmap;
599
      float[] projection= surface.mProjectionMatrix;
600

    
601
      EffectQueue.send(queues, mMainOITProgramH, distance, mipmap, projection, inflate, 1 );
602
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
603
      mMainOITProgram.stopUsingProgram();
604

    
605
      if( mesh.getShowNormals() ) displayNormals(projection,mesh);
606
      }
607
    }
608

    
609
///////////////////////////////////////////////////////////////////////////////////////////////////
610

    
611
  static void drawPriv(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime, long step)
612
    {
613
    if( mMainProgram!=null )
614
      {
615
      EffectQueue[] queues = effects.getQueues();
616

    
617
      EffectQueue.compute(queues, currTime, step);
618
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
619

    
620
      mMainProgram.useProgram();
621
      GLES30.glUniform1i(DistortedLibrary.mMainTextureH, 0);
622
      mesh.bindVertexAttribs(DistortedLibrary.mMainProgram);
623
      mesh.send(mMainProgramH,0);
624

    
625
      float inflate     = mesh.getInflate();
626
      float distance    = surface.mDistance;
627
      float mipmap      = surface.mMipmap;
628
      float[] projection= surface.mProjectionMatrix;
629

    
630
      EffectQueue.send(queues, mMainProgramH, distance, mipmap, projection, inflate, 0 );
631
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
632
      mMainProgram.stopUsingProgram();
633

    
634
      if( mesh.getShowNormals() ) displayNormals(projection,mesh);
635
      }
636
    }
637

    
638
///////////////////////////////////////////////////////////////////////////////////////////////////
639

    
640
  static void blitPriv(InternalOutputSurface surface)
641
    {
642
    if( mBlitProgram!=null )
643
      {
644
      mBlitProgram.useProgram();
645
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
646
      GLES30.glUniform1i(mBlitTextureH, 0);
647
      GLES30.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
648
      GLES30.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
649
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
650
      mBlitProgram.stopUsingProgram();
651
      }
652
    }
653

    
654
///////////////////////////////////////////////////////////////////////////////////////////////////
655

    
656
  static void blitDepthPriv(InternalOutputSurface surface, float corrW, float corrH)
657
    {
658
    if( mBlitDepthProgram!=null )
659
      {
660
      mBlitDepthProgram.useProgram();
661
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
662
      GLES30.glUniform1i(mBlitDepthTextureH, 0);
663
      GLES30.glUniform1i(mBlitDepthDepthTextureH, 1);
664
      GLES30.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
665
      GLES30.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
666
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
667
      mBlitDepthProgram.stopUsingProgram();
668
      }
669
    }
670

    
671
///////////////////////////////////////////////////////////////////////////////////////////////////
672
// yes it is safe to be mixing 3.0 and 3.1 like that, senior members of the OpenGL discussions forum assert
673

    
674
  private static int printPreviousBuffer()
675
    {
676
    int counter = 0;
677

    
678
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
679
                                                                GLES30.GL_MAP_READ_BIT);
680
    if( atomicBuf!=null )
681
      {
682
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
683
      counter = atomicIntBuf.get(0);
684
      }
685
    else
686
      {
687
      Log.e("effects", "print: failed to map atomic buffer");
688
      }
689

    
690
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
691

    
692
    return counter;
693
    }
694

    
695
///////////////////////////////////////////////////////////////////////////////////////////////////
696

    
697
  private static void zeroBuffer()
698
    {
699
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
700
                                                                GLES30.GL_MAP_WRITE_BIT|GLES30.GL_MAP_INVALIDATE_BUFFER_BIT);
701
    if( atomicBuf!=null )
702
      {
703
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
704
      atomicIntBuf.put(0,0);
705
      }
706
    else
707
      {
708
      Log.e("effects", "zero: failed to map atomic buffer");
709
      }
710

    
711
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
712
    }
713

    
714
///////////////////////////////////////////////////////////////////////////////////////////////////
715
// reset atomic counter to 0
716

    
717
  static int zeroOutAtomic()
718
    {
719
    int counter = 0;
720

    
721
    if( mAtomicCounter==null )
722
      {
723
      mAtomicCounter = new int[mFBOQueueSize];
724

    
725
      GLES30.glGenBuffers(mFBOQueueSize,mAtomicCounter,0);
726

    
727
      for(int i=0; i<mFBOQueueSize; i++)
728
        {
729
        GLES30.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
730
        GLES30.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES30.GL_DYNAMIC_DRAW);
731
        zeroBuffer();
732
        }
733
      }
734

    
735
    // reading the value of the buffer on every frame would slow down rendering by
736
    // about 3%; doing it only once every 5 frames affects speed by less than 1%.
737
    if( mCurrBuffer==0 )
738
      {
739
      GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
740
      counter = printPreviousBuffer();
741
      }
742

    
743
    if( ++mCurrBuffer>=mFBOQueueSize ) mCurrBuffer = 0;
744

    
745
    GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
746
    zeroBuffer();
747

    
748
    return counter;
749
    }
750

    
751
///////////////////////////////////////////////////////////////////////////////////////////////////
752
// Pass1 of the OIT algorithm. Clear per-pixel head-pointers.
753

    
754
  static void oitClear(InternalOutputSurface surface, int counter)
755
    {
756
    if( mOITClearProgram==null )
757
      {
758
      if( mGLSL>=310 && !mOITCompilationAttempted )
759
        {
760
        mOITCompilationAttempted = true;
761

    
762
        try
763
          {
764
          createOITProgram(mResources);
765
          }
766
        catch(Exception ex)
767
          {
768
          mListener.distortedException(ex);
769
          return;
770
          }
771
        }
772
      else
773
        {
774
        return;
775
        }
776
      }
777

    
778
    if( mLinkedListSSBO[0]<0 )
779
      {
780
      GLES30.glGenBuffers(1,mLinkedListSSBO,0);
781

    
782
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
783
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
784
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
785
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
786

    
787
      GLES30.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
788
      }
789

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

    
794
    if( overflow>1.0f )
795
      {
796
      mBufferSize *= (int)(overflow+1.0f);
797
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
798
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
799
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
800
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
801
      }
802

    
803
    mOITClearProgram.useProgram();
804
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
805
    GLES30.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
806
    GLES30.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
807
    GLES30.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
808
    GLES30.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
809
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
810
    mOITClearProgram.stopUsingProgram();
811
    }
812

    
813
///////////////////////////////////////////////////////////////////////////////////////////////////
814
// Pass2 of the OIT algorithm - build per-pixel linked lists.
815

    
816
  static void oitBuild(InternalOutputSurface surface, float corrW, float corrH)
817
    {
818
    if( mOITBuildProgram!=null )
819
      {
820
      mOITBuildProgram.useProgram();
821
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
822
      GLES30.glUniform1i(mOITBuildTextureH, 0);
823
      GLES30.glUniform1i(mOITBuildDepthTextureH, 1);
824
      GLES30.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
825
      GLES30.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
826
      GLES30.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
827
      GLES30.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
828
      GLES30.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
829
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
830
      mOITBuildProgram.stopUsingProgram();
831
      }
832
    }
833

    
834
///////////////////////////////////////////////////////////////////////////////////////////////////
835
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
836

    
837
  static void oitCollapse(InternalOutputSurface surface, float corrW, float corrH)
838
    {
839
    if( mOITCollapseProgram!=null )
840
      {
841
      mOITCollapseProgram.useProgram();
842
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
843
      GLES30.glUniform1i(mOITCollapseDepthTextureH, 1);
844
      GLES30.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
845
      GLES30.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
846
      GLES30.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
847
      GLES30.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
848
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
849
      mOITCollapseProgram.stopUsingProgram();
850
      }
851
    }
852

    
853
///////////////////////////////////////////////////////////////////////////////////////////////////
854
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
855

    
856
  static void oitRender(InternalOutputSurface surface, float corrW, float corrH)
857
    {
858
    if( mOITRenderProgram!=null )
859
      {
860
      mOITRenderProgram.useProgram();
861
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
862
      GLES30.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
863
      GLES30.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
864
      GLES30.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
865
      GLES30.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
866
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
867
      mOITRenderProgram.stopUsingProgram();
868
      }
869
    }
870

    
871
///////////////////////////////////////////////////////////////////////////////////////////////////
872

    
873
  static void setSSBOSize(float size)
874
    {
875
    mBufferSize = size;
876
    }
877

    
878
///////////////////////////////////////////////////////////////////////////////////////////////////
879

    
880
  static int getQueueSize()
881
    {
882
    return mFBOQueueSize;
883
    }
884

    
885
///////////////////////////////////////////////////////////////////////////////////////////////////
886

    
887
  private static int parseQualcommDriverVersion(String version)
888
    {
889
    int at = version.indexOf('@');
890

    
891
    if( at>=0 )
892
      {
893
      int dot = version.indexOf('.',at);
894

    
895
      if( dot>at+1 )
896
        {
897
        String ver = version.substring(at+1,dot);
898
        return Integer.parseInt(ver);
899
        }
900
      }
901

    
902
    return 0;
903
    }
904

    
905
///////////////////////////////////////////////////////////////////////////////////////////////////
906
// ARM Mali driver r12 has problems when we keep swapping many FBOs (fixed in r22)
907
// PowerVR GE8100 / GE8300 compiler fails to compile OIT programs.
908

    
909
  private static void detectBuggyDriversAndSetQueueSize(int queueSize)
910
    {
911
    mVendor  = GLES30.glGetString(GLES30.GL_VENDOR);
912
    mVersion = GLES30.glGetString(GLES30.GL_VERSION);
913
    mRenderer= GLES30.glGetString(GLES30.GL_RENDERER);
914

    
915
    mFBOQueueSize = 1;
916
    mFastCompilationTF = true;
917

    
918
    if( mVendor.contains("ARM") )
919
      {
920
      try
921
        {
922
        String regex = ".*r(\\d+)p\\d.*";
923
        Pattern pattern = Pattern.compile(regex);
924
        Matcher matcher = pattern.matcher(mVersion);
925

    
926
        if( matcher.find() )
927
          {
928
          String driverVersion = matcher.group(1);
929

    
930
          if( driverVersion!=null )
931
            {
932
            int drvVersion = Integer.parseInt(driverVersion);
933

    
934
            if( drvVersion<22 )
935
              {
936
              Log.e("DISTORTED", "You are running this on a ARM Mali driver r"+driverVersion+".\n" +
937
                    "This is a buggy driver, please update to r22. Inserting workaround which uses a lot of memory.");
938

    
939
              mFBOQueueSize = queueSize;
940
              }
941
            }
942
          }
943
        }
944
      catch(Exception ex)
945
        {
946
        android.util.Log.e("library", "exception trying to pattern match version: "+ex.toString());
947
        }
948
      }
949
    else if( mVendor.contains("Imagination") )
950
      {
951
      if( mRenderer.contains("GE8") )
952
        {
953
        Log.e("DISTORTED", "You are running this on a PowerVR GE8XXX.\nDue to a buggy compiler OIT rendering will not work");
954
        Log.e("DISTORTED", "GLSL Version "+GLES30.glGetString(GLES31.GL_SHADING_LANGUAGE_VERSION));
955
        }
956
      }
957
    else if( mVendor.contains("Qualcomm"))
958
      {
959
      int driverVersion = parseQualcommDriverVersion(mVersion);
960

    
961
      if( mRenderer.contains("308") && (driverVersion==331 || driverVersion==415) )
962
        {
963
        Log.e("DISTORTED", "You are running this on an Adreno 308 driver 331 or 415.\nStrange shit might happen.");
964
        mBuggyUBOs = true;
965
        }
966
      if( mGLSL<=300 && driverVersion<415 ) // This is only on old enough drivers, 84,95,100,104,140 and known bad, 415 is known good.
967
        {
968
        Log.e("DISTORTED", "Slow compilation of Transform Feedback programs!");
969
        mFastCompilationTF = false;
970
        }
971
      }
972
    }
973

    
974
///////////////////////////////////////////////////////////////////////////////////////////////////
975
/**
976
 * Return OpenGL ES version supported by the hardware we are running on.
977
 * There are only three possibilities: 300 (OpenGL ES 3.0) or 310 (at least OpenGL ES 3.1)
978
 * or 200 (OpenGL ES 2.0)
979
 */
980
  public static int getGLSL()
981
    {
982
    return mGLSL;
983
    }
984

    
985
///////////////////////////////////////////////////////////////////////////////////////////////////
986
/**
987
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
988
 * I.e. best called from GLSurfaceView.Renderer.onSurfaceCreated().
989
 * <p>
990
 * Needs to be called from a thread holding the OpenGL context.
991
 *
992
 * @param context  Context of the App using the library - used to open up Resources and read Shader code.
993
 * @param listener The library will send all (asynchronous!) exceptions there.
994
 */
995
  public static void onSurfaceCreated(final Context context, final ExceptionListener listener)
996
    {
997
    onSurfaceCreated(context,listener,4);
998
    }
999

    
1000
///////////////////////////////////////////////////////////////////////////////////////////////////
1001
/**
1002
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
1003
 * I.e. best called from GLSurfaceView.Renderer.onSurfaceCreated().
1004
 * <p>
1005
 * Needs to be called from a thread holding the OpenGL context.
1006
 *   
1007
 * @param context   Context of the App using the library - used to open up Resources and read Shader code.
1008
 * @param listener  The library will send all (asynchronous!) exceptions there.
1009
 * @param queueSize the size of the FBO queue, a workaround for the bug on Mali drivers. Use a small integer - 1,...,4
1010
 */
1011
  public static void onSurfaceCreated(final Context context, final ExceptionListener listener, int queueSize)
1012
    {
1013
    final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
1014
    final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
1015

    
1016
    int glESversion = configurationInfo.reqGlEsVersion;
1017
    int major = glESversion >> 16;
1018
    int minor = glESversion & 0xff;
1019

    
1020
    mListener = listener;
1021

    
1022
    if( major< 3 )
1023
      {
1024
      mGLSL = 100*major + 10*minor;
1025
      VertexCompilationException ex = new VertexCompilationException("at least OpenGL ES 3.0 required, this device supports only "+major+"."+minor);
1026
      mListener.distortedException(ex);
1027
      }
1028
    else
1029
      {
1030
      mGLSL = (major==3 && minor==0) ? 300 : 310;
1031
      }
1032

    
1033
    int[] tmp = new int[1];
1034
    GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, tmp, 0);
1035
    mMaxTextureSize = tmp[0];
1036
    GLES30.glGetIntegerv(GLES30.GL_MAX_VERTEX_UNIFORM_VECTORS  , tmp, 0);
1037
    mMaxNumberOfVerUniforms = tmp[0];
1038
    GLES30.glGetIntegerv(GLES30.GL_MAX_FRAGMENT_UNIFORM_VECTORS, tmp, 0);
1039
    mMaxNumberOfFraUniforms = tmp[0];
1040

    
1041
    android.util.Log.e("DISTORTED", "Using OpenGL ES "+major+"."+minor);
1042
/*
1043
    android.util.Log.e("DISTORTED", "max texture size: "+mMaxTextureSize);
1044
    android.util.Log.e("DISTORTED", "max num vert: "+mMaxNumberOfVerUniforms);
1045
    android.util.Log.e("DISTORTED", "max num frag: "+mMaxNumberOfFraUniforms);
1046
*/
1047
    mGLSL_VERSION = "#version "+mGLSL+" es\n";
1048

    
1049
    InternalStackFrameList.setInitialized(true);
1050
    mOITCompilationAttempted = false;
1051

    
1052
    detectBuggyDriversAndSetQueueSize(queueSize);
1053
    EffectMessageSender.startSending();
1054

    
1055
    mResources = context.getResources();
1056

    
1057
    try
1058
      {
1059
      createMainProgram();
1060
      }
1061
    catch(Exception ex)
1062
      {
1063
      mListener.distortedException(ex);
1064
      }
1065

    
1066
    try
1067
      {
1068
      EffectQueuePostprocess.createPrograms(mResources, mGLSL);
1069
      }
1070
    catch(Exception ex)
1071
      {
1072
      mListener.distortedException(ex);
1073
      }
1074

    
1075
    try
1076
      {
1077
      PostprocessEffect.createPrograms(mGLSL);
1078
      }
1079
    catch(Exception ex)
1080
      {
1081
      mListener.distortedException(ex);
1082
      }
1083
    }
1084

    
1085
///////////////////////////////////////////////////////////////////////////////////////////////////
1086
/**
1087
 * Switch face culling on/off
1088
 */
1089
  public static void setCull(boolean on)
1090
    {
1091
    if( on )
1092
      {
1093
      GLES30.glEnable(GLES30.GL_CULL_FACE);
1094
      GLES30.glCullFace(GLES30.GL_FRONT);
1095
      }
1096
    else
1097
      {
1098
      GLES30.glDisable(GLES30.GL_CULL_FACE);
1099
      }
1100
    }
1101

    
1102
///////////////////////////////////////////////////////////////////////////////////////////////////
1103
/**
1104
 * Call this so that the Library can initialize its internal data structures.
1105
 * Must be called from Activity.onCreate().
1106
 */
1107
  public static void onCreate()
1108
    {
1109
    onCreate(0);
1110
    }
1111

    
1112
///////////////////////////////////////////////////////////////////////////////////////////////////
1113
/**
1114
 * Call this so that the Library can initialize its internal data structures.
1115
 * Must be called from Activity.onCreate().
1116
 *
1117
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1118
 *           tell between Activities in case you're going to be using it from more than one.
1119
 */
1120
  public static void onCreate(long id)
1121
    {
1122
    InternalStackFrameList.onCreate(id);
1123
    }
1124

    
1125
///////////////////////////////////////////////////////////////////////////////////////////////////
1126
/**
1127
 * Call this so that the Library can resume its operations.
1128
 * Must be called from Activity.onResume().
1129
 */
1130
  public static void onResume()
1131
    {
1132
    onResume(0);
1133
    }
1134

    
1135
///////////////////////////////////////////////////////////////////////////////////////////////////
1136
/**
1137
 * Call this so that the Library can resume its operations.
1138
 * Must be called from Activity.onResume().
1139
 *
1140
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1141
 *           tell between Activities in case you're going to be using it from more than one.
1142
 */
1143
  public static void onResume(long id)
1144
    {
1145
    InternalStackFrameList.onResume(id);
1146
    }
1147

    
1148
///////////////////////////////////////////////////////////////////////////////////////////////////
1149
/**
1150
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1151
 * Must be called from Activity.onPause().
1152
 */
1153
  public static void onPause()
1154
    {
1155
    onPause(0);
1156
    }
1157

    
1158
///////////////////////////////////////////////////////////////////////////////////////////////////
1159
/**
1160
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1161
 * Must be called from Activity.onPause().
1162
 *
1163
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1164
 *           tell between Activities in case you're going to be using it from more than one.
1165
 */
1166
  public static void onPause(long id)
1167
    {
1168
    InternalStackFrameList.onPause(id);
1169

    
1170
    Dynamic.onPause();  // common for all frames
1171
    InternalOutputSurface.onPause();
1172
    Effect.onPause();
1173
    DeferredJobs.onPause();
1174

    
1175
    mOITCompilationAttempted = false;
1176
    mNeedsTransformFeedback  = false;
1177

    
1178
    mLinkedListSSBO[0]= -1;
1179
    mAtomicCounter = null;
1180

    
1181
    mNormalProgram     = null;
1182
    mMainOITProgram    = null;
1183
    mMainProgram       = null;
1184
    mFullProgram       = null;
1185
    mOITClearProgram   = null;
1186
    mOITBuildProgram   = null;
1187
    mOITCollapseProgram= null;
1188
    mOITRenderProgram  = null;
1189
    mBlitDepthProgram  = null;
1190
    mBlitProgram       = null;
1191
    }
1192

    
1193
///////////////////////////////////////////////////////////////////////////////////////////////////
1194
/**
1195
 * Call this so that the Library can release its internal data structures.
1196
 * Must be called from Activity.onDestroy().
1197
 */
1198
  public static void onDestroy()
1199
    {
1200
    onDestroy(0);
1201
    }
1202

    
1203
///////////////////////////////////////////////////////////////////////////////////////////////////
1204
/**
1205
 * Call this so that the Library can release its internal data structures.
1206
 * Must be called from Activity.onDestroy().
1207
 *
1208
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1209
 *           tell between Activities in case you're going to be using it from more than one.
1210
 */
1211
  public static void onDestroy(long id)
1212
    {
1213
    if( InternalStackFrameList.isInitialized() )
1214
      {
1215
      InternalStackFrameList.onDestroy(id);
1216
      }
1217
    }
1218

    
1219
///////////////////////////////////////////////////////////////////////////////////////////////////
1220
/**
1221
 * Some devices - Qualcomm's Adreno 3xx with drivers v. 84,95,100,104,140, and possibly more -
1222
 * suffer from a very slow compilation of GLSL program if said program includes Transform Feedback.
1223
 * Return true if the platform we are running on does not suffer from this problem.
1224
 */
1225
  public static boolean fastCompilationTF()
1226
    {
1227
    return mFastCompilationTF;
1228
    }
1229

    
1230
///////////////////////////////////////////////////////////////////////////////////////////////////
1231
/**
1232
 * Return the maximum size of the texture supported by the driver.
1233
 */
1234
  public static int getMaxTextureSize()
1235
    {
1236
    return mMaxTextureSize;
1237
    }
1238

    
1239
///////////////////////////////////////////////////////////////////////////////////////////////////
1240
/**
1241
 * Call this before calling onSurfaceCreated() if you want to access normal vectors in CPU.
1242
 */
1243
  public static void needTransformFeedback()
1244
    {
1245
    mNeedsTransformFeedback = true;
1246
    }
1247

    
1248
///////////////////////////////////////////////////////////////////////////////////////////////////
1249
/**
1250
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
1251
 * single (InputSurface,MeshBase) combo.
1252
 *
1253
 * @param type {@link EffectType}
1254
 * @return The maximum number of effects of a given type.
1255
 */
1256
  @SuppressWarnings("unused")
1257
  public static int getMax(EffectType type)
1258
    {
1259
    return EffectQueue.getMax(type.ordinal());
1260
    }
1261

    
1262
///////////////////////////////////////////////////////////////////////////////////////////////////
1263
/**
1264
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
1265
 * This can fail if:
1266
 * <ul>
1267
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
1268
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
1269
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link DistortedLibrary#onSurfaceCreated}. After this
1270
 *     time only decreasing the value of 'max' is permitted.
1271
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
1272
 * </ul>
1273
 *
1274
 * @param type {@link EffectType}
1275
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
1276
 *            than Byte.MAX_VALUE
1277
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
1278
 */
1279
  @SuppressWarnings("unused")
1280
  public static boolean setMax(EffectType type, int max)
1281
    {
1282
    return EffectQueue.setMax(type.ordinal(),max);
1283
    }
1284

    
1285
///////////////////////////////////////////////////////////////////////////////////////////////////
1286
/**
1287
 * Return a String defining the vendor of the graphics driver.
1288
 */
1289
  public static String getDriverVendor()
1290
    {
1291
    return mVendor;
1292
    }
1293

    
1294
///////////////////////////////////////////////////////////////////////////////////////////////////
1295
/**
1296
 * Return a String defining the version of the graphics driver.
1297
 */
1298
  public static String getDriverVersion()
1299
    {
1300
    return mVersion;
1301
    }
1302

    
1303
///////////////////////////////////////////////////////////////////////////////////////////////////
1304
/**
1305
 * Return a String defining the renderer of the graphics driver.
1306
 */
1307
  public static String getDriverRenderer()
1308
    {
1309
    return mRenderer;
1310
    }
1311
  }
(3-3/17)