Project

General

Profile

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

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

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.effectqueue.EffectQueueVertex;
39
import org.distorted.library.mesh.DeferredJobs;
40
import org.distorted.library.mesh.MeshBase;
41
import org.distorted.library.message.EffectMessageSender;
42
import org.distorted.library.program.DistortedProgram;
43
import org.distorted.library.program.VertexCompilationException;
44
import org.distorted.library.type.Dynamic;
45

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

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

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

    
120
  private static boolean mInitialized=false;
121

    
122
  //////////////////////////////////////////////////////////////////////////////////////////////
123
  /// MAIN PROGRAM ///
124
  private static DistortedProgram mMainProgram;
125
  private static int mMainTextureH;
126
  private static int mTransformFeedbackH;
127

    
128
  /// NORMAL PROGRAM /////
129
  private static DistortedProgram mNormalProgram;
130
  private static int mNormalProjectionH;
131

    
132
  /// MAIN OIT PROGRAM ///
133
  private static DistortedProgram mMainOITProgram;
134
  private static int mMainOITTextureH;
135
  private static int mMainOITSizeH;
136
  private static int mMainOITNumRecordsH;
137

    
138
  /// BLIT PROGRAM ///
139
  private static DistortedProgram mBlitProgram;
140
  private static int mBlitTextureH;
141
  private static int mBlitDepthH;
142
  private static final FloatBuffer mQuadPositions;
143

    
144
  /// FULL PROGRAM ///
145
  private static DistortedProgram mFullProgram;
146

    
147
  static
148
    {
149
    float[] positionData= { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
150
    mQuadPositions = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()).asFloatBuffer();
151
    mQuadPositions.put(positionData).position(0);
152
    }
153

    
154
  /// BLIT DEPTH PROGRAM ///
155
  private static DistortedProgram mBlitDepthProgram;
156
  private static int mBlitDepthTextureH;
157
  private static int mBlitDepthDepthTextureH;
158
  private static int mBlitDepthDepthH;
159
  private static int mBlitDepthTexCorrH;
160

    
161
  /// Program Handles ///
162
  private static int mMainProgramH, mFullProgramH, mMainOITProgramH;
163

    
164
  /// OIT SSBO BUFFER ///
165
  private static int[] mLinkedListSSBO = new int[1];
166
  private static int[] mAtomicCounter;
167
  private static int   mCurrBuffer;
168

    
169
  static
170
    {
171
    mLinkedListSSBO[0]= -1;
172
    mCurrBuffer       =  0;
173
    }
174

    
175
  ///////////////////////////////////////////////////////////////
176
  // meaning: allocate 1.0 screenful of places for transparent
177
  // fragments in the SSBO backing up the OIT render method.
178
  private static float mBufferSize=1.0f;
179

    
180
  /// OIT CLEAR PROGRAM ///
181
  private static DistortedProgram mOITClearProgram;
182
  private static int mOITClearDepthH;
183
  private static int mOITClearTexCorrH;
184
  private static int mOITClearSizeH;
185

    
186
  /// OIT BUILD PROGRAM ///
187
  private static DistortedProgram mOITBuildProgram;
188
  private static int mOITBuildTextureH;
189
  private static int mOITBuildDepthTextureH;
190
  private static int mOITBuildDepthH;
191
  private static int mOITBuildTexCorrH;
192
  private static int mOITBuildSizeH;
193
  private static int mOITBuildNumRecordsH;
194

    
195
  /// OIT COLLAPSE PROGRAM ///
196
  private static DistortedProgram mOITCollapseProgram;
197
  private static int mOITCollapseDepthTextureH;
198
  private static int mOITCollapseDepthH;
199
  private static int mOITCollapseTexCorrH;
200
  private static int mOITCollapseSizeH;
201

    
202
  /// OIT RENDER PROGRAM ///
203
  private static DistortedProgram mOITRenderProgram;
204
  private static int mOITRenderDepthH;
205
  private static int mOITRenderTexCorrH;
206
  private static int mOITRenderSizeH;
207

    
208
  /// END PROGRAMS //////
209

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

    
222
  private static ExceptionListener mListener;
223
  private static Resources mResources;
224
  private static int mMaxTextureSize;
225

    
226
///////////////////////////////////////////////////////////////////////////////////////////////////
227
// private: hide this from Javadoc
228

    
229
  private DistortedLibrary()
230
    {
231

    
232
    }
233

    
234
///////////////////////////////////////////////////////////////////////////////////////////////////
235

    
236
  private static void createMainProgram()
237
    {
238
    // MAIN PROGRAM ////////////////////////////////////
239
    final InputStream mainVertStream = mResources.openRawResource(R.raw.main_vertex_shader);
240
    final InputStream mainFragStream = mResources.openRawResource(R.raw.main_fragment_shader);
241

    
242
    int numF = FragmentEffect.getNumEnabled();
243
    int numV = VertexEffect.getNumEnabled();
244

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

    
248
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
249

    
250
    String enabledEffectV= VertexEffect.getGLSL();
251
    String enabledEffectF= FragmentEffect.getGLSL();
252

    
253
    String[] feedback = { "v_Position", "v_endPosition" };
254

    
255
    try
256
      {
257
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
258
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
259
      }
260
    catch(Exception e)
261
      {
262
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
263
      throw new RuntimeException(e.getMessage());
264
      }
265

    
266
    mMainProgramH = mMainProgram.getProgramHandle();
267
    EffectQueue.getUniforms(mMainProgramH,0);
268
    MeshBase.getUniforms(mMainProgramH,0);
269
    mMainTextureH= GLES30.glGetUniformLocation( mMainProgramH, "u_Texture");
270
    mTransformFeedbackH= GLES30.glGetUniformLocation( mMainProgramH, "u_TransformFeedback");
271

    
272
    // BLIT PROGRAM ////////////////////////////////////
273
    final InputStream blitVertStream = mResources.openRawResource(R.raw.blit_vertex_shader);
274
    final InputStream blitFragStream = mResources.openRawResource(R.raw.blit_fragment_shader);
275

    
276
    try
277
      {
278
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
279
      }
280
    catch(Exception e)
281
      {
282
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
283
      throw new RuntimeException(e.getMessage());
284
      }
285

    
286
    int blitProgramH = mBlitProgram.getProgramHandle();
287
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
288
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
289

    
290
    // BLIT DEPTH PROGRAM ////////////////////////////////////
291
    final InputStream blitDepthVertStream = mResources.openRawResource(R.raw.blit_depth_vertex_shader);
292
    final InputStream blitDepthFragStream = mResources.openRawResource(R.raw.blit_depth_fragment_shader);
293

    
294
    try
295
      {
296
      mBlitDepthProgram = new DistortedProgram(blitDepthVertStream,blitDepthFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
297
      }
298
    catch(Exception e)
299
      {
300
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH program: "+e.getMessage());
301
      throw new RuntimeException(e.getMessage());
302
      }
303

    
304
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
305
    mBlitDepthTextureH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Texture");
306
    mBlitDepthDepthTextureH = GLES30.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
307
    mBlitDepthDepthH        = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Depth");
308
    mBlitDepthTexCorrH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
309
    }
310

    
311
///////////////////////////////////////////////////////////////////////////////////////////////////
312

    
313
  private static void createNormalProgram(Resources resources)
314
    {
315
    // NORMAL PROGRAM //////////////////////////////////////
316
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
317
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
318

    
319
    try
320
      {
321
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
322
      }
323
    catch(Exception e)
324
      {
325
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
326
      throw new RuntimeException(e.getMessage());
327
      }
328

    
329
    int normalProgramH = mNormalProgram.getProgramHandle();
330
    mNormalProjectionH = GLES30.glGetUniformLocation( normalProgramH, "u_Projection");
331
    }
332

    
333
///////////////////////////////////////////////////////////////////////////////////////////////////
334

    
335
  private static void createFullProgram(Resources resources)
336
    {
337
    final InputStream fullVertStream = resources.openRawResource(R.raw.main_vertex_shader);
338
    final InputStream fullFragStream = resources.openRawResource(R.raw.main_fragment_shader);
339

    
340
    int numV = VertexEffect.getAllEnabled();
341

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

    
345
    fullVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
346

    
347
    String enabledEffectV= VertexEffect.getAllGLSL();
348
    String enabledEffectF= "{}";
349

    
350
    fullVertHeader += "#define PREAPPLY\n";
351

    
352
    String[] feedback = { "v_Position", "v_endPosition" };
353

    
354
    try
355
      {
356
      mFullProgram = new DistortedProgram(fullVertStream, fullFragStream, fullVertHeader, fullFragHeader,
357
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
358
      }
359
    catch(Exception e)
360
      {
361
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile FULL program: "+e.getMessage());
362
      throw new RuntimeException(e.getMessage());
363
      }
364

    
365
    mFullProgramH = mFullProgram.getProgramHandle();
366
    EffectQueue.getUniforms(mFullProgramH,3);
367
    MeshBase.getUniforms(mFullProgramH,3);
368
    }
369

    
370
///////////////////////////////////////////////////////////////////////////////////////////////////
371

    
372
  private static void createOITProgram(Resources resources)
373
    {
374
    // MAIN OIT PROGRAM ////////////////////////////////
375
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
376
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
377

    
378
    int numF = FragmentEffect.getNumEnabled();
379
    int numV = VertexEffect.getNumEnabled();
380

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

    
384
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
385

    
386
    String enabledEffectV= VertexEffect.getGLSL();
387
    String enabledEffectF= FragmentEffect.getGLSL();
388

    
389
    try
390
      {
391
      mMainOITProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
392
                                             enabledEffectV, enabledEffectF, mGLSL, null);
393
      }
394
    catch(Exception e)
395
      {
396
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN OIT program: "+e.getMessage());
397
      throw new RuntimeException(e.getMessage());
398
      }
399

    
400
    mMainOITProgramH = mMainOITProgram.getProgramHandle();
401
    EffectQueue.getUniforms(mMainOITProgramH,1);
402
    MeshBase.getUniforms(mMainOITProgramH,1);
403
    mMainOITTextureH    = GLES30.glGetUniformLocation( mMainOITProgramH, "u_Texture");
404
    mMainOITSizeH       = GLES30.glGetUniformLocation( mMainOITProgramH, "u_Size");
405
    mMainOITNumRecordsH = GLES30.glGetUniformLocation( mMainOITProgramH, "u_numRecords");
406

    
407
    // OIT CLEAR PROGRAM ////////////////////////////////////
408
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
409
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
410

    
411
    try
412
      {
413
      mOITClearProgram = new DistortedProgram(oitClearVertStream,oitClearFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
414
      }
415
    catch(Exception e)
416
      {
417
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT CLEAR program: "+e.getMessage());
418
      throw new RuntimeException(e.getMessage());
419
      }
420

    
421
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
422
    mOITClearDepthH        = GLES30.glGetUniformLocation( oitClearProgramH, "u_Depth");
423
    mOITClearTexCorrH      = GLES30.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
424
    mOITClearSizeH         = GLES30.glGetUniformLocation( oitClearProgramH, "u_Size");
425

    
426
    // OIT BUILD PROGRAM ////////////////////////////////////
427
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
428
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
429

    
430
    try
431
      {
432
      mOITBuildProgram = new DistortedProgram(oitBuildVertStream,oitBuildFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
433
      }
434
    catch(Exception e)
435
      {
436
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT BUILD program: "+e.getMessage());
437
      throw new RuntimeException(e.getMessage());
438
      }
439

    
440
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
441
    mOITBuildTextureH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Texture");
442
    mOITBuildDepthTextureH = GLES30.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
443
    mOITBuildDepthH        = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Depth");
444
    mOITBuildTexCorrH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
445
    mOITBuildSizeH         = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Size");
446
    mOITBuildNumRecordsH   = GLES30.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
447

    
448
    // OIT COLLAPSE PROGRAM ///////////////////////////
449
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
450
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
451

    
452
    try
453
      {
454
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
455
      }
456
    catch(Exception e)
457
      {
458
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
459
      throw new RuntimeException(e.getMessage());
460
      }
461

    
462
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
463
    mOITCollapseDepthTextureH = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
464
    mOITCollapseDepthH        = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
465
    mOITCollapseTexCorrH      = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
466
    mOITCollapseSizeH         = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Size");
467

    
468
    // OIT RENDER PROGRAM ///////////////////////////
469
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
470
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
471

    
472
    try
473
      {
474
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
475
      }
476
    catch(Exception e)
477
      {
478
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
479
      throw new RuntimeException(e.getMessage());
480
      }
481

    
482
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
483
    mOITRenderDepthH        = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Depth");
484
    mOITRenderTexCorrH      = GLES30.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
485
    mOITRenderSizeH         = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Size");
486
    }
487

    
488
///////////////////////////////////////////////////////////////////////////////////////////////////
489

    
490
  private static void displayNormals(float[] projection, MeshBase mesh)
491
    {
492
    if( mNormalProgram==null )
493
      {
494
      try
495
        {
496
        createNormalProgram(mResources);
497
        }
498
      catch(Exception ex)
499
        {
500
        mListener.distortedException(ex);
501
        return;
502
        }
503
      }
504

    
505
    int num = mesh.getNumVertices();
506
    int tfo = mesh.getTFO();
507

    
508
    GLES30.glUniform1i(DistortedLibrary.mTransformFeedbackH, 1);
509
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
510
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
511
    InternalRenderState.switchOffDrawing();
512
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
513
    InternalRenderState.restoreDrawing();
514
    GLES30.glEndTransformFeedback();
515
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
516

    
517
    mNormalProgram.useProgram();
518
    GLES30.glUniformMatrix4fv(mNormalProjectionH, 1, false, projection, 0);
519
    mesh.bindTransformAttribs(mNormalProgram);
520
    GLES30.glLineWidth(8.0f);
521
    GLES30.glDrawArrays(GLES30.GL_LINES, 0, 2*num);
522
    }
523

    
524
///////////////////////////////////////////////////////////////////////////////////////////////////
525
/**
526
 * Execute all VertexEffects and adjust all vertices
527
 *
528
 * @y.exclude
529
 */
530
  public static void adjustVertices(MeshBase mesh, EffectQueueVertex queue)
531
    {
532
    if( mFullProgram==null )
533
      {
534
      try
535
        {
536
        createFullProgram(mResources);
537
        }
538
      catch(Exception ex)
539
        {
540
        mListener.distortedException(ex);
541
        return;
542
        }
543
      }
544

    
545
    int num = mesh.getNumVertices();
546
    int tfo = mesh.getTFO();
547

    
548
    mFullProgram.useProgram();
549
    mesh.bindVertexAttribs(mFullProgram);
550
    queue.compute(1);
551
    queue.send(0.0f,3);
552
    mesh.send(mFullProgramH,3);
553

    
554
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
555
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
556
    InternalRenderState.switchOffDrawing();
557
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
558
    InternalRenderState.restoreDrawing();
559
    GLES30.glEndTransformFeedback();
560
    mesh.copyTransformToVertex();
561
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
562
    }
563

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

    
566
  static void drawPrivOIT(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
567
    {
568
    if( mMainOITProgram!=null )
569
      {
570
      EffectQueue[] queues = effects.getQueues();
571

    
572
      EffectQueue.compute(queues, currTime);
573
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
574

    
575
      mMainOITProgram.useProgram();
576
      GLES30.glUniform1i(mMainOITTextureH, 0);
577
      GLES30.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
578
      GLES30.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
579
      mesh.bindVertexAttribs(mMainOITProgram);
580
      mesh.send(mMainOITProgramH,1);
581

    
582
      float inflate     = mesh.getInflate();
583
      float distance    = surface.mDistance;
584
      float mipmap      = surface.mMipmap;
585
      float[] projection= surface.mProjectionMatrix;
586

    
587
      EffectQueue.send(queues, distance, mipmap, projection, inflate, 1 );
588
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
589

    
590
      if( mesh.getShowNormals() )
591
        {
592
        mMainProgram.useProgram();
593
        mesh.send(mMainProgramH,0);
594
        EffectQueue.send(queues, distance, mipmap, projection, inflate, 0 );
595
        displayNormals(projection,mesh);
596
        }
597
      }
598
    }
599

    
600
///////////////////////////////////////////////////////////////////////////////////////////////////
601

    
602
  static void drawPriv(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
603
    {
604
    if( mMainProgram!=null )
605
      {
606
      EffectQueue[] queues = effects.getQueues();
607

    
608
      EffectQueue.compute(queues, currTime);
609
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
610

    
611
      mMainProgram.useProgram();
612
      GLES30.glUniform1i(DistortedLibrary.mMainTextureH, 0);
613
      mesh.bindVertexAttribs(DistortedLibrary.mMainProgram);
614
      mesh.send(mMainProgramH,0);
615

    
616
      float inflate     = mesh.getInflate();
617
      float distance    = surface.mDistance;
618
      float mipmap      = surface.mMipmap;
619
      float[] projection= surface.mProjectionMatrix;
620

    
621
      EffectQueue.send(queues, distance, mipmap, projection, inflate, 0 );
622
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
623

    
624
      if( mesh.getShowNormals() ) displayNormals(projection,mesh);
625
      }
626
    }
627

    
628
///////////////////////////////////////////////////////////////////////////////////////////////////
629

    
630
  static void blitPriv(InternalOutputSurface surface)
631
    {
632
    if( mBlitProgram!=null )
633
      {
634
      mBlitProgram.useProgram();
635

    
636
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
637
      GLES30.glUniform1i(mBlitTextureH, 0);
638
      GLES30.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
639
      GLES30.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
640
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
641
      }
642
    }
643

    
644
///////////////////////////////////////////////////////////////////////////////////////////////////
645

    
646
  static void blitDepthPriv(InternalOutputSurface surface, float corrW, float corrH)
647
    {
648
    if( mBlitDepthProgram!=null )
649
      {
650
      mBlitDepthProgram.useProgram();
651

    
652
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
653
      GLES30.glUniform1i(mBlitDepthTextureH, 0);
654
      GLES30.glUniform1i(mBlitDepthDepthTextureH, 1);
655
      GLES30.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
656
      GLES30.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
657
      GLES30.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
658
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
659
      }
660
    }
661

    
662
///////////////////////////////////////////////////////////////////////////////////////////////////
663
// yes it is safe to be mixing 3.0 and 3.1 like that, senior members of the OpenGL discussions forum assert
664

    
665
  private static int printPreviousBuffer()
666
    {
667
    int counter = 0;
668

    
669
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
670
                                                                GLES30.GL_MAP_READ_BIT);
671
    if( atomicBuf!=null )
672
      {
673
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
674
      counter = atomicIntBuf.get(0);
675
      }
676
    else
677
      {
678
      Log.e("effects", "print: failed to map atomic buffer");
679
      }
680

    
681
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
682

    
683
    return counter;
684
    }
685

    
686
///////////////////////////////////////////////////////////////////////////////////////////////////
687

    
688
  private static void zeroBuffer()
689
    {
690
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
691
                                                                GLES30.GL_MAP_WRITE_BIT|GLES30.GL_MAP_INVALIDATE_BUFFER_BIT);
692
    if( atomicBuf!=null )
693
      {
694
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
695
      atomicIntBuf.put(0,0);
696
      }
697
    else
698
      {
699
      Log.e("effects", "zero: failed to map atomic buffer");
700
      }
701

    
702
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
703
    }
704

    
705
///////////////////////////////////////////////////////////////////////////////////////////////////
706
// reset atomic counter to 0
707

    
708
  static int zeroOutAtomic()
709
    {
710
    int counter = 0;
711

    
712
    if( mAtomicCounter==null )
713
      {
714
      mAtomicCounter = new int[mFBOQueueSize];
715

    
716
      GLES30.glGenBuffers(mFBOQueueSize,mAtomicCounter,0);
717

    
718
      for(int i=0; i<mFBOQueueSize; i++)
719
        {
720
        GLES30.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
721
        GLES30.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES30.GL_DYNAMIC_DRAW);
722
        zeroBuffer();
723
        }
724
      }
725

    
726
    // reading the value of the buffer on every frame would slow down rendering by
727
    // about 3%; doing it only once every 5 frames affects speed by less than 1%.
728
    if( mCurrBuffer==0 )
729
      {
730
      GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
731
      counter = printPreviousBuffer();
732
      }
733

    
734
    if( ++mCurrBuffer>=mFBOQueueSize ) mCurrBuffer = 0;
735

    
736
    GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
737
    zeroBuffer();
738

    
739
    return counter;
740
    }
741

    
742
///////////////////////////////////////////////////////////////////////////////////////////////////
743
// Pass1 of the OIT algorithm. Clear per-pixel head-pointers.
744

    
745
  static void oitClear(InternalOutputSurface surface, int counter)
746
    {
747
    if( mOITClearProgram==null )
748
      {
749
      if( mGLSL>=310 && !mOITCompilationAttempted )
750
        {
751
        mOITCompilationAttempted = true;
752

    
753
        try
754
          {
755
          createOITProgram(mResources);
756
          }
757
        catch(Exception ex)
758
          {
759
          mListener.distortedException(ex);
760
          return;
761
          }
762
        }
763
      else
764
        {
765
        return;
766
        }
767
      }
768

    
769
    if( mLinkedListSSBO[0]<0 )
770
      {
771
      GLES30.glGenBuffers(1,mLinkedListSSBO,0);
772

    
773
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
774
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
775
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
776
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
777

    
778
      GLES30.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
779
      }
780

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

    
785
    if( overflow>1.0f )
786
      {
787
      mBufferSize *= (int)(overflow+1.0f);
788
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
789
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
790
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
791
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
792
      }
793

    
794
    mOITClearProgram.useProgram();
795

    
796
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
797
    GLES30.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
798
    GLES30.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
799
    GLES30.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
800
    GLES30.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
801
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
802
    }
803

    
804
///////////////////////////////////////////////////////////////////////////////////////////////////
805
// Pass2 of the OIT algorithm - build per-pixel linked lists.
806

    
807
  static void oitBuild(InternalOutputSurface surface, float corrW, float corrH)
808
    {
809
    if( mOITBuildProgram!=null )
810
      {
811
      mOITBuildProgram.useProgram();
812

    
813
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
814
      GLES30.glUniform1i(mOITBuildTextureH, 0);
815
      GLES30.glUniform1i(mOITBuildDepthTextureH, 1);
816
      GLES30.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
817
      GLES30.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
818
      GLES30.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
819
      GLES30.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
820
      GLES30.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
821
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
822
      }
823
    }
824

    
825
///////////////////////////////////////////////////////////////////////////////////////////////////
826
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
827

    
828
  static void oitCollapse(InternalOutputSurface surface, float corrW, float corrH)
829
    {
830
    if( mOITCollapseProgram!=null )
831
      {
832
      mOITCollapseProgram.useProgram();
833

    
834
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
835
      GLES30.glUniform1i(mOITCollapseDepthTextureH, 1);
836
      GLES30.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
837
      GLES30.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
838
      GLES30.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
839
      GLES30.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
840
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
841
      }
842
    }
843

    
844
///////////////////////////////////////////////////////////////////////////////////////////////////
845
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
846

    
847
  static void oitRender(InternalOutputSurface surface, float corrW, float corrH)
848
    {
849
    if( mOITRenderProgram!=null )
850
      {
851
      mOITRenderProgram.useProgram();
852

    
853
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
854
      GLES30.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
855
      GLES30.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
856
      GLES30.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
857
      GLES30.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
858
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
859
      }
860
    }
861

    
862
///////////////////////////////////////////////////////////////////////////////////////////////////
863

    
864
  static void setSSBOSize(float size)
865
    {
866
    mBufferSize = size;
867
    }
868

    
869
///////////////////////////////////////////////////////////////////////////////////////////////////
870

    
871
  static int getQueueSize()
872
    {
873
    return mFBOQueueSize;
874
    }
875

    
876
///////////////////////////////////////////////////////////////////////////////////////////////////
877
// ARM Mali driver r12 has problems when we keep swapping many FBOs (fixed in r22)
878
// PowerVR GE8100 / GE8300 compiler fails to compile OIT programs.
879

    
880
  private static void detectBuggyDriversAndSetQueueSize(int queueSize)
881
    {
882
    String vendor  = GLES30.glGetString(GLES30.GL_VENDOR);
883
    String version = GLES30.glGetString(GLES30.GL_VERSION);
884
    String renderer= GLES30.glGetString(GLES30.GL_RENDERER);
885

    
886
    mFBOQueueSize = 1;
887

    
888
    if( vendor.contains("ARM") )
889
      {
890
      try
891
        {
892
        String regex = ".*r(\\d+)p\\d.*";
893
        Pattern pattern = Pattern.compile(regex);
894
        Matcher matcher = pattern.matcher(version);
895

    
896
        if( matcher.find() )
897
          {
898
          String driverVersion = matcher.group(1);
899

    
900
          if( driverVersion!=null )
901
            {
902
            int drvVersion = Integer.parseInt(driverVersion);
903

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

    
909
              mFBOQueueSize = queueSize;
910
              }
911
            }
912
          }
913
        }
914
      catch(Exception ex)
915
        {
916
        android.util.Log.e("library", "exception trying to pattern match version: "+ex.toString());
917
        }
918
      }
919
    else if( vendor.contains("Imagination") )
920
      {
921
      if( renderer.contains("GE8") )
922
        {
923
        Log.e("DISTORTED", "You are running this on a PowerVR GE8XXX.\nDue to a buggy compiler OIT rendering will not work");
924
        Log.e("DISTORTED", "GLSL Version "+GLES30.glGetString(GLES31.GL_SHADING_LANGUAGE_VERSION));
925
        }
926
      }
927
    }
928

    
929
///////////////////////////////////////////////////////////////////////////////////////////////////
930
/**
931
 * Return OpenGL ES version supported by the hardware we are running on.
932
 * There are only three possibilities: 300 (OpenGL ES 3.0) or 310 (at least OpenGL ES 3.1)
933
 * or 200 (OpenGL ES 2.0)
934
 */
935
  public static int getGLSL()
936
    {
937
    return mGLSL;
938
    }
939

    
940
///////////////////////////////////////////////////////////////////////////////////////////////////
941
/**
942
 * Have we called onCreate yet, ie have we initialized the library?
943
 * @return <code>true</code> if the library is initialized and ready for action.
944
 */
945
  public static boolean isInitialized()
946
    {
947
    return mInitialized;
948
    }
949

    
950
///////////////////////////////////////////////////////////////////////////////////////////////////
951
/**
952
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
953
 * I.e. best called from GLSurfaceView.onCreate().
954
 * <p>
955
 * Needs to be called from a thread holding the OpenGL context.
956
 *
957
 * @param context Context of the App using the library - used to open up Resources and read Shader code.
958
 * @param listener The library will send all (asynchronous!) exceptions there.
959
 */
960
  public static void onCreate(final Context context, final ExceptionListener listener)
961
    {
962
    onCreate(context,listener,4);
963
    }
964

    
965
///////////////////////////////////////////////////////////////////////////////////////////////////
966
/**
967
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
968
 * I.e. best called from GLSurfaceView.onCreate().
969
 * <p>
970
 * Needs to be called from a thread holding the OpenGL context.
971
 *   
972
 * @param context Context of the App using the library - used to open up Resources and read Shader code.
973
 * @param listener The library will send all (asynchronous!) exceptions there.
974
 * @param queueSize the size of the FBO queue, a workaround for the bug on Mali drivers.
975
 */
976
  public static void onCreate(final Context context, final ExceptionListener listener, int queueSize)
977
    {
978
    final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
979
    final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
980

    
981
    int glESversion = configurationInfo.reqGlEsVersion;
982
    int major = glESversion >> 16;
983
    int minor = glESversion & 0xff;
984

    
985
    mListener = listener;
986

    
987
    if( major< 3 )
988
      {
989
      mGLSL = 100*major + 10*minor;
990
      VertexCompilationException ex = new VertexCompilationException("at least OpenGL ES 3.0 required, this device supports only "+major+"."+minor);
991
      mListener.distortedException(ex);
992
      }
993
    else
994
      {
995
      mGLSL = (major==3 && minor==0) ? 300 : 310;
996
      }
997

    
998
    int[] maxTextureSize = new int[1];
999
    GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, maxTextureSize, 0);
1000
    mMaxTextureSize = maxTextureSize[0];
1001

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

    
1005
    mInitialized = true;
1006
    mOITCompilationAttempted = false;
1007

    
1008
    detectBuggyDriversAndSetQueueSize(queueSize);
1009

    
1010
    EffectMessageSender.startSending();
1011

    
1012
    mResources = context.getResources();
1013

    
1014
    try
1015
      {
1016
      createMainProgram();
1017
      }
1018
    catch(Exception ex)
1019
      {
1020
      mListener.distortedException(ex);
1021
      }
1022

    
1023
    try
1024
      {
1025
      EffectQueuePostprocess.createPrograms(mResources, mGLSL);
1026
      }
1027
    catch(Exception ex)
1028
      {
1029
      mListener.distortedException(ex);
1030
      }
1031

    
1032
    try
1033
      {
1034
      PostprocessEffect.createPrograms(mGLSL);
1035
      }
1036
    catch(Exception ex)
1037
      {
1038
      mListener.distortedException(ex);
1039
      }
1040
    }
1041

    
1042
///////////////////////////////////////////////////////////////////////////////////////////////////
1043
/**
1044
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1045
 * Must be called from Activity.onPause().
1046
 */
1047
  public static void onPause()
1048
    {
1049
    InternalObject.onPause();
1050
    Dynamic.onPause();
1051

    
1052
    mLinkedListSSBO[0]= -1;
1053
    mAtomicCounter = null;
1054

    
1055
    mNormalProgram     = null;
1056
    mMainOITProgram    = null;
1057
    mMainProgram       = null;
1058
    mFullProgram       = null;
1059
    mOITClearProgram   = null;
1060
    mOITBuildProgram   = null;
1061
    mOITCollapseProgram= null;
1062
    mOITRenderProgram  = null;
1063
    mBlitDepthProgram  = null;
1064
    mBlitProgram       = null;
1065
    }
1066

    
1067
///////////////////////////////////////////////////////////////////////////////////////////////////
1068
/**
1069
 * Call this so that the Library can release its internal data structures.
1070
 * Must be called from Activity.onDestroy(). 
1071
 */
1072
  public static void onDestroy()
1073
    {
1074
    if( mInitialized )
1075
      {
1076
      mInitialized = false;
1077
      mOITCompilationAttempted = false;
1078

    
1079
      InternalObject.onDestroy();
1080
      InternalNodeData.onDestroy();
1081
      InternalMaster.onDestroy();
1082
      InternalOutputSurface.onDestroy();
1083
      DistortedEffects.onDestroy();
1084
      EffectQueue.onDestroy();
1085
      Effect.onDestroy();
1086
      DeferredJobs.onDestroy();
1087
      EffectMessageSender.stopSending();
1088
      }
1089
    }
1090

    
1091
///////////////////////////////////////////////////////////////////////////////////////////////////
1092
/**
1093
 * Return the maximum size of the texture supported by the driver.
1094
 */
1095
  public static int getMaxTextureSize()
1096
    {
1097
    return mMaxTextureSize;
1098
    }
1099

    
1100
///////////////////////////////////////////////////////////////////////////////////////////////////
1101
/**
1102
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
1103
 * single (InputSurface,MeshBase) combo.
1104
 *
1105
 * @param type {@link EffectType}
1106
 * @return The maximum number of effects of a given type.
1107
 */
1108
  @SuppressWarnings("unused")
1109
  public static int getMax(EffectType type)
1110
    {
1111
    return EffectQueue.getMax(type.ordinal());
1112
    }
1113

    
1114
///////////////////////////////////////////////////////////////////////////////////////////////////
1115
/**
1116
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
1117
 * This can fail if:
1118
 * <ul>
1119
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
1120
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
1121
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link DistortedLibrary#onCreate}. After this
1122
 *     time only decreasing the value of 'max' is permitted.
1123
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
1124
 * </ul>
1125
 *
1126
 * @param type {@link EffectType}
1127
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
1128
 *            than Byte.MAX_VALUE
1129
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
1130
 */
1131
  @SuppressWarnings("unused")
1132
  public static boolean setMax(EffectType type, int max)
1133
    {
1134
    return EffectQueue.setMax(type.ordinal(),max);
1135
    }
1136
  }
(3-3/14)