Project

General

Profile

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

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

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