Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedLibrary.java @ 46d463a4

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