Project

General

Profile

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

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

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

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

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

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

    
119
  private static boolean mInitialized=false;
120

    
121
  //////////////////////////////////////////////////////////////////////////////////////////////
122
  /// MAIN PROGRAM ///
123
  private static DistortedProgram mMainProgram;
124
  private static int mMainTextureH;
125

    
126
  /// NORMAL PROGRAM /////
127
  private static DistortedProgram mNormalProgram;
128
  private static int mNormalMVPMatrixH;
129

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

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

    
142
  /// FULL PROGRAM ///
143
  private static DistortedProgram mFullProgram;
144

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

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

    
159
  /// OIT SSBO BUFFER ///
160
  private static int[] mLinkedListSSBO = new int[1];
161
  private static int[] mAtomicCounter;
162
  private static int   mCurrBuffer;
163

    
164
  static
165
    {
166
    mLinkedListSSBO[0]= -1;
167
    mCurrBuffer       =  0;
168
    }
169

    
170
  ///////////////////////////////////////////////////////////////
171
  // meaning: allocate 1.0 screenful of places for transparent
172
  // fragments in the SSBO backing up the OIT render method.
173
  private static float mBufferSize=1.0f;
174

    
175
  /// OIT CLEAR PROGRAM ///
176
  private static DistortedProgram mOITClearProgram;
177
  private static int mOITClearDepthH;
178
  private static int mOITClearTexCorrH;
179
  private static int mOITClearSizeH;
180

    
181
  /// OIT BUILD PROGRAM ///
182
  private static DistortedProgram mOITBuildProgram;
183
  private static int mOITBuildTextureH;
184
  private static int mOITBuildDepthTextureH;
185
  private static int mOITBuildDepthH;
186
  private static int mOITBuildTexCorrH;
187
  private static int mOITBuildSizeH;
188
  private static int mOITBuildNumRecordsH;
189

    
190
  /// OIT COLLAPSE PROGRAM ///
191
  private static DistortedProgram mOITCollapseProgram;
192
  private static int mOITCollapseDepthTextureH;
193
  private static int mOITCollapseDepthH;
194
  private static int mOITCollapseTexCorrH;
195
  private static int mOITCollapseSizeH;
196

    
197
  /// OIT RENDER PROGRAM ///
198
  private static DistortedProgram mOITRenderProgram;
199
  private static int mOITRenderDepthH;
200
  private static int mOITRenderTexCorrH;
201
  private static int mOITRenderSizeH;
202

    
203
  /// END PROGRAMS //////
204

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

    
217
  private static ExceptionListener mListener;
218
  private static Resources mResources;
219

    
220
///////////////////////////////////////////////////////////////////////////////////////////////////
221
// private: hide this from Javadoc
222

    
223
  private DistortedLibrary()
224
    {
225

    
226
    }
227

    
228
///////////////////////////////////////////////////////////////////////////////////////////////////
229

    
230
  private static void createMainProgram()
231
    {
232
    // MAIN PROGRAM ////////////////////////////////////
233
    final InputStream mainVertStream = mResources.openRawResource(R.raw.main_vertex_shader);
234
    final InputStream mainFragStream = mResources.openRawResource(R.raw.main_fragment_shader);
235

    
236
    int numF = FragmentEffect.getNumEnabled();
237
    int numV = VertexEffect.getNumEnabled();
238

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

    
242
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
243

    
244
    String enabledEffectV= VertexEffect.getGLSL();
245
    String enabledEffectF= FragmentEffect.getGLSL();
246

    
247
    String[] feedback = { "v_Position", "v_endPosition" };
248

    
249
    try
250
      {
251
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
252
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
253
      }
254
    catch(Exception e)
255
      {
256
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
257
      throw new RuntimeException(e.getMessage());
258
      }
259

    
260
    int mainProgramH = mMainProgram.getProgramHandle();
261
    EffectQueue.getUniforms(mainProgramH,0);
262
    MeshBase.getUniforms(mainProgramH,0);
263
    mMainTextureH= GLES30.glGetUniformLocation( mainProgramH, "u_Texture");
264

    
265
    // BLIT PROGRAM ////////////////////////////////////
266
    final InputStream blitVertStream = mResources.openRawResource(R.raw.blit_vertex_shader);
267
    final InputStream blitFragStream = mResources.openRawResource(R.raw.blit_fragment_shader);
268

    
269
    try
270
      {
271
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
272
      }
273
    catch(Exception e)
274
      {
275
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
276
      throw new RuntimeException(e.getMessage());
277
      }
278

    
279
    int blitProgramH = mBlitProgram.getProgramHandle();
280
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
281
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
282

    
283
    // BLIT DEPTH PROGRAM ////////////////////////////////////
284
    final InputStream blitDepthVertStream = mResources.openRawResource(R.raw.blit_depth_vertex_shader);
285
    final InputStream blitDepthFragStream = mResources.openRawResource(R.raw.blit_depth_fragment_shader);
286

    
287
    try
288
      {
289
      mBlitDepthProgram = new DistortedProgram(blitDepthVertStream,blitDepthFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
290
      }
291
    catch(Exception e)
292
      {
293
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH program: "+e.getMessage());
294
      throw new RuntimeException(e.getMessage());
295
      }
296

    
297
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
298
    mBlitDepthTextureH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Texture");
299
    mBlitDepthDepthTextureH = GLES30.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
300
    mBlitDepthDepthH        = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Depth");
301
    mBlitDepthTexCorrH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
302
    }
303

    
304
///////////////////////////////////////////////////////////////////////////////////////////////////
305

    
306
  private static void createNormalProgram(Resources resources)
307
    {
308
    // NORMAL PROGRAM //////////////////////////////////////
309
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
310
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
311

    
312
    try
313
      {
314
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
315
      }
316
    catch(Exception e)
317
      {
318
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
319
      throw new RuntimeException(e.getMessage());
320
      }
321

    
322
    int normalProgramH = mNormalProgram.getProgramHandle();
323
    mNormalMVPMatrixH  = GLES30.glGetUniformLocation( normalProgramH, "u_MVPMatrix");
324
    }
325

    
326
///////////////////////////////////////////////////////////////////////////////////////////////////
327

    
328
  private static void createFullProgram(Resources resources)
329
    {
330
    final InputStream fullVertStream = resources.openRawResource(R.raw.main_vertex_shader);
331
    final InputStream fullFragStream = resources.openRawResource(R.raw.main_fragment_shader);
332

    
333
    int numV = VertexEffect.getAllEnabled();
334

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

    
338
    fullVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
339

    
340
    String enabledEffectV= VertexEffect.getAllGLSL();
341
    String enabledEffectF= "{}";
342

    
343
    fullVertHeader += "#define PREAPPLY\n";
344

    
345
    String[] feedback = { "v_Position", "v_endPosition", "v_Inflate" };
346

    
347
    try
348
      {
349
      mFullProgram = new DistortedProgram(fullVertStream, fullFragStream, fullVertHeader, fullFragHeader,
350
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
351
      }
352
    catch(Exception e)
353
      {
354
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile FULL program: "+e.getMessage());
355
      throw new RuntimeException(e.getMessage());
356
      }
357

    
358
    int fullProgramH = mFullProgram.getProgramHandle();
359
    EffectQueue.getUniforms(fullProgramH,3);
360
    MeshBase.getUniforms(fullProgramH,3);
361
    }
362

    
363
///////////////////////////////////////////////////////////////////////////////////////////////////
364

    
365
  private static void createOITProgram(Resources resources)
366
    {
367
    // MAIN OIT PROGRAM ////////////////////////////////
368
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
369
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
370

    
371
    int numF = FragmentEffect.getNumEnabled();
372
    int numV = VertexEffect.getNumEnabled();
373

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

    
377
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
378

    
379
    String enabledEffectV= VertexEffect.getGLSL();
380
    String enabledEffectF= FragmentEffect.getGLSL();
381

    
382
    try
383
      {
384
      mMainOITProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
385
                                             enabledEffectV, enabledEffectF, mGLSL, null);
386
      }
387
    catch(Exception e)
388
      {
389
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN OIT program: "+e.getMessage());
390
      throw new RuntimeException(e.getMessage());
391
      }
392

    
393
    int mainOITProgramH = mMainOITProgram.getProgramHandle();
394
    EffectQueue.getUniforms(mainOITProgramH,1);
395
    MeshBase.getUniforms(mainOITProgramH,1);
396
    mMainOITTextureH    = GLES30.glGetUniformLocation( mainOITProgramH, "u_Texture");
397
    mMainOITSizeH       = GLES30.glGetUniformLocation( mainOITProgramH, "u_Size");
398
    mMainOITNumRecordsH = GLES30.glGetUniformLocation( mainOITProgramH, "u_numRecords");
399

    
400
    // OIT CLEAR PROGRAM ////////////////////////////////////
401
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
402
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
403

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

    
414
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
415
    mOITClearDepthH        = GLES30.glGetUniformLocation( oitClearProgramH, "u_Depth");
416
    mOITClearTexCorrH      = GLES30.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
417
    mOITClearSizeH         = GLES30.glGetUniformLocation( oitClearProgramH, "u_Size");
418

    
419
    // OIT BUILD PROGRAM ////////////////////////////////////
420
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
421
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
422

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

    
433
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
434
    mOITBuildTextureH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Texture");
435
    mOITBuildDepthTextureH = GLES30.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
436
    mOITBuildDepthH        = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Depth");
437
    mOITBuildTexCorrH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
438
    mOITBuildSizeH         = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Size");
439
    mOITBuildNumRecordsH   = GLES30.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
440

    
441
    // OIT COLLAPSE PROGRAM ///////////////////////////
442
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
443
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
444

    
445
    try
446
      {
447
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
448
      }
449
    catch(Exception e)
450
      {
451
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
452
      throw new RuntimeException(e.getMessage());
453
      }
454

    
455
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
456
    mOITCollapseDepthTextureH = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
457
    mOITCollapseDepthH        = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
458
    mOITCollapseTexCorrH      = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
459
    mOITCollapseSizeH         = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Size");
460

    
461
    // OIT RENDER PROGRAM ///////////////////////////
462
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
463
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
464

    
465
    try
466
      {
467
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
468
      }
469
    catch(Exception e)
470
      {
471
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
472
      throw new RuntimeException(e.getMessage());
473
      }
474

    
475
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
476
    mOITRenderDepthH        = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Depth");
477
    mOITRenderTexCorrH      = GLES30.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
478
    mOITRenderSizeH         = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Size");
479
    }
480

    
481
///////////////////////////////////////////////////////////////////////////////////////////////////
482

    
483
  private static void displayNormals(EffectQueue[] queues, MeshBase mesh)
484
    {
485
    if( mNormalProgram==null )
486
      {
487
      try
488
        {
489
        createNormalProgram(mResources);
490
        }
491
      catch(Exception ex)
492
        {
493
        mListener.distortedException(ex);
494
        return;
495
        }
496
      }
497

    
498
    int num = mesh.getNumVertices();
499
    int tfo = mesh.getTFO();
500

    
501
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
502
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
503
    InternalRenderState.switchOffDrawing();
504
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
505
    InternalRenderState.restoreDrawing();
506
    GLES30.glEndTransformFeedback();
507
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
508

    
509
    mNormalProgram.useProgram();
510
    GLES30.glUniformMatrix4fv(mNormalMVPMatrixH, 1, false, EffectQueue.getMVP(queues) , 0);
511
    mesh.bindTransformAttribs(mNormalProgram);
512
    GLES30.glLineWidth(8.0f);
513
    GLES30.glDrawArrays(GLES30.GL_LINES, 0, 2*num);
514
    }
515

    
516
///////////////////////////////////////////////////////////////////////////////////////////////////
517
// execute all VertexEffects and adjust all vertices
518

    
519
  public static void adjustVertices(MeshBase mesh, EffectQueueVertex queue)
520
    {
521
    if( mFullProgram==null )
522
      {
523
      try
524
        {
525
        createFullProgram(mResources);
526
        }
527
      catch(Exception ex)
528
        {
529
        mListener.distortedException(ex);
530
        return;
531
        }
532
      }
533

    
534
    int num = mesh.getNumVertices();
535
    int tfo = mesh.getTFO();
536

    
537
    mFullProgram.useProgram();
538
    mesh.bindVertexAttribs(mFullProgram);
539
    queue.compute(1);
540
    queue.send(0.0f,3);
541
    mesh.send(3);
542

    
543
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
544
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
545
    InternalRenderState.switchOffDrawing();
546
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
547
    InternalRenderState.restoreDrawing();
548
    GLES30.glEndTransformFeedback();
549
    mesh.copyTransformToVertex();
550
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
551
    }
552

    
553
///////////////////////////////////////////////////////////////////////////////////////////////////
554

    
555
  static void drawPrivOIT(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
556
    {
557
    EffectQueue[] queues = effects.getQueues();
558

    
559
    EffectQueue.compute(queues, currTime);
560
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
561

    
562
    mMainOITProgram.useProgram();
563
    GLES30.glUniform1i(mMainOITTextureH, 0);
564
    GLES30.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
565
    GLES30.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
566
    mesh.bindVertexAttribs(mMainOITProgram);
567
    mesh.send(1);
568

    
569
    float inflate     = mesh.getInflate();
570
    float distance    = surface.mDistance;
571
    float mipmap      = surface.mMipmap;
572
    float[] projection= surface.mProjectionMatrix;
573

    
574
    EffectQueue.send(queues, distance, mipmap, projection, inflate, mesh, 1 );
575
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
576

    
577
    if( mesh.getShowNormals() )
578
      {
579
      mMainProgram.useProgram();
580
      mesh.send(0);
581
      EffectQueue.send(queues, distance, mipmap, projection, inflate, mesh, 0 );
582
      displayNormals(queues,mesh);
583
      }
584
    }
585

    
586
///////////////////////////////////////////////////////////////////////////////////////////////////
587

    
588
  static void drawPriv(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
589
    {
590
    if( mMainProgram!=null )
591
      {
592
      EffectQueue[] queues = effects.getQueues();
593

    
594
      EffectQueue.compute(queues, currTime);
595
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
596

    
597
      mMainProgram.useProgram();
598
      GLES30.glUniform1i(DistortedLibrary.mMainTextureH, 0);
599
      mesh.bindVertexAttribs(DistortedLibrary.mMainProgram);
600
      mesh.send(0);
601

    
602
      float inflate     = mesh.getInflate();
603
      float distance    = surface.mDistance;
604
      float mipmap      = surface.mMipmap;
605
      float[] projection= surface.mProjectionMatrix;
606

    
607
      EffectQueue.send(queues, distance, mipmap, projection, inflate, mesh, 0 );
608
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
609

    
610
      if( mesh.getShowNormals() ) displayNormals(queues,mesh);
611
      }
612
    }
613

    
614
///////////////////////////////////////////////////////////////////////////////////////////////////
615

    
616
  static void blitPriv(InternalOutputSurface surface)
617
    {
618
    if( mBlitProgram!=null )
619
      {
620
      mBlitProgram.useProgram();
621

    
622
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
623
      GLES30.glUniform1i(mBlitTextureH, 0);
624
      GLES30.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
625
      GLES30.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
626
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
627
      }
628
    }
629

    
630
///////////////////////////////////////////////////////////////////////////////////////////////////
631

    
632
  static void blitDepthPriv(InternalOutputSurface surface, float corrW, float corrH)
633
    {
634
    if( mBlitDepthProgram!=null )
635
      {
636
      mBlitDepthProgram.useProgram();
637

    
638
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
639
      GLES30.glUniform1i(mBlitDepthTextureH, 0);
640
      GLES30.glUniform1i(mBlitDepthDepthTextureH, 1);
641
      GLES30.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
642
      GLES30.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
643
      GLES30.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
644
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
645
      }
646
    }
647

    
648
///////////////////////////////////////////////////////////////////////////////////////////////////
649
// yes it is safe to be mixing 3.0 and 3.1 like that, senior members of the OpenGL discussions forum assert
650

    
651
  private static int printPreviousBuffer()
652
    {
653
    int counter = 0;
654

    
655
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
656
                                                                GLES30.GL_MAP_READ_BIT);
657
    if( atomicBuf!=null )
658
      {
659
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
660
      counter = atomicIntBuf.get(0);
661
      }
662
    else
663
      {
664
      Log.e("effects", "print: failed to map atomic buffer");
665
      }
666

    
667
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
668

    
669
    return counter;
670
    }
671

    
672
///////////////////////////////////////////////////////////////////////////////////////////////////
673

    
674
  private static void zeroBuffer()
675
    {
676
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
677
        GLES30.GL_MAP_WRITE_BIT|GLES30.GL_MAP_INVALIDATE_BUFFER_BIT);
678
    if( atomicBuf!=null )
679
      {
680
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
681
      atomicIntBuf.put(0,0);
682
      }
683
    else
684
      {
685
      Log.e("effects", "zero: failed to map atomic buffer");
686
      }
687

    
688
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
689
    }
690

    
691
///////////////////////////////////////////////////////////////////////////////////////////////////
692
// reset atomic counter to 0
693

    
694
  static int zeroOutAtomic()
695
    {
696
    int counter = 0;
697

    
698
    if( mAtomicCounter==null )
699
      {
700
      mAtomicCounter = new int[mFBOQueueSize];
701

    
702
      GLES30.glGenBuffers(mFBOQueueSize,mAtomicCounter,0);
703

    
704
      for(int i=0; i<mFBOQueueSize; i++)
705
        {
706
        GLES30.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
707
        GLES30.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES30.GL_DYNAMIC_DRAW);
708
        zeroBuffer();
709
        }
710
      }
711

    
712
    // reading the value of the buffer on every frame would slow down rendering by
713
    // about 3%; doing it only once every 5 frames affects speed by less than 1%.
714
    if( mCurrBuffer==0 )
715
      {
716
      GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
717
      counter = printPreviousBuffer();
718
      }
719

    
720
    if( ++mCurrBuffer>=mFBOQueueSize ) mCurrBuffer = 0;
721

    
722
    GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
723
    zeroBuffer();
724

    
725
    return counter;
726
    }
727

    
728
///////////////////////////////////////////////////////////////////////////////////////////////////
729
// Pass1 of the OIT algorithm. Clear per-pixel head-pointers.
730

    
731
  static void oitClear(InternalOutputSurface surface, int counter)
732
    {
733
    if( mOITClearProgram==null )
734
      {
735
      android.util.Log.e("aa", "attempting OIT compilation");
736

    
737
      if( mGLSL>=310 && !mOITCompilationAttempted )
738
        {
739
        mOITCompilationAttempted = true;
740

    
741
        try
742
          {
743
          createOITProgram(mResources);
744
          }
745
        catch(Exception ex)
746
          {
747
          mListener.distortedException(ex);
748
          return;
749
          }
750

    
751
        android.util.Log.e("aa", "OIT compilation successfull");
752
        }
753
      else
754
        {
755
        return;
756
        }
757
      }
758

    
759
    if( mLinkedListSSBO[0]<0 )
760
      {
761
      GLES30.glGenBuffers(1,mLinkedListSSBO,0);
762

    
763
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
764
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
765
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
766
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
767

    
768
      GLES30.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
769
      }
770

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

    
775
    if( overflow>1.0f )
776
      {
777
      mBufferSize *= (int)(overflow+1.0f);
778
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
779
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
780
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
781
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
782
      }
783

    
784
    mOITClearProgram.useProgram();
785

    
786
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
787
    GLES30.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
788
    GLES30.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
789
    GLES30.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
790
    GLES30.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
791
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
792
    }
793

    
794
///////////////////////////////////////////////////////////////////////////////////////////////////
795
// Pass2 of the OIT algorithm - build per-pixel linked lists.
796

    
797
  static void oitBuild(InternalOutputSurface surface, float corrW, float corrH)
798
    {
799
    if( mOITBuildProgram!=null )
800
      {
801
      mOITBuildProgram.useProgram();
802

    
803
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
804
      GLES30.glUniform1i(mOITBuildTextureH, 0);
805
      GLES30.glUniform1i(mOITBuildDepthTextureH, 1);
806
      GLES30.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
807
      GLES30.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
808
      GLES30.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
809
      GLES30.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
810
      GLES30.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
811
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
812
      }
813
    }
814

    
815
///////////////////////////////////////////////////////////////////////////////////////////////////
816
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
817

    
818
  static void oitCollapse(InternalOutputSurface surface, float corrW, float corrH)
819
    {
820
    if( mOITCollapseProgram!=null )
821
      {
822
      mOITCollapseProgram.useProgram();
823

    
824
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
825
      GLES30.glUniform1i(mOITCollapseDepthTextureH, 1);
826
      GLES30.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
827
      GLES30.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
828
      GLES30.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
829
      GLES30.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
830
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
831
      }
832
    }
833

    
834
///////////////////////////////////////////////////////////////////////////////////////////////////
835
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
836

    
837
  static void oitRender(InternalOutputSurface surface, float corrW, float corrH)
838
    {
839
    if( mOITRenderProgram!=null )
840
      {
841
      mOITRenderProgram.useProgram();
842

    
843
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
844
      GLES30.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
845
      GLES30.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
846
      GLES30.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
847
      GLES30.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
848
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
849
      }
850
    }
851

    
852
///////////////////////////////////////////////////////////////////////////////////////////////////
853

    
854
  static void setSSBOSize(float size)
855
    {
856
    mBufferSize = size;
857
    }
858

    
859
///////////////////////////////////////////////////////////////////////////////////////////////////
860

    
861
  static int getQueueSize()
862
    {
863
    return mFBOQueueSize;
864
    }
865

    
866
///////////////////////////////////////////////////////////////////////////////////////////////////
867
// ARM Mali driver r12 has problems when we keep swapping many FBOs (fixed in r22)
868
// PowerVR GE8100 / GE8300 compiler fails to compile OIT programs.
869

    
870
  private static void detectBuggyDriversAndSetQueueSize(int queueSize)
871
    {
872
    String vendor  = GLES30.glGetString(GLES30.GL_VENDOR);
873
    String version = GLES30.glGetString(GLES30.GL_VERSION);
874
    String renderer= GLES30.glGetString(GLES30.GL_RENDERER);
875

    
876
    mFBOQueueSize = 1;
877

    
878
    if( vendor.contains("ARM") )
879
      {
880
      try
881
        {
882
        String regex = ".*r(\\d+)p\\d.*";
883
        Pattern pattern = Pattern.compile(regex);
884
        Matcher matcher = pattern.matcher(version);
885

    
886
        if( matcher.find() )
887
          {
888
          String driverVersion = matcher.group(1);
889

    
890
          if( driverVersion!=null )
891
            {
892
            int drvVersion = Integer.parseInt(driverVersion);
893

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

    
899
              mFBOQueueSize = queueSize;
900
              }
901
            }
902
          }
903
        }
904
      catch(Exception ex)
905
        {
906
        android.util.Log.e("library", "exception trying to pattern match version: "+ex.toString());
907
        }
908
      }
909
    else if( vendor.contains("Imagination") )
910
      {
911
      if( renderer.contains("GE8") )
912
        {
913
        Log.e("DISTORTED", "You are running this on a PowerVR GE8XXX.\nDue to a buggy compiler OIT rendering will not work");
914
        Log.e("DISTORTED", "GLSL Version "+GLES30.glGetString(GLES31.GL_SHADING_LANGUAGE_VERSION));
915
        }
916
      }
917
    }
918

    
919
///////////////////////////////////////////////////////////////////////////////////////////////////
920
/**
921
 * Return OpenGL ES version supported by the hardware we are running on.
922
 * There are only three possibilities: 300 (OpenGL ES 3.0) or 310 (at least OpenGL ES 3.1)
923
 * or 200 (OpenGL ES 2.0)
924
 */
925
  public static int getGLSL()
926
    {
927
    return mGLSL;
928
    }
929

    
930
///////////////////////////////////////////////////////////////////////////////////////////////////
931
/**
932
 * Have we called onCreate yet, ie have we initialized the library?
933
 * @return <code>true</code> if the library is initialized and ready for action.
934
 */
935
  public static boolean isInitialized()
936
    {
937
    return mInitialized;
938
    }
939

    
940
///////////////////////////////////////////////////////////////////////////////////////////////////
941
/**
942
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
943
 * I.e. best called from GLSurfaceView.onCreate().
944
 * <p>
945
 * Needs to be called from a thread holding the OpenGL context.
946
 *
947
 * @param context Context of the App using the library - used to open up Resources and read Shader code.
948
 * @param listener The library will send all (asynchronous!) exceptions there.
949
 */
950
  public static void onCreate(final Context context, final ExceptionListener listener)
951
    {
952
    onCreate(context,listener,4);
953
    }
954

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

    
971
    int glESversion = configurationInfo.reqGlEsVersion;
972
    int major = glESversion >> 16;
973
    int minor = glESversion & 0xff;
974

    
975
    mListener = listener;
976

    
977
    if( major< 3 )
978
      {
979
      mGLSL = 100*major + 10*minor;
980
      VertexCompilationException ex = new VertexCompilationException("at least OpenGL ES 3.0 required, this device supports only "+major+"."+minor);
981
      mListener.distortedException(ex);
982
      }
983
    else
984
      {
985
      mGLSL = (major==3 && minor==0) ? 300 : 310;
986
      }
987

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

    
991
    mInitialized = true;
992
    mOITCompilationAttempted = false;
993

    
994
    detectBuggyDriversAndSetQueueSize(queueSize);
995

    
996
    EffectMessageSender.startSending();
997

    
998
    mResources = context.getResources();
999

    
1000
    try
1001
      {
1002
      createMainProgram();
1003
      }
1004
    catch(Exception ex)
1005
      {
1006
      mListener.distortedException(ex);
1007
      }
1008

    
1009
    try
1010
      {
1011
      EffectQueuePostprocess.createPrograms(mResources, mGLSL);
1012
      }
1013
    catch(Exception ex)
1014
      {
1015
      mListener.distortedException(ex);
1016
      }
1017

    
1018
    try
1019
      {
1020
      PostprocessEffect.createPrograms(mGLSL);
1021
      }
1022
    catch(Exception ex)
1023
      {
1024
      mListener.distortedException(ex);
1025
      }
1026
    }
1027

    
1028
///////////////////////////////////////////////////////////////////////////////////////////////////
1029
/**
1030
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1031
 * Must be called from Activity.onPause().
1032
 */
1033
  public static void onPause()
1034
    {
1035
    InternalObject.onPause();
1036

    
1037
    mLinkedListSSBO[0]= -1;
1038
    mAtomicCounter = null;
1039
    }
1040

    
1041
///////////////////////////////////////////////////////////////////////////////////////////////////
1042
/**
1043
 * Call this so that the Library can release its internal data structures.
1044
 * Must be called from Activity.onDestroy(). 
1045
 */
1046
  public static void onDestroy()
1047
    {
1048
    InternalObject.onDestroy();
1049
    InternalNodeData.onDestroy();
1050
    InternalMaster.onDestroy();
1051
    InternalOutputSurface.onDestroy();
1052
    DistortedEffects.onDestroy();
1053
    EffectQueue.onDestroy();
1054
    Effect.onDestroy();
1055
    DeferredJobs.onDestroy();
1056
    EffectMessageSender.stopSending();
1057

    
1058
    mInitialized = false;
1059
    mOITCompilationAttempted = false;
1060

    
1061
    mNormalProgram     = null;
1062
    mMainOITProgram    = null;
1063
    mMainProgram       = null;
1064
    mFullProgram       = null;
1065
    mOITClearProgram   = null;
1066
    mOITBuildProgram   = null;
1067
    mOITCollapseProgram= null;
1068
    mOITRenderProgram  = null;
1069
    mBlitDepthProgram  = null;
1070
    mBlitProgram       = null;
1071
    }
1072

    
1073
///////////////////////////////////////////////////////////////////////////////////////////////////
1074
/**
1075
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
1076
 * single (InputSurface,MeshBase) combo.
1077
 *
1078
 * @param type {@link EffectType}
1079
 * @return The maximum number of effects of a given type.
1080
 */
1081
  @SuppressWarnings("unused")
1082
  public static int getMax(EffectType type)
1083
    {
1084
    return EffectQueue.getMax(type.ordinal());
1085
    }
1086

    
1087
///////////////////////////////////////////////////////////////////////////////////////////////////
1088
/**
1089
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
1090
 * This can fail if:
1091
 * <ul>
1092
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
1093
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
1094
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link DistortedLibrary#onCreate}. After this
1095
 *     time only decreasing the value of 'max' is permitted.
1096
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
1097
 * </ul>
1098
 *
1099
 * @param type {@link EffectType}
1100
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
1101
 *            than Byte.MAX_VALUE
1102
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
1103
 */
1104
  @SuppressWarnings("unused")
1105
  public static boolean setMax(EffectType type, int max)
1106
    {
1107
    return EffectQueue.setMax(type.ordinal(),max);
1108
    }
1109
  }
(3-3/14)