Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedLibrary.java @ 246d021c

1 d333eb6b Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski                                                               //
3
//                                                                                               //
4 46b572b5 Leszek Koltunski
// This file is part of Distorted.                                                               //
5 d333eb6b Leszek Koltunski
//                                                                                               //
6 46b572b5 Leszek Koltunski
// Distorted is free software: you can redistribute it and/or modify                             //
7 d333eb6b Leszek Koltunski
// 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 46b572b5 Leszek Koltunski
// Distorted is distributed in the hope that it will be useful,                                  //
12 d333eb6b Leszek Koltunski
// 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 46b572b5 Leszek Koltunski
// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18 d333eb6b Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
19
20 fe82a979 Leszek Koltunski
package org.distorted.library.main;
21 6a06a912 Leszek Koltunski
22 30beb34f Leszek Koltunski
import android.app.ActivityManager;
23 7845dc66 Leszek Koltunski
import android.content.Context;
24 30beb34f Leszek Koltunski
import android.content.pm.ConfigurationInfo;
25 d6e94c84 Leszek Koltunski
import android.content.res.Resources;
26 b7074bc6 Leszek Koltunski
import android.opengl.GLES30;
27 edea9cf3 Leszek Koltunski
import android.opengl.GLES31;
28 bfe45b4a Leszek Koltunski
import android.util.Log;
29 310e14fb leszek
30 bfe45b4a Leszek Koltunski
import org.distorted.library.R;
31 26a4e5f6 leszek
import org.distorted.library.effect.Effect;
32 809dcae3 Leszek Koltunski
import org.distorted.library.effectqueue.EffectQueue;
33
import org.distorted.library.effectqueue.EffectQueuePostprocess;
34 bfe45b4a Leszek Koltunski
import org.distorted.library.effect.EffectType;
35
import org.distorted.library.effect.FragmentEffect;
36 aa2f0486 Leszek Koltunski
import org.distorted.library.effect.PostprocessEffect;
37 bfe45b4a Leszek Koltunski
import org.distorted.library.effect.VertexEffect;
38 07206c71 Leszek Koltunski
import org.distorted.library.effectqueue.EffectQueueVertex;
39
import org.distorted.library.mesh.DeferredJobs;
40 bfe45b4a Leszek Koltunski
import org.distorted.library.mesh.MeshBase;
41 ed06301f Leszek Koltunski
import org.distorted.library.message.EffectMessageSender;
42 bfe45b4a Leszek Koltunski
import org.distorted.library.program.DistortedProgram;
43 b7074bc6 Leszek Koltunski
import org.distorted.library.program.VertexCompilationException;
44 0273ef2a Leszek Koltunski
import org.distorted.library.type.Dynamic;
45 bfe45b4a Leszek Koltunski
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 5f35f1cb Leszek Koltunski
import java.util.regex.Matcher;
52
import java.util.regex.Pattern;
53 6a06a912 Leszek Koltunski
54
///////////////////////////////////////////////////////////////////////////////////////////////////
55
/**
56 f953bee0 Leszek Koltunski
 * A singleton class used to control various global dialog_settings.
57 6a06a912 Leszek Koltunski
 */
58 7602a827 Leszek Koltunski
public class DistortedLibrary
59 39cbf9dc Leszek Koltunski
  {
60 b7074bc6 Leszek Koltunski
  private static int mGLSL;
61
  private static String mGLSL_VERSION;
62 d99fcc9c Leszek Koltunski
  private static boolean mOITCompilationAttempted;
63 6a06a912 Leszek Koltunski
  /**
64 cacc63de Leszek Koltunski
   * When creating an instance of a DistortedTexture from another instance, clone the Bitmap that's
65
   * backing up our DistortedTexture.
66 6a06a912 Leszek Koltunski
   * <p>
67 cacc63de Leszek Koltunski
   * This way we can have two DistortedTextures, both backed up by the same Bitmap, to which we can
68 6a06a912 Leszek Koltunski
   * apply different effects. Used in the copy constructor.
69
   */
70 29a06526 Leszek Koltunski
  public static final int CLONE_SURFACE = 0x1;
71 6a06a912 Leszek Koltunski
  /**
72 cacc63de Leszek Koltunski
   * When creating an instance of a DistortedEffects from another instance, clone the Matrix Effects.
73 6a06a912 Leszek Koltunski
   * <p>
74 cacc63de Leszek Koltunski
   * This way we can have two different DistortedEffects sharing the MATRIX queue.
75 6a06a912 Leszek Koltunski
   */
76 015642fb Leszek Koltunski
  public static final int CLONE_MATRIX = 0x2;
77 6a06a912 Leszek Koltunski
  /**
78 cacc63de Leszek Koltunski
   * When creating an instance of a DistortedEffects from another instance, clone the Vertex Effects.
79 6a06a912 Leszek Koltunski
   * <p>
80 cacc63de Leszek Koltunski
   * This way we can have two different DistortedEffects sharing the VERTEX queue.
81 6a06a912 Leszek Koltunski
   */
82
  public static final int CLONE_VERTEX  = 0x4;
83
  /**
84 cacc63de Leszek Koltunski
   * When creating an instance of a DistortedEffects from another instance, clone the Fragment Effects.
85 6a06a912 Leszek Koltunski
   * <p>
86 cacc63de Leszek Koltunski
   * This way we can have two different DistortedEffects sharing the FRAGMENT queue.
87 6a06a912 Leszek Koltunski
   */
88
  public static final int CLONE_FRAGMENT= 0x8;
89 d6e94c84 Leszek Koltunski
   /**
90
   * When creating an instance of a DistortedEffects from another instance, clone the PostProcess Effects.
91
   * <p>
92
   * This way we can have two different DistortedEffects sharing the POSTPROCESS queue.
93
   */
94
  public static final int CLONE_POSTPROCESS= 0x10;
95 6a06a912 Leszek Koltunski
  /**
96 a09ada4c Leszek Koltunski
   * When creating an instance of a DistortedNode from another instance, clone the children Nodes.
97 6a06a912 Leszek Koltunski
   * <p>
98 cacc63de Leszek Koltunski
   * This is mainly useful for creating many similar sub-trees and rendering then at different places
99
   * on the screen with (optionally) different Effects.
100 6a06a912 Leszek Koltunski
   */
101 d6e94c84 Leszek Koltunski
  public static final int CLONE_CHILDREN= 0x20;
102 b3618cb5 Leszek Koltunski
103 5f35f1cb Leszek Koltunski
  /**
104
   * When creating a DistortedScreen (which needs to have mFBOQueueSize FBOs attached), pass this
105
   * constant for 'numOfFBOs' and the number of backing FBOs will be taken from 'mFBOQueueSize'
106
   * (the value of which is most likely unknown at the time of creation of the Screen)
107
   */
108
  public static final int WAIT_FOR_FBO_QUEUE_SIZE = -1;
109 586b5fa1 Leszek Koltunski
  /**
110
   * Work around bugs in ARM Mali driver by, instead to a single FBO, rendering to a circular queue
111 5f35f1cb Leszek Koltunski
   * of mFBOQueueSize FBOs. (otherwise we sometimes get a 'full pipeline flush' and the end result
112 586b5fa1 Leszek Koltunski
   * might be missing part of the Objects)
113 6672d895 Leszek Koltunski
   *
114 5f35f1cb Leszek Koltunski
   * This bug only exists on Mali driver r12. (or more precisely it's there in r12 but fixed in r22)
115 6672d895 Leszek Koltunski
   *
116
   * https://community.arm.com/graphics/f/discussions/10285/opengl-es-3-1-on-mali-t880-flashes
117 586b5fa1 Leszek Koltunski
   */
118 5f35f1cb Leszek Koltunski
  private static int mFBOQueueSize;
119 586b5fa1 Leszek Koltunski
120 55c14a19 Leszek Koltunski
  private static boolean mInitialized=false;
121 6a06a912 Leszek Koltunski
122 bfe45b4a Leszek Koltunski
  //////////////////////////////////////////////////////////////////////////////////////////////
123
  /// MAIN PROGRAM ///
124
  private static DistortedProgram mMainProgram;
125
  private static int mMainTextureH;
126
127
  /// NORMAL PROGRAM /////
128
  private static DistortedProgram mNormalProgram;
129
  private static int mNormalMVPMatrixH;
130
131
  /// MAIN OIT PROGRAM ///
132
  private static DistortedProgram mMainOITProgram;
133
  private static int mMainOITTextureH;
134
  private static int mMainOITSizeH;
135
  private static int mMainOITNumRecordsH;
136
137
  /// BLIT PROGRAM ///
138
  private static DistortedProgram mBlitProgram;
139
  private static int mBlitTextureH;
140
  private static int mBlitDepthH;
141
  private static final FloatBuffer mQuadPositions;
142
143 f046b159 Leszek Koltunski
  /// FULL PROGRAM ///
144
  private static DistortedProgram mFullProgram;
145
146 bfe45b4a Leszek Koltunski
  static
147
    {
148
    float[] positionData= { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
149
    mQuadPositions = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()).asFloatBuffer();
150
    mQuadPositions.put(positionData).position(0);
151
    }
152
153
  /// BLIT DEPTH PROGRAM ///
154
  private static DistortedProgram mBlitDepthProgram;
155
  private static int mBlitDepthTextureH;
156
  private static int mBlitDepthDepthTextureH;
157
  private static int mBlitDepthDepthH;
158
  private static int mBlitDepthTexCorrH;
159
160
  /// OIT SSBO BUFFER ///
161
  private static int[] mLinkedListSSBO = new int[1];
162 5f35f1cb Leszek Koltunski
  private static int[] mAtomicCounter;
163 bfe45b4a Leszek Koltunski
  private static int   mCurrBuffer;
164
165
  static
166
    {
167
    mLinkedListSSBO[0]= -1;
168
    mCurrBuffer       =  0;
169
    }
170
171
  ///////////////////////////////////////////////////////////////
172
  // meaning: allocate 1.0 screenful of places for transparent
173
  // fragments in the SSBO backing up the OIT render method.
174
  private static float mBufferSize=1.0f;
175
176
  /// OIT CLEAR PROGRAM ///
177
  private static DistortedProgram mOITClearProgram;
178
  private static int mOITClearDepthH;
179
  private static int mOITClearTexCorrH;
180
  private static int mOITClearSizeH;
181
182
  /// OIT BUILD PROGRAM ///
183
  private static DistortedProgram mOITBuildProgram;
184
  private static int mOITBuildTextureH;
185
  private static int mOITBuildDepthTextureH;
186
  private static int mOITBuildDepthH;
187
  private static int mOITBuildTexCorrH;
188
  private static int mOITBuildSizeH;
189
  private static int mOITBuildNumRecordsH;
190
191
  /// OIT COLLAPSE PROGRAM ///
192
  private static DistortedProgram mOITCollapseProgram;
193
  private static int mOITCollapseDepthTextureH;
194
  private static int mOITCollapseDepthH;
195
  private static int mOITCollapseTexCorrH;
196
  private static int mOITCollapseSizeH;
197
198
  /// OIT RENDER PROGRAM ///
199
  private static DistortedProgram mOITRenderProgram;
200
  private static int mOITRenderDepthH;
201
  private static int mOITRenderTexCorrH;
202
  private static int mOITRenderSizeH;
203
204
  /// END PROGRAMS //////
205
206 d99fcc9c Leszek Koltunski
  /**
207
   * Every application using the library must implement this interface so that the library can send
208
   * it exceptions that arise. The exceptions may come at any time, for example the library will
209
   * compile its OIT problem only on the first attempt to use the OIT
210
   * Those will mainly be hardware-related: shaders do not compile on particular hardware, the required
211
   * OpenGL ES 3.0 is not supported, etc.
212
   */
213
  public interface ExceptionListener
214
    {
215
    void distortedException(Exception ex);
216
    }
217
218
  private static ExceptionListener mListener;
219
  private static Resources mResources;
220
221 6a06a912 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
222 c638c1b0 Leszek Koltunski
// private: hide this from Javadoc
223 6a06a912 Leszek Koltunski
224 7602a827 Leszek Koltunski
  private DistortedLibrary()
225 6a06a912 Leszek Koltunski
    {
226 8eccf334 Leszek Koltunski
227 6a06a912 Leszek Koltunski
    }
228
229 bfe45b4a Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
230
231 d99fcc9c Leszek Koltunski
  private static void createMainProgram()
232 bfe45b4a Leszek Koltunski
    {
233
    // MAIN PROGRAM ////////////////////////////////////
234 d99fcc9c Leszek Koltunski
    final InputStream mainVertStream = mResources.openRawResource(R.raw.main_vertex_shader);
235
    final InputStream mainFragStream = mResources.openRawResource(R.raw.main_fragment_shader);
236 bfe45b4a Leszek Koltunski
237
    int numF = FragmentEffect.getNumEnabled();
238
    int numV = VertexEffect.getNumEnabled();
239
240 b7074bc6 Leszek Koltunski
    String mainVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n");
241
    String mainFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n");
242 36d65d88 Leszek Koltunski
243 e8925fcd Leszek Koltunski
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
244 36d65d88 Leszek Koltunski
245 bfe45b4a Leszek Koltunski
    String enabledEffectV= VertexEffect.getGLSL();
246
    String enabledEffectF= FragmentEffect.getGLSL();
247
248
    String[] feedback = { "v_Position", "v_endPosition" };
249
250
    try
251
      {
252
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
253 b7074bc6 Leszek Koltunski
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
254 bfe45b4a Leszek Koltunski
      }
255
    catch(Exception e)
256
      {
257
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
258
      throw new RuntimeException(e.getMessage());
259
      }
260
261
    int mainProgramH = mMainProgram.getProgramHandle();
262
    EffectQueue.getUniforms(mainProgramH,0);
263 36d65d88 Leszek Koltunski
    MeshBase.getUniforms(mainProgramH,0);
264 b7074bc6 Leszek Koltunski
    mMainTextureH= GLES30.glGetUniformLocation( mainProgramH, "u_Texture");
265 bfe45b4a Leszek Koltunski
266
    // BLIT PROGRAM ////////////////////////////////////
267 d99fcc9c Leszek Koltunski
    final InputStream blitVertStream = mResources.openRawResource(R.raw.blit_vertex_shader);
268
    final InputStream blitFragStream = mResources.openRawResource(R.raw.blit_fragment_shader);
269 bfe45b4a Leszek Koltunski
270
    try
271
      {
272 b7074bc6 Leszek Koltunski
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
273 bfe45b4a Leszek Koltunski
      }
274
    catch(Exception e)
275
      {
276
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
277
      throw new RuntimeException(e.getMessage());
278
      }
279
280
    int blitProgramH = mBlitProgram.getProgramHandle();
281 b7074bc6 Leszek Koltunski
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
282
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
283 bfe45b4a Leszek Koltunski
284
    // BLIT DEPTH PROGRAM ////////////////////////////////////
285 d99fcc9c Leszek Koltunski
    final InputStream blitDepthVertStream = mResources.openRawResource(R.raw.blit_depth_vertex_shader);
286
    final InputStream blitDepthFragStream = mResources.openRawResource(R.raw.blit_depth_fragment_shader);
287 bfe45b4a Leszek Koltunski
288
    try
289
      {
290 b7074bc6 Leszek Koltunski
      mBlitDepthProgram = new DistortedProgram(blitDepthVertStream,blitDepthFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
291 bfe45b4a Leszek Koltunski
      }
292
    catch(Exception e)
293
      {
294
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH program: "+e.getMessage());
295
      throw new RuntimeException(e.getMessage());
296
      }
297
298
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
299 b7074bc6 Leszek Koltunski
    mBlitDepthTextureH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Texture");
300
    mBlitDepthDepthTextureH = GLES30.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
301
    mBlitDepthDepthH        = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Depth");
302
    mBlitDepthTexCorrH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
303 d99fcc9c Leszek Koltunski
    }
304
305
///////////////////////////////////////////////////////////////////////////////////////////////////
306 bfe45b4a Leszek Koltunski
307 d99fcc9c Leszek Koltunski
  private static void createNormalProgram(Resources resources)
308
    {
309 bfe45b4a Leszek Koltunski
    // NORMAL PROGRAM //////////////////////////////////////
310
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
311
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
312
313
    try
314
      {
315 b7074bc6 Leszek Koltunski
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
316 bfe45b4a Leszek Koltunski
      }
317
    catch(Exception e)
318
      {
319
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
320
      throw new RuntimeException(e.getMessage());
321
      }
322
323
    int normalProgramH = mNormalProgram.getProgramHandle();
324 b7074bc6 Leszek Koltunski
    mNormalMVPMatrixH  = GLES30.glGetUniformLocation( normalProgramH, "u_MVPMatrix");
325 bfe45b4a Leszek Koltunski
    }
326
327 f046b159 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
328
329
  private static void createFullProgram(Resources resources)
330
    {
331
    final InputStream fullVertStream = resources.openRawResource(R.raw.main_vertex_shader);
332
    final InputStream fullFragStream = resources.openRawResource(R.raw.main_fragment_shader);
333
334
    int numV = VertexEffect.getAllEnabled();
335
336
    String fullVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX ) : 0 ) + "\n");
337
    String fullFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " +                                         0   + "\n");
338 36d65d88 Leszek Koltunski
339 e8925fcd Leszek Koltunski
    fullVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
340 36d65d88 Leszek Koltunski
341 f046b159 Leszek Koltunski
    String enabledEffectV= VertexEffect.getAllGLSL();
342
    String enabledEffectF= "{}";
343
344 667884b0 Leszek Koltunski
    fullVertHeader += "#define PREAPPLY\n";
345
346 e54bfada Leszek Koltunski
    String[] feedback = { "v_Position", "v_endPosition", "v_Inflate" };
347 f046b159 Leszek Koltunski
348
    try
349
      {
350
      mFullProgram = new DistortedProgram(fullVertStream, fullFragStream, fullVertHeader, fullFragHeader,
351
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
352
      }
353
    catch(Exception e)
354
      {
355
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile FULL program: "+e.getMessage());
356
      throw new RuntimeException(e.getMessage());
357
      }
358
359
    int fullProgramH = mFullProgram.getProgramHandle();
360
    EffectQueue.getUniforms(fullProgramH,3);
361 36d65d88 Leszek Koltunski
    MeshBase.getUniforms(fullProgramH,3);
362 f046b159 Leszek Koltunski
    }
363
364 bfe45b4a Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
365
366 d99fcc9c Leszek Koltunski
  private static void createOITProgram(Resources resources)
367 bfe45b4a Leszek Koltunski
    {
368
    // MAIN OIT PROGRAM ////////////////////////////////
369
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
370
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
371
372
    int numF = FragmentEffect.getNumEnabled();
373
    int numV = VertexEffect.getNumEnabled();
374
375 b7074bc6 Leszek Koltunski
    String mainVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n") + ("#define OIT\n");
376
    String mainFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n") + ("#define OIT\n");
377 bfe45b4a Leszek Koltunski
378 e8925fcd Leszek Koltunski
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
379 36d65d88 Leszek Koltunski
380 bfe45b4a Leszek Koltunski
    String enabledEffectV= VertexEffect.getGLSL();
381
    String enabledEffectF= FragmentEffect.getGLSL();
382
383
    try
384
      {
385
      mMainOITProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
386 b7074bc6 Leszek Koltunski
                                             enabledEffectV, enabledEffectF, mGLSL, null);
387 bfe45b4a Leszek Koltunski
      }
388
    catch(Exception e)
389
      {
390
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN OIT program: "+e.getMessage());
391
      throw new RuntimeException(e.getMessage());
392
      }
393
394
    int mainOITProgramH = mMainOITProgram.getProgramHandle();
395
    EffectQueue.getUniforms(mainOITProgramH,1);
396 36d65d88 Leszek Koltunski
    MeshBase.getUniforms(mainOITProgramH,1);
397 b7074bc6 Leszek Koltunski
    mMainOITTextureH    = GLES30.glGetUniformLocation( mainOITProgramH, "u_Texture");
398
    mMainOITSizeH       = GLES30.glGetUniformLocation( mainOITProgramH, "u_Size");
399
    mMainOITNumRecordsH = GLES30.glGetUniformLocation( mainOITProgramH, "u_numRecords");
400 bfe45b4a Leszek Koltunski
401
    // OIT CLEAR PROGRAM ////////////////////////////////////
402
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
403
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
404
405
    try
406
      {
407 b7074bc6 Leszek Koltunski
      mOITClearProgram = new DistortedProgram(oitClearVertStream,oitClearFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
408 bfe45b4a Leszek Koltunski
      }
409
    catch(Exception e)
410
      {
411
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT CLEAR program: "+e.getMessage());
412
      throw new RuntimeException(e.getMessage());
413
      }
414
415
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
416 b7074bc6 Leszek Koltunski
    mOITClearDepthH        = GLES30.glGetUniformLocation( oitClearProgramH, "u_Depth");
417
    mOITClearTexCorrH      = GLES30.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
418
    mOITClearSizeH         = GLES30.glGetUniformLocation( oitClearProgramH, "u_Size");
419 bfe45b4a Leszek Koltunski
420
    // OIT BUILD PROGRAM ////////////////////////////////////
421
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
422
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
423
424
    try
425
      {
426 b7074bc6 Leszek Koltunski
      mOITBuildProgram = new DistortedProgram(oitBuildVertStream,oitBuildFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
427 bfe45b4a Leszek Koltunski
      }
428
    catch(Exception e)
429
      {
430
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT BUILD program: "+e.getMessage());
431
      throw new RuntimeException(e.getMessage());
432
      }
433
434
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
435 b7074bc6 Leszek Koltunski
    mOITBuildTextureH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Texture");
436
    mOITBuildDepthTextureH = GLES30.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
437
    mOITBuildDepthH        = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Depth");
438
    mOITBuildTexCorrH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
439
    mOITBuildSizeH         = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Size");
440
    mOITBuildNumRecordsH   = GLES30.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
441 bfe45b4a Leszek Koltunski
442
    // OIT COLLAPSE PROGRAM ///////////////////////////
443
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
444
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
445
446
    try
447
      {
448 b7074bc6 Leszek Koltunski
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
449 bfe45b4a Leszek Koltunski
      }
450
    catch(Exception e)
451
      {
452
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
453
      throw new RuntimeException(e.getMessage());
454
      }
455
456
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
457 b7074bc6 Leszek Koltunski
    mOITCollapseDepthTextureH = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
458
    mOITCollapseDepthH        = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
459
    mOITCollapseTexCorrH      = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
460
    mOITCollapseSizeH         = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Size");
461 bfe45b4a Leszek Koltunski
462
    // OIT RENDER PROGRAM ///////////////////////////
463
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
464
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
465
466
    try
467
      {
468 b7074bc6 Leszek Koltunski
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
469 bfe45b4a Leszek Koltunski
      }
470
    catch(Exception e)
471
      {
472
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
473
      throw new RuntimeException(e.getMessage());
474
      }
475
476
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
477 b7074bc6 Leszek Koltunski
    mOITRenderDepthH        = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Depth");
478
    mOITRenderTexCorrH      = GLES30.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
479
    mOITRenderSizeH         = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Size");
480 bfe45b4a Leszek Koltunski
    }
481
482
///////////////////////////////////////////////////////////////////////////////////////////////////
483
484
  private static void displayNormals(EffectQueue[] queues, MeshBase mesh)
485
    {
486 d99fcc9c Leszek Koltunski
    if( mNormalProgram==null )
487
      {
488
      try
489
        {
490
        createNormalProgram(mResources);
491
        }
492
      catch(Exception ex)
493
        {
494
        mListener.distortedException(ex);
495
        return;
496
        }
497
      }
498
499 bfe45b4a Leszek Koltunski
    int num = mesh.getNumVertices();
500
    int tfo = mesh.getTFO();
501
502 b7074bc6 Leszek Koltunski
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
503
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
504 7602a827 Leszek Koltunski
    InternalRenderState.switchOffDrawing();
505 b7074bc6 Leszek Koltunski
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
506 7602a827 Leszek Koltunski
    InternalRenderState.restoreDrawing();
507 b7074bc6 Leszek Koltunski
    GLES30.glEndTransformFeedback();
508
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
509 bfe45b4a Leszek Koltunski
510 f046b159 Leszek Koltunski
    mNormalProgram.useProgram();
511
    GLES30.glUniformMatrix4fv(mNormalMVPMatrixH, 1, false, EffectQueue.getMVP(queues) , 0);
512
    mesh.bindTransformAttribs(mNormalProgram);
513 b7074bc6 Leszek Koltunski
    GLES30.glLineWidth(8.0f);
514
    GLES30.glDrawArrays(GLES30.GL_LINES, 0, 2*num);
515 bfe45b4a Leszek Koltunski
    }
516
517 f046b159 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
518
// execute all VertexEffects and adjust all vertices
519
520 07206c71 Leszek Koltunski
  public static void adjustVertices(MeshBase mesh, EffectQueueVertex queue)
521 f046b159 Leszek Koltunski
    {
522 d99fcc9c Leszek Koltunski
    if( mFullProgram==null )
523 f046b159 Leszek Koltunski
      {
524 d99fcc9c Leszek Koltunski
      try
525
        {
526
        createFullProgram(mResources);
527
        }
528
      catch(Exception ex)
529
        {
530
        mListener.distortedException(ex);
531
        return;
532
        }
533 f046b159 Leszek Koltunski
      }
534 d99fcc9c Leszek Koltunski
535
    int num = mesh.getNumVertices();
536
    int tfo = mesh.getTFO();
537
538
    mFullProgram.useProgram();
539
    mesh.bindVertexAttribs(mFullProgram);
540
    queue.compute(1);
541
    queue.send(0.0f,3);
542
    mesh.send(3);
543
544
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
545
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
546
    InternalRenderState.switchOffDrawing();
547
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
548
    InternalRenderState.restoreDrawing();
549
    GLES30.glEndTransformFeedback();
550
    mesh.copyTransformToVertex();
551
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
552 f046b159 Leszek Koltunski
    }
553
554 bfe45b4a Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
555
556 c90aca24 Leszek Koltunski
  static void drawPrivOIT(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
557 bfe45b4a Leszek Koltunski
    {
558 06ddd60d Leszek Koltunski
    if( mMainOITProgram!=null )
559
      {
560
      EffectQueue[] queues = effects.getQueues();
561 c90aca24 Leszek Koltunski
562 06ddd60d Leszek Koltunski
      EffectQueue.compute(queues, currTime);
563
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
564 bfe45b4a Leszek Koltunski
565 06ddd60d Leszek Koltunski
      mMainOITProgram.useProgram();
566
      GLES30.glUniform1i(mMainOITTextureH, 0);
567
      GLES30.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
568
      GLES30.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
569
      mesh.bindVertexAttribs(mMainOITProgram);
570
      mesh.send(1);
571 bfe45b4a Leszek Koltunski
572 06ddd60d Leszek Koltunski
      float inflate     = mesh.getInflate();
573
      float distance    = surface.mDistance;
574
      float mipmap      = surface.mMipmap;
575
      float[] projection= surface.mProjectionMatrix;
576 bfe45b4a Leszek Koltunski
577 06ddd60d Leszek Koltunski
      EffectQueue.send(queues, distance, mipmap, projection, inflate, mesh, 1 );
578
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
579 bfe45b4a Leszek Koltunski
580 06ddd60d Leszek Koltunski
      if( mesh.getShowNormals() )
581
        {
582
        mMainProgram.useProgram();
583
        mesh.send(0);
584
        EffectQueue.send(queues, distance, mipmap, projection, inflate, mesh, 0 );
585
        displayNormals(queues,mesh);
586
        }
587 bfe45b4a Leszek Koltunski
      }
588
    }
589
590
///////////////////////////////////////////////////////////////////////////////////////////////////
591
592 c90aca24 Leszek Koltunski
  static void drawPriv(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
593 bfe45b4a Leszek Koltunski
    {
594 f046b159 Leszek Koltunski
    if( mMainProgram!=null )
595 f482efa3 Leszek Koltunski
      {
596
      EffectQueue[] queues = effects.getQueues();
597 bfe45b4a Leszek Koltunski
598 f482efa3 Leszek Koltunski
      EffectQueue.compute(queues, currTime);
599
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
600 46b572b5 Leszek Koltunski
601 f482efa3 Leszek Koltunski
      mMainProgram.useProgram();
602
      GLES30.glUniform1i(DistortedLibrary.mMainTextureH, 0);
603
      mesh.bindVertexAttribs(DistortedLibrary.mMainProgram);
604 36d65d88 Leszek Koltunski
      mesh.send(0);
605 809dcae3 Leszek Koltunski
606 f482efa3 Leszek Koltunski
      float inflate     = mesh.getInflate();
607
      float distance    = surface.mDistance;
608
      float mipmap      = surface.mMipmap;
609
      float[] projection= surface.mProjectionMatrix;
610 809dcae3 Leszek Koltunski
611 f482efa3 Leszek Koltunski
      EffectQueue.send(queues, distance, mipmap, projection, inflate, mesh, 0 );
612
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
613 bfe45b4a Leszek Koltunski
614 f482efa3 Leszek Koltunski
      if( mesh.getShowNormals() ) displayNormals(queues,mesh);
615
      }
616 bfe45b4a Leszek Koltunski
    }
617
618
///////////////////////////////////////////////////////////////////////////////////////////////////
619
620 7602a827 Leszek Koltunski
  static void blitPriv(InternalOutputSurface surface)
621 bfe45b4a Leszek Koltunski
    {
622 f482efa3 Leszek Koltunski
    if( mBlitProgram!=null )
623
      {
624
      mBlitProgram.useProgram();
625 bfe45b4a Leszek Koltunski
626 f482efa3 Leszek Koltunski
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
627
      GLES30.glUniform1i(mBlitTextureH, 0);
628
      GLES30.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
629
      GLES30.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
630
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
631
      }
632 bfe45b4a Leszek Koltunski
    }
633
634
///////////////////////////////////////////////////////////////////////////////////////////////////
635
636 7602a827 Leszek Koltunski
  static void blitDepthPriv(InternalOutputSurface surface, float corrW, float corrH)
637 bfe45b4a Leszek Koltunski
    {
638 f482efa3 Leszek Koltunski
    if( mBlitDepthProgram!=null )
639
      {
640
      mBlitDepthProgram.useProgram();
641
642
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
643
      GLES30.glUniform1i(mBlitDepthTextureH, 0);
644
      GLES30.glUniform1i(mBlitDepthDepthTextureH, 1);
645
      GLES30.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
646
      GLES30.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
647
      GLES30.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
648
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
649
      }
650 bfe45b4a Leszek Koltunski
    }
651
652
///////////////////////////////////////////////////////////////////////////////////////////////////
653 b7074bc6 Leszek Koltunski
// yes it is safe to be mixing 3.0 and 3.1 like that, senior members of the OpenGL discussions forum assert
654 bfe45b4a Leszek Koltunski
655
  private static int printPreviousBuffer()
656
    {
657
    int counter = 0;
658
659 b7074bc6 Leszek Koltunski
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
660
                                                                GLES30.GL_MAP_READ_BIT);
661 bfe45b4a Leszek Koltunski
    if( atomicBuf!=null )
662
      {
663
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
664
      counter = atomicIntBuf.get(0);
665
      }
666
    else
667
      {
668 b7074bc6 Leszek Koltunski
      Log.e("effects", "print: failed to map atomic buffer");
669 bfe45b4a Leszek Koltunski
      }
670
671 b7074bc6 Leszek Koltunski
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
672 bfe45b4a Leszek Koltunski
673
    return counter;
674
    }
675
676
///////////////////////////////////////////////////////////////////////////////////////////////////
677
678
  private static void zeroBuffer()
679
    {
680 b7074bc6 Leszek Koltunski
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
681
        GLES30.GL_MAP_WRITE_BIT|GLES30.GL_MAP_INVALIDATE_BUFFER_BIT);
682 bfe45b4a Leszek Koltunski
    if( atomicBuf!=null )
683
      {
684
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
685
      atomicIntBuf.put(0,0);
686
      }
687
    else
688
      {
689 b7074bc6 Leszek Koltunski
      Log.e("effects", "zero: failed to map atomic buffer");
690 bfe45b4a Leszek Koltunski
      }
691
692 b7074bc6 Leszek Koltunski
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
693 bfe45b4a Leszek Koltunski
    }
694
695
///////////////////////////////////////////////////////////////////////////////////////////////////
696
// reset atomic counter to 0
697
698
  static int zeroOutAtomic()
699
    {
700
    int counter = 0;
701
702 5f35f1cb Leszek Koltunski
    if( mAtomicCounter==null )
703 bfe45b4a Leszek Koltunski
      {
704 5f35f1cb Leszek Koltunski
      mAtomicCounter = new int[mFBOQueueSize];
705
706
      GLES30.glGenBuffers(mFBOQueueSize,mAtomicCounter,0);
707 bfe45b4a Leszek Koltunski
708 5f35f1cb Leszek Koltunski
      for(int i=0; i<mFBOQueueSize; i++)
709 bfe45b4a Leszek Koltunski
        {
710 b7074bc6 Leszek Koltunski
        GLES30.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
711
        GLES30.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES30.GL_DYNAMIC_DRAW);
712 bfe45b4a Leszek Koltunski
        zeroBuffer();
713
        }
714
      }
715
716
    // reading the value of the buffer on every frame would slow down rendering by
717 d99fcc9c Leszek Koltunski
    // about 3%; doing it only once every 5 frames affects speed by less than 1%.
718 bfe45b4a Leszek Koltunski
    if( mCurrBuffer==0 )
719
      {
720 b7074bc6 Leszek Koltunski
      GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
721 bfe45b4a Leszek Koltunski
      counter = printPreviousBuffer();
722
      }
723
724 5f35f1cb Leszek Koltunski
    if( ++mCurrBuffer>=mFBOQueueSize ) mCurrBuffer = 0;
725 bfe45b4a Leszek Koltunski
726 b7074bc6 Leszek Koltunski
    GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
727 bfe45b4a Leszek Koltunski
    zeroBuffer();
728
729
    return counter;
730
    }
731
732
///////////////////////////////////////////////////////////////////////////////////////////////////
733 809dcae3 Leszek Koltunski
// Pass1 of the OIT algorithm. Clear per-pixel head-pointers.
734 bfe45b4a Leszek Koltunski
735 7602a827 Leszek Koltunski
  static void oitClear(InternalOutputSurface surface, int counter)
736 bfe45b4a Leszek Koltunski
    {
737 d99fcc9c Leszek Koltunski
    if( mOITClearProgram==null )
738 bfe45b4a Leszek Koltunski
      {
739 d99fcc9c Leszek Koltunski
      if( mGLSL>=310 && !mOITCompilationAttempted )
740 f482efa3 Leszek Koltunski
        {
741 d99fcc9c Leszek Koltunski
        mOITCompilationAttempted = true;
742 bfe45b4a Leszek Koltunski
743 d99fcc9c Leszek Koltunski
        try
744
          {
745
          createOITProgram(mResources);
746
          }
747
        catch(Exception ex)
748
          {
749
          mListener.distortedException(ex);
750
          return;
751
          }
752 f482efa3 Leszek Koltunski
        }
753 d99fcc9c Leszek Koltunski
      else
754 f482efa3 Leszek Koltunski
        {
755 d99fcc9c Leszek Koltunski
        return;
756 f482efa3 Leszek Koltunski
        }
757 d99fcc9c Leszek Koltunski
      }
758 bfe45b4a Leszek Koltunski
759 d99fcc9c Leszek Koltunski
    if( mLinkedListSSBO[0]<0 )
760
      {
761
      GLES30.glGenBuffers(1,mLinkedListSSBO,0);
762 bfe45b4a Leszek Koltunski
763 d99fcc9c Leszek Koltunski
      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 f482efa3 Leszek Koltunski
      }
783 d99fcc9c Leszek Koltunski
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 bfe45b4a Leszek Koltunski
    }
793
794
///////////////////////////////////////////////////////////////////////////////////////////////////
795
// Pass2 of the OIT algorithm - build per-pixel linked lists.
796
797 7602a827 Leszek Koltunski
  static void oitBuild(InternalOutputSurface surface, float corrW, float corrH)
798 bfe45b4a Leszek Koltunski
    {
799 f482efa3 Leszek Koltunski
    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 bfe45b4a Leszek Koltunski
    }
814
815
///////////////////////////////////////////////////////////////////////////////////////////////////
816
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
817
818 7602a827 Leszek Koltunski
  static void oitCollapse(InternalOutputSurface surface, float corrW, float corrH)
819 bfe45b4a Leszek Koltunski
    {
820 f482efa3 Leszek Koltunski
    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 bfe45b4a Leszek Koltunski
    }
833
834
///////////////////////////////////////////////////////////////////////////////////////////////////
835
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
836
837 7602a827 Leszek Koltunski
  static void oitRender(InternalOutputSurface surface, float corrW, float corrH)
838 bfe45b4a Leszek Koltunski
    {
839 f482efa3 Leszek Koltunski
    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 bfe45b4a Leszek Koltunski
    }
851
852
///////////////////////////////////////////////////////////////////////////////////////////////////
853
854
  static void setSSBOSize(float size)
855
    {
856
    mBufferSize = size;
857
    }
858
859 5f35f1cb Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
860
861
  static int getQueueSize()
862
    {
863
    return mFBOQueueSize;
864
    }
865
866 edea9cf3 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
867
// ARM Mali driver r12 has problems when we keep swapping many FBOs (fixed in r22)
868 b7074bc6 Leszek Koltunski
// PowerVR GE8100 / GE8300 compiler fails to compile OIT programs.
869 edea9cf3 Leszek Koltunski
870 5f35f1cb Leszek Koltunski
  private static void detectBuggyDriversAndSetQueueSize(int queueSize)
871 edea9cf3 Leszek Koltunski
    {
872 b7074bc6 Leszek Koltunski
    String vendor  = GLES30.glGetString(GLES30.GL_VENDOR);
873
    String version = GLES30.glGetString(GLES30.GL_VERSION);
874
    String renderer= GLES30.glGetString(GLES30.GL_RENDERER);
875 edea9cf3 Leszek Koltunski
876 5f35f1cb Leszek Koltunski
    mFBOQueueSize = 1;
877 edea9cf3 Leszek Koltunski
878
    if( vendor.contains("ARM") )
879
      {
880 5f35f1cb Leszek Koltunski
      try
881 edea9cf3 Leszek Koltunski
        {
882 5f35f1cb Leszek Koltunski
        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 edea9cf3 Leszek Koltunski
        }
908
      }
909
    else if( vendor.contains("Imagination") )
910
      {
911
      if( renderer.contains("GE8") )
912
        {
913 b7074bc6 Leszek Koltunski
        Log.e("DISTORTED", "You are running this on a PowerVR GE8XXX.\nDue to a buggy compiler OIT rendering will not work");
914 a79650a2 Leszek Koltunski
        Log.e("DISTORTED", "GLSL Version "+GLES30.glGetString(GLES31.GL_SHADING_LANGUAGE_VERSION));
915 edea9cf3 Leszek Koltunski
        }
916
      }
917
    }
918
919 b7074bc6 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
920
/**
921
 * Return OpenGL ES version supported by the hardware we are running on.
922 60fdf71d Leszek Koltunski
 * 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 b7074bc6 Leszek Koltunski
 */
925 60fdf71d Leszek Koltunski
  public static int getGLSL()
926 b7074bc6 Leszek Koltunski
    {
927
    return mGLSL;
928
    }
929
930 421c2728 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
931 310e14fb leszek
/**
932
 * Have we called onCreate yet, ie have we initialized the library?
933 1dfc9074 leszek
 * @return <code>true</code> if the library is initialized and ready for action.
934 310e14fb leszek
 */
935
  public static boolean isInitialized()
936 421c2728 Leszek Koltunski
    {
937 55c14a19 Leszek Koltunski
    return mInitialized;
938 421c2728 Leszek Koltunski
    }
939
940 6a06a912 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
941
/**
942 c43abe6c Leszek Koltunski
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
943 432442f9 Leszek Koltunski
 * I.e. best called from GLSurfaceView.onCreate().
944 6a06a912 Leszek Koltunski
 * <p>
945 432442f9 Leszek Koltunski
 * Needs to be called from a thread holding the OpenGL context.
946 5f35f1cb Leszek Koltunski
 *
947 015642fb Leszek Koltunski
 * @param context Context of the App using the library - used to open up Resources and read Shader code.
948 d99fcc9c Leszek Koltunski
 * @param listener The library will send all (asynchronous!) exceptions there.
949 6a06a912 Leszek Koltunski
 */
950 d99fcc9c Leszek Koltunski
  public static void onCreate(final Context context, final ExceptionListener listener)
951 5f35f1cb Leszek Koltunski
    {
952 d99fcc9c Leszek Koltunski
    onCreate(context,listener,4);
953 5f35f1cb Leszek Koltunski
    }
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 d99fcc9c Leszek Koltunski
 * @param listener The library will send all (asynchronous!) exceptions there.
964 5f35f1cb Leszek Koltunski
 * @param queueSize the size of the FBO queue, a workaround for the bug on Mali drivers.
965
 */
966 d99fcc9c Leszek Koltunski
  public static void onCreate(final Context context, final ExceptionListener listener, int queueSize)
967 d6e94c84 Leszek Koltunski
    {
968 30beb34f Leszek Koltunski
    final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
969
    final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
970 b7074bc6 Leszek Koltunski
971
    int glESversion = configurationInfo.reqGlEsVersion;
972
    int major = glESversion >> 16;
973
    int minor = glESversion & 0xff;
974
975 d99fcc9c Leszek Koltunski
    mListener = listener;
976
977 b7074bc6 Leszek Koltunski
    if( major< 3 )
978
      {
979
      mGLSL = 100*major + 10*minor;
980 d99fcc9c Leszek Koltunski
      VertexCompilationException ex = new VertexCompilationException("at least OpenGL ES 3.0 required, this device supports only "+major+"."+minor);
981
      mListener.distortedException(ex);
982 b7074bc6 Leszek Koltunski
      }
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 edea9cf3 Leszek Koltunski
991
    mInitialized = true;
992 d99fcc9c Leszek Koltunski
    mOITCompilationAttempted = false;
993 edea9cf3 Leszek Koltunski
994 5f35f1cb Leszek Koltunski
    detectBuggyDriversAndSetQueueSize(queueSize);
995 edea9cf3 Leszek Koltunski
996 0e924ba5 Leszek Koltunski
    EffectMessageSender.startSending();
997
998 d99fcc9c Leszek Koltunski
    mResources = context.getResources();
999 edea9cf3 Leszek Koltunski
1000
    try
1001
      {
1002 d99fcc9c Leszek Koltunski
      createMainProgram();
1003 edea9cf3 Leszek Koltunski
      }
1004
    catch(Exception ex)
1005
      {
1006 d99fcc9c Leszek Koltunski
      mListener.distortedException(ex);
1007 edea9cf3 Leszek Koltunski
      }
1008
1009 f046b159 Leszek Koltunski
    try
1010
      {
1011 d99fcc9c Leszek Koltunski
      EffectQueuePostprocess.createPrograms(mResources, mGLSL);
1012 f046b159 Leszek Koltunski
      }
1013
    catch(Exception ex)
1014
      {
1015 d99fcc9c Leszek Koltunski
      mListener.distortedException(ex);
1016 a13dde77 Leszek Koltunski
      }
1017
1018 edea9cf3 Leszek Koltunski
    try
1019
      {
1020 b7074bc6 Leszek Koltunski
      PostprocessEffect.createPrograms(mGLSL);
1021 edea9cf3 Leszek Koltunski
      }
1022
    catch(Exception ex)
1023
      {
1024 d99fcc9c Leszek Koltunski
      mListener.distortedException(ex);
1025 edea9cf3 Leszek Koltunski
      }
1026 6a06a912 Leszek Koltunski
    }
1027
1028 05ecc6fe Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
1029
/**
1030 78e89fb5 Leszek Koltunski
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1031 05ecc6fe Leszek Koltunski
 * Must be called from Activity.onPause().
1032
 */
1033
  public static void onPause()
1034
    {
1035 7602a827 Leszek Koltunski
    InternalObject.onPause();
1036 0273ef2a Leszek Koltunski
    Dynamic.onPause();
1037 bfe45b4a Leszek Koltunski
    mLinkedListSSBO[0]= -1;
1038 5f35f1cb Leszek Koltunski
    mAtomicCounter = null;
1039 05ecc6fe Leszek Koltunski
    }
1040
1041 6a06a912 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 7602a827 Leszek Koltunski
    InternalObject.onDestroy();
1049
    InternalNodeData.onDestroy();
1050
    InternalMaster.onDestroy();
1051
    InternalOutputSurface.onDestroy();
1052 46b572b5 Leszek Koltunski
    DistortedEffects.onDestroy();
1053 42571056 Leszek Koltunski
    EffectQueue.onDestroy();
1054 26a4e5f6 leszek
    Effect.onDestroy();
1055 07206c71 Leszek Koltunski
    DeferredJobs.onDestroy();
1056 6a06a912 Leszek Koltunski
    EffectMessageSender.stopSending();
1057 f8686932 Leszek Koltunski
1058 55c14a19 Leszek Koltunski
    mInitialized = false;
1059 d99fcc9c Leszek Koltunski
    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 6a06a912 Leszek Koltunski
    }
1072 bfe45b4a Leszek Koltunski
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 7602a827 Leszek Koltunski
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link DistortedLibrary#onCreate}. After this
1095 bfe45b4a Leszek Koltunski
 *     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 f8f6d457 leszek
  }