Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedLibrary.java @ 97b6c85e

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

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

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

    
125
  //////////////////////////////////////////////////////////////////////////////////////////////
126
  /// MAIN PROGRAM ///
127
  private static DistortedProgram mMainProgram;
128
  private static int mMainTextureH;
129
  private static int mTransformFeedbackH;
130

    
131
  /// NORMAL PROGRAM /////
132
  private static DistortedProgram mNormalProgram;
133
  private static int mNormalProjectionH;
134

    
135
  /// MAIN OIT PROGRAM ///
136
  private static DistortedProgram mMainOITProgram;
137
  private static int mMainOITTextureH;
138
  private static int mMainOITSizeH;
139
  private static int mMainOITNumRecordsH;
140

    
141
  /// BLIT PROGRAM ///
142
  private static DistortedProgram mBlitProgram;
143
  private static int mBlitTextureH;
144
  private static int mBlitDepthH;
145
  private static final FloatBuffer mQuadPositions;
146

    
147
  /// FULL PROGRAM ///
148
  private static DistortedProgram mFullProgram;
149

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

    
157
  /// BLIT DEPTH PROGRAM ///
158
  private static DistortedProgram mBlitDepthProgram;
159
  private static int mBlitDepthTextureH;
160
  private static int mBlitDepthDepthTextureH;
161
  private static int mBlitDepthDepthH;
162
  private static int mBlitDepthTexCorrH;
163

    
164
  /// Program Handles ///
165
  private static int mMainProgramH, mFullProgramH, mMainOITProgramH;
166

    
167
  /// OIT SSBO BUFFER ///
168
  private static int[] mLinkedListSSBO = new int[1];
169
  private static int[] mAtomicCounter;
170
  private static int   mCurrBuffer;
171

    
172
  static
173
    {
174
    mLinkedListSSBO[0]= -1;
175
    mCurrBuffer       =  0;
176
    }
177

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

    
183
  /// OIT CLEAR PROGRAM ///
184
  private static DistortedProgram mOITClearProgram;
185
  private static int mOITClearDepthH;
186
  private static int mOITClearTexCorrH;
187
  private static int mOITClearSizeH;
188

    
189
  /// OIT BUILD PROGRAM ///
190
  private static DistortedProgram mOITBuildProgram;
191
  private static int mOITBuildTextureH;
192
  private static int mOITBuildDepthTextureH;
193
  private static int mOITBuildDepthH;
194
  private static int mOITBuildTexCorrH;
195
  private static int mOITBuildSizeH;
196
  private static int mOITBuildNumRecordsH;
197

    
198
  /// OIT COLLAPSE PROGRAM ///
199
  private static DistortedProgram mOITCollapseProgram;
200
  private static int mOITCollapseDepthTextureH;
201
  private static int mOITCollapseDepthH;
202
  private static int mOITCollapseTexCorrH;
203
  private static int mOITCollapseSizeH;
204

    
205
  /// OIT RENDER PROGRAM ///
206
  private static DistortedProgram mOITRenderProgram;
207
  private static int mOITRenderDepthH;
208
  private static int mOITRenderTexCorrH;
209
  private static int mOITRenderSizeH;
210

    
211
  /// END PROGRAMS //////
212

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

    
225
  private static ExceptionListener mListener;
226
  private static Resources mResources;
227

    
228
///////////////////////////////////////////////////////////////////////////////////////////////////
229
// private: hide this from Javadoc
230

    
231
  private DistortedLibrary()
232
    {
233

    
234
    }
235

    
236
///////////////////////////////////////////////////////////////////////////////////////////////////
237

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

    
244
    int numF = FragmentEffect.getNumEnabled();
245
    int numV = VertexEffect.getNumEnabled();
246

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

    
250
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
251

    
252
    String enabledEffectV= VertexEffect.getGLSL();
253
    String enabledEffectF= FragmentEffect.getGLSL();
254

    
255
    String[] feedback = { "v_Position", "v_endPosition" };
256

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

    
269
    mMainProgramH = mMainProgram.getProgramHandle();
270
    EffectQueue.getUniforms(mMainProgramH,0);
271
    MeshBase.getUniforms(mMainProgramH,0);
272
    mMainTextureH= GLES30.glGetUniformLocation( mMainProgramH, "u_Texture");
273
    mTransformFeedbackH= GLES30.glGetUniformLocation( mMainProgramH, "u_TransformFeedback");
274

    
275
    // BLIT PROGRAM ////////////////////////////////////
276
    final InputStream blitVertStream = mResources.openRawResource(R.raw.blit_vertex_shader);
277
    final InputStream blitFragStream = mResources.openRawResource(R.raw.blit_fragment_shader);
278

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

    
289
    int blitProgramH = mBlitProgram.getProgramHandle();
290
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
291
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
292

    
293
    // BLIT DEPTH PROGRAM ////////////////////////////////////
294
    final InputStream blitDepthVertStream = mResources.openRawResource(R.raw.blit_depth_vertex_shader);
295
    final InputStream blitDepthFragStream = mResources.openRawResource(R.raw.blit_depth_fragment_shader);
296

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

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

    
314
///////////////////////////////////////////////////////////////////////////////////////////////////
315

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

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

    
332
    int normalProgramH = mNormalProgram.getProgramHandle();
333
    mNormalProjectionH = GLES30.glGetUniformLocation( normalProgramH, "u_Projection");
334
    }
335

    
336
///////////////////////////////////////////////////////////////////////////////////////////////////
337

    
338
  private static void createFullProgram(Resources resources)
339
    {
340
    final InputStream fullVertStream = resources.openRawResource(R.raw.main_vertex_shader);
341
    final InputStream fullFragStream = resources.openRawResource(R.raw.main_fragment_shader);
342

    
343
    int numV = VertexEffect.getAllEnabled();
344

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

    
348
    fullVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
349

    
350
    String enabledEffectV= VertexEffect.getAllGLSL();
351
    String enabledEffectF= "{}";
352

    
353
    fullVertHeader += "#define PREAPPLY\n";
354

    
355
    String[] feedback = { "v_Position", "v_endPosition" };
356

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

    
368
    mFullProgramH = mFullProgram.getProgramHandle();
369
    EffectQueue.getUniforms(mFullProgramH,3);
370
    MeshBase.getUniforms(mFullProgramH,3);
371
    }
372

    
373
///////////////////////////////////////////////////////////////////////////////////////////////////
374

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

    
381
    int numF = FragmentEffect.getNumEnabled();
382
    int numV = VertexEffect.getNumEnabled();
383

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

    
387
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
388

    
389
    String enabledEffectV= VertexEffect.getGLSL();
390
    String enabledEffectF= FragmentEffect.getGLSL();
391

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

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

    
410
    // OIT CLEAR PROGRAM ////////////////////////////////////
411
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
412
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
413

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

    
424
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
425
    mOITClearDepthH        = GLES30.glGetUniformLocation( oitClearProgramH, "u_Depth");
426
    mOITClearTexCorrH      = GLES30.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
427
    mOITClearSizeH         = GLES30.glGetUniformLocation( oitClearProgramH, "u_Size");
428

    
429
    // OIT BUILD PROGRAM ////////////////////////////////////
430
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
431
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
432

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

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

    
451
    // OIT COLLAPSE PROGRAM ///////////////////////////
452
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
453
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
454

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

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

    
471
    // OIT RENDER PROGRAM ///////////////////////////
472
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
473
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
474

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

    
485
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
486
    mOITRenderDepthH        = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Depth");
487
    mOITRenderTexCorrH      = GLES30.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
488
    mOITRenderSizeH         = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Size");
489
    }
490

    
491
///////////////////////////////////////////////////////////////////////////////////////////////////
492

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

    
508
    int num = mesh.getNumVertices();
509
    int tfo = mesh.getTFO();
510

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

    
521
    mNormalProgram.useProgram();
522
    GLES30.glUniformMatrix4fv(mNormalProjectionH, 1, false, projection, 0);
523
    mesh.bindTransformAttribs(mNormalProgram);
524
    GLES30.glLineWidth(8.0f);
525
    GLES30.glDrawArrays(GLES30.GL_LINES, 0, 2*num);
526
    }
527

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

    
549
    int num = mesh.getNumVertices();
550
    int tfo = mesh.getTFO();
551

    
552
    mFullProgram.useProgram();
553
    mesh.bindVertexAttribs(mFullProgram);
554
    queue.compute(1);
555
    queue.send(0.0f,mFullProgramH,3);
556
    mesh.send(mFullProgramH,3);
557

    
558
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
559
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
560
    InternalRenderState.switchOffDrawing();
561
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
562
    InternalRenderState.restoreDrawing();
563
    GLES30.glEndTransformFeedback();
564
    mesh.copyTransformToVertex();
565
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
566
    }
567

    
568
///////////////////////////////////////////////////////////////////////////////////////////////////
569

    
570
  static void drawPrivOIT(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
571
    {
572
    if( mMainOITProgram!=null )
573
      {
574
      EffectQueue[] queues = effects.getQueues();
575

    
576
      EffectQueue.compute(queues, currTime);
577
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
578

    
579
      mMainOITProgram.useProgram();
580
      GLES30.glUniform1i(mMainOITTextureH, 0);
581
      GLES30.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
582
      GLES30.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
583
      mesh.bindVertexAttribs(mMainOITProgram);
584
      mesh.send(mMainOITProgramH,1);
585

    
586
      float inflate     = mesh.getInflate();
587
      float distance    = surface.mDistance;
588
      float mipmap      = surface.mMipmap;
589
      float[] projection= surface.mProjectionMatrix;
590

    
591
      EffectQueue.send(queues, mMainOITProgramH, distance, mipmap, projection, inflate, 1 );
592
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
593

    
594
      if( mesh.getShowNormals() )
595
        {
596
        mMainProgram.useProgram();
597
        mesh.send(mMainProgramH,0);
598
        EffectQueue.send(queues, mMainProgramH, distance, mipmap, projection, inflate, 0 );
599
        displayNormals(projection,mesh);
600
        }
601
      }
602
    }
603

    
604
///////////////////////////////////////////////////////////////////////////////////////////////////
605

    
606
  static void drawPriv(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
607
    {
608
    if( mMainProgram!=null )
609
      {
610
      EffectQueue[] queues = effects.getQueues();
611

    
612
      EffectQueue.compute(queues, currTime);
613
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
614

    
615
      mMainProgram.useProgram();
616
      GLES30.glUniform1i(DistortedLibrary.mMainTextureH, 0);
617
      mesh.bindVertexAttribs(DistortedLibrary.mMainProgram);
618
      mesh.send(mMainProgramH,0);
619

    
620
      float inflate     = mesh.getInflate();
621
      float distance    = surface.mDistance;
622
      float mipmap      = surface.mMipmap;
623
      float[] projection= surface.mProjectionMatrix;
624

    
625
      EffectQueue.send(queues, mMainProgramH, distance, mipmap, projection, inflate, 0 );
626
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
627

    
628
      if( mesh.getShowNormals() ) displayNormals(projection,mesh);
629
      }
630
    }
631

    
632
///////////////////////////////////////////////////////////////////////////////////////////////////
633

    
634
  static void blitPriv(InternalOutputSurface surface)
635
    {
636
    if( mBlitProgram!=null )
637
      {
638
      mBlitProgram.useProgram();
639

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

    
648
///////////////////////////////////////////////////////////////////////////////////////////////////
649

    
650
  static void blitDepthPriv(InternalOutputSurface surface, float corrW, float corrH)
651
    {
652
    if( mBlitDepthProgram!=null )
653
      {
654
      mBlitDepthProgram.useProgram();
655

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

    
666
///////////////////////////////////////////////////////////////////////////////////////////////////
667
// yes it is safe to be mixing 3.0 and 3.1 like that, senior members of the OpenGL discussions forum assert
668

    
669
  private static int printPreviousBuffer()
670
    {
671
    int counter = 0;
672

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

    
685
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
686

    
687
    return counter;
688
    }
689

    
690
///////////////////////////////////////////////////////////////////////////////////////////////////
691

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

    
706
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
707
    }
708

    
709
///////////////////////////////////////////////////////////////////////////////////////////////////
710
// reset atomic counter to 0
711

    
712
  static int zeroOutAtomic()
713
    {
714
    int counter = 0;
715

    
716
    if( mAtomicCounter==null )
717
      {
718
      mAtomicCounter = new int[mFBOQueueSize];
719

    
720
      GLES30.glGenBuffers(mFBOQueueSize,mAtomicCounter,0);
721

    
722
      for(int i=0; i<mFBOQueueSize; i++)
723
        {
724
        GLES30.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
725
        GLES30.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES30.GL_DYNAMIC_DRAW);
726
        zeroBuffer();
727
        }
728
      }
729

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

    
738
    if( ++mCurrBuffer>=mFBOQueueSize ) mCurrBuffer = 0;
739

    
740
    GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
741
    zeroBuffer();
742

    
743
    return counter;
744
    }
745

    
746
///////////////////////////////////////////////////////////////////////////////////////////////////
747
// Pass1 of the OIT algorithm. Clear per-pixel head-pointers.
748

    
749
  static void oitClear(InternalOutputSurface surface, int counter)
750
    {
751
    if( mOITClearProgram==null )
752
      {
753
      if( mGLSL>=310 && !mOITCompilationAttempted )
754
        {
755
        mOITCompilationAttempted = true;
756

    
757
        try
758
          {
759
          createOITProgram(mResources);
760
          }
761
        catch(Exception ex)
762
          {
763
          mListener.distortedException(ex);
764
          return;
765
          }
766
        }
767
      else
768
        {
769
        return;
770
        }
771
      }
772

    
773
    if( mLinkedListSSBO[0]<0 )
774
      {
775
      GLES30.glGenBuffers(1,mLinkedListSSBO,0);
776

    
777
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
778
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
779
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
780
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
781

    
782
      GLES30.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
783
      }
784

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

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

    
798
    mOITClearProgram.useProgram();
799

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

    
808
///////////////////////////////////////////////////////////////////////////////////////////////////
809
// Pass2 of the OIT algorithm - build per-pixel linked lists.
810

    
811
  static void oitBuild(InternalOutputSurface surface, float corrW, float corrH)
812
    {
813
    if( mOITBuildProgram!=null )
814
      {
815
      mOITBuildProgram.useProgram();
816

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

    
829
///////////////////////////////////////////////////////////////////////////////////////////////////
830
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
831

    
832
  static void oitCollapse(InternalOutputSurface surface, float corrW, float corrH)
833
    {
834
    if( mOITCollapseProgram!=null )
835
      {
836
      mOITCollapseProgram.useProgram();
837

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

    
848
///////////////////////////////////////////////////////////////////////////////////////////////////
849
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
850

    
851
  static void oitRender(InternalOutputSurface surface, float corrW, float corrH)
852
    {
853
    if( mOITRenderProgram!=null )
854
      {
855
      mOITRenderProgram.useProgram();
856

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

    
866
///////////////////////////////////////////////////////////////////////////////////////////////////
867

    
868
  static void setSSBOSize(float size)
869
    {
870
    mBufferSize = size;
871
    }
872

    
873
///////////////////////////////////////////////////////////////////////////////////////////////////
874

    
875
  static int getQueueSize()
876
    {
877
    return mFBOQueueSize;
878
    }
879

    
880
///////////////////////////////////////////////////////////////////////////////////////////////////
881
// ARM Mali driver r12 has problems when we keep swapping many FBOs (fixed in r22)
882
// PowerVR GE8100 / GE8300 compiler fails to compile OIT programs.
883

    
884
  private static void detectBuggyDriversAndSetQueueSize(int queueSize)
885
    {
886
    String vendor  = GLES30.glGetString(GLES30.GL_VENDOR);
887
    String version = GLES30.glGetString(GLES30.GL_VERSION);
888
    String renderer= GLES30.glGetString(GLES30.GL_RENDERER);
889

    
890
    mFBOQueueSize = 1;
891

    
892
    if( vendor.contains("ARM") )
893
      {
894
      try
895
        {
896
        String regex = ".*r(\\d+)p\\d.*";
897
        Pattern pattern = Pattern.compile(regex);
898
        Matcher matcher = pattern.matcher(version);
899

    
900
        if( matcher.find() )
901
          {
902
          String driverVersion = matcher.group(1);
903

    
904
          if( driverVersion!=null )
905
            {
906
            int drvVersion = Integer.parseInt(driverVersion);
907

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

    
913
              mFBOQueueSize = queueSize;
914
              }
915
            }
916
          }
917
        }
918
      catch(Exception ex)
919
        {
920
        android.util.Log.e("library", "exception trying to pattern match version: "+ex.toString());
921
        }
922
      }
923
    else if( vendor.contains("Imagination") )
924
      {
925
      if( renderer.contains("GE8") )
926
        {
927
        Log.e("DISTORTED", "You are running this on a PowerVR GE8XXX.\nDue to a buggy compiler OIT rendering will not work");
928
        Log.e("DISTORTED", "GLSL Version "+GLES30.glGetString(GLES31.GL_SHADING_LANGUAGE_VERSION));
929
        }
930
      }
931
    else if( vendor.contains("Qualcomm"))
932
      {
933
      if( version.contains("V@331.0") )
934
        {
935
        Log.e("DISTORTED", "You are running this on an Adreno 3xx driver version 331.\nStrange shit might happen.");
936
        }
937
      }
938
    }
939

    
940
///////////////////////////////////////////////////////////////////////////////////////////////////
941
/**
942
 * Return OpenGL ES version supported by the hardware we are running on.
943
 * There are only three possibilities: 300 (OpenGL ES 3.0) or 310 (at least OpenGL ES 3.1)
944
 * or 200 (OpenGL ES 2.0)
945
 */
946
  public static int getGLSL()
947
    {
948
    return mGLSL;
949
    }
950

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

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

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

    
986
    mListener = listener;
987

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

    
999
    int[] tmp = new int[1];
1000
    GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, tmp, 0);
1001
    mMaxTextureSize = tmp[0];
1002
    GLES30.glGetIntegerv(GLES30.GL_MAX_VERTEX_UNIFORM_VECTORS  , tmp, 0);
1003
    mMaxNumberOfVerUniforms = tmp[0];
1004
    GLES30.glGetIntegerv(GLES30.GL_MAX_FRAGMENT_UNIFORM_VECTORS, tmp, 0);
1005
    mMaxNumberOfFraUniforms = tmp[0];
1006

    
1007
    android.util.Log.e("DISTORTED", "Using OpenGL ES "+major+"."+minor);
1008
/*
1009
    android.util.Log.e("DISTORTED", "max texture size: "+mMaxTextureSize);
1010
    android.util.Log.e("DISTORTED", "max num vert: "+mMaxNumberOfVerUniforms);
1011
    android.util.Log.e("DISTORTED", "max num frag: "+mMaxNumberOfFraUniforms);
1012
*/
1013
    mGLSL_VERSION = "#version "+mGLSL+" es\n";
1014

    
1015
    InternalStackFrameList.setInitialized(true);
1016
    mOITCompilationAttempted = false;
1017

    
1018
    detectBuggyDriversAndSetQueueSize(queueSize);
1019
    EffectMessageSender.startSending();
1020

    
1021
    mResources = context.getResources();
1022

    
1023
    try
1024
      {
1025
      createMainProgram();
1026
      }
1027
    catch(Exception ex)
1028
      {
1029
      mListener.distortedException(ex);
1030
      }
1031

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

    
1041
    try
1042
      {
1043
      PostprocessEffect.createPrograms(mGLSL);
1044
      }
1045
    catch(Exception ex)
1046
      {
1047
      mListener.distortedException(ex);
1048
      }
1049
    }
1050

    
1051
///////////////////////////////////////////////////////////////////////////////////////////////////
1052
/**
1053
 * Call this so that the Library can initialize its internal data structures.
1054
 * Must be called from Activity.onCreate().
1055
 */
1056
  public static void onCreate()
1057
    {
1058
    onCreate(0);
1059
    }
1060

    
1061
///////////////////////////////////////////////////////////////////////////////////////////////////
1062
/**
1063
 * Call this so that the Library can initialize its internal data structures.
1064
 * Must be called from Activity.onCreate().
1065
 *
1066
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1067
 *           tell between Activities in case you're going to be using it from more than one.
1068
 */
1069
  public static void onCreate(long id)
1070
    {
1071
    InternalStackFrameList.onCreate(id);
1072
    }
1073

    
1074
///////////////////////////////////////////////////////////////////////////////////////////////////
1075
/**
1076
 * Call this so that the Library can resume its operations.
1077
 * Must be called from Activity.onResume().
1078
 */
1079
  public static void onResume()
1080
    {
1081
    onCreate(0);
1082
    }
1083

    
1084
///////////////////////////////////////////////////////////////////////////////////////////////////
1085
/**
1086
 * Call this so that the Library can resume its operations.
1087
 * Must be called from Activity.onResume().
1088
 *
1089
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1090
 *           tell between Activities in case you're going to be using it from more than one.
1091
 */
1092
  public static void onResume(long id)
1093
    {
1094
    InternalStackFrameList.onResume(id);
1095
    }
1096

    
1097
///////////////////////////////////////////////////////////////////////////////////////////////////
1098
/**
1099
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1100
 * Must be called from Activity.onPause().
1101
 */
1102
  public static void onPause()
1103
    {
1104
    onPause(0);
1105
    }
1106

    
1107
///////////////////////////////////////////////////////////////////////////////////////////////////
1108
/**
1109
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1110
 * Must be called from Activity.onPause().
1111
 *
1112
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1113
 *           tell between Activities in case you're going to be using it from more than one.
1114
 */
1115
  public static void onPause(long id)
1116
    {
1117
    InternalStackFrameList.onPause(id);
1118
    Dynamic.onPause();  // common for all frames
1119

    
1120
    mLinkedListSSBO[0]= -1;
1121
    mAtomicCounter = null;
1122

    
1123
    mNormalProgram     = null;
1124
    mMainOITProgram    = null;
1125
    mMainProgram       = null;
1126
    mFullProgram       = null;
1127
    mOITClearProgram   = null;
1128
    mOITBuildProgram   = null;
1129
    mOITCollapseProgram= null;
1130
    mOITRenderProgram  = null;
1131
    mBlitDepthProgram  = null;
1132
    mBlitProgram       = null;
1133
    }
1134

    
1135
///////////////////////////////////////////////////////////////////////////////////////////////////
1136
/**
1137
 * Call this so that the Library can release its internal data structures.
1138
 * Must be called from Activity.onDestroy().
1139
 */
1140
  public static void onDestroy()
1141
    {
1142
    onDestroy(0);
1143
    }
1144

    
1145
///////////////////////////////////////////////////////////////////////////////////////////////////
1146
/**
1147
 * Call this so that the Library can release its internal data structures.
1148
 * Must be called from Activity.onDestroy().
1149
 *
1150
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1151
 *           tell between Activities in case you're going to be using it from more than one.
1152
 */
1153
  public static void onDestroy(long id)
1154
    {
1155
    if( InternalStackFrameList.isInitialized() )
1156
      {
1157
      InternalStackFrameList.onDestroy(id);
1158

    
1159
      InternalOutputSurface.onDestroy(); // those three really destroy
1160
      Effect.onDestroy();                // static data that does not
1161
      DeferredJobs.onDestroy();          // need to be part of a frame
1162

    
1163
      mOITCompilationAttempted = false;
1164
      }
1165
    }
1166

    
1167
///////////////////////////////////////////////////////////////////////////////////////////////////
1168
/**
1169
 * Return the maximum size of the texture supported by the driver.
1170
 */
1171
  public static int getMaxTextureSize()
1172
    {
1173
    return mMaxTextureSize;
1174
    }
1175

    
1176
///////////////////////////////////////////////////////////////////////////////////////////////////
1177
/**
1178
 * Call this before calling onSurfaceCreated() if you want to access normal vectors in CPU.
1179
 */
1180
  public static void needTransformFeedback()
1181
    {
1182
    mNeedsTransformFeedback = true;
1183
    }
1184

    
1185
///////////////////////////////////////////////////////////////////////////////////////////////////
1186
/**
1187
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
1188
 * single (InputSurface,MeshBase) combo.
1189
 *
1190
 * @param type {@link EffectType}
1191
 * @return The maximum number of effects of a given type.
1192
 */
1193
  @SuppressWarnings("unused")
1194
  public static int getMax(EffectType type)
1195
    {
1196
    return EffectQueue.getMax(type.ordinal());
1197
    }
1198

    
1199
///////////////////////////////////////////////////////////////////////////////////////////////////
1200
/**
1201
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
1202
 * This can fail if:
1203
 * <ul>
1204
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
1205
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
1206
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link DistortedLibrary#onSurfaceCreated}. After this
1207
 *     time only decreasing the value of 'max' is permitted.
1208
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
1209
 * </ul>
1210
 *
1211
 * @param type {@link EffectType}
1212
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
1213
 *            than Byte.MAX_VALUE
1214
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
1215
 */
1216
  @SuppressWarnings("unused")
1217
  public static boolean setMax(EffectType type, int max)
1218
    {
1219
    return EffectQueue.setMax(type.ordinal(),max);
1220
    }
1221
  }
(3-3/16)