Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedLibrary.java @ 97755c02

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