Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedOutputSurface.java @ 61441ce2

1 c5369f1b leszek
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// Distorted is free software: you can redistribute it and/or modify                             //
7
// it under the terms of the GNU General Public License as published by                          //
8
// the Free Software Foundation, either version 2 of the License, or                             //
9
// (at your option) any later version.                                                           //
10
//                                                                                               //
11
// Distorted is distributed in the hope that it will be useful,                                  //
12
// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
14
// GNU General Public License for more details.                                                  //
15
//                                                                                               //
16
// You should have received a copy of the GNU General Public License                             //
17
// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19
20 fe82a979 Leszek Koltunski
package org.distorted.library.main;
21 c5369f1b leszek
22 e6519ac8 Leszek Koltunski
import android.opengl.GLES31;
23 af4cc5db Leszek Koltunski
import android.opengl.Matrix;
24 86e99907 leszek
25 3521c6fe leszek
import org.distorted.library.effect.EffectQuality;
26
27 12f45260 Leszek Koltunski
import java.nio.ByteBuffer;
28
import java.nio.ByteOrder;
29 66ace7f5 Leszek Koltunski
import java.nio.IntBuffer;
30 a09ada4c Leszek Koltunski
import java.util.ArrayList;
31 af4cc5db Leszek Koltunski
32
///////////////////////////////////////////////////////////////////////////////////////////////////
33 70b6a155 Leszek Koltunski
/**
34
 * This is not really part of the public API.
35
 *
36
 * @y.exclude
37
 */
38
public abstract class DistortedOutputSurface extends DistortedSurface implements DistortedMaster.Slave
39 af4cc5db Leszek Koltunski
{
40 86e99907 leszek
//////////// DEBUG FLAGS /////////////////////////////////////////////
41
/**
42
 * When rendering a Screen, show FPS in the upper-left corner?
43
 */
44
public static final int DEBUG_FPS = 1;
45
//////////// END DEBUG FLAGS /////////////////////////////////////////
46
47 89de975c leszek
/**
48
 * Do not create DEPTH or STENCIL attachment
49
 */
50 23eecbd9 Leszek Koltunski
  public static final int NO_DEPTH_NO_STENCIL = 0;
51 89de975c leszek
/**
52
 * Create DEPTH, but not STENCIL
53
 */
54 23eecbd9 Leszek Koltunski
  public static final int DEPTH_NO_STENCIL    = 1;
55 89de975c leszek
/**
56
 * Create both DEPTH and STENCIL
57
 */
58 23eecbd9 Leszek Koltunski
  public static final int BOTH_DEPTH_STENCIL  = 2;
59 89de975c leszek
60 efe3d8fe leszek
  private static final int ATTACH = 0;
61
  private static final int DETACH = 1;
62
  private static final int DETALL = 2;
63
  private static final int SORT   = 3;
64
65 a09ada4c Leszek Koltunski
  private ArrayList<DistortedNode> mChildren;
66
  private int mNumChildren;   // ==mChildren.length(), but we only create mChildren if the first one gets added
67
68 efe3d8fe leszek
  private class Job
69
    {
70
    int type;
71
    DistortedNode node;
72
73 ffbe7ecf Leszek Koltunski
    Job(int t, DistortedNode n)
74 efe3d8fe leszek
      {
75
      type = t;
76
      node = n;
77
      }
78
    }
79
80
  private ArrayList<Job> mJobs = new ArrayList<>();
81
82 61441ce2 Leszek Koltunski
  // buffers used for postprocessing.
83
  private DistortedOutputSurface[] mBuffer;
84 60c1c622 leszek
85 95c441a2 leszek
  private long mTime;
86 c2c08950 leszek
  private float mFOV;
87
  float mDistance, mNear;
88 af4cc5db Leszek Koltunski
  float[] mProjectionMatrix;
89
90 89de975c leszek
  int mDepthStencilCreated;
91
  int mDepthStencil;
92
  int[] mDepthStencilH = new int[1];
93
  int[] mFBOH          = new int[1];
94 a436ccc5 leszek
95 a9f41fa3 leszek
  private float mClearR, mClearG, mClearB, mClearA;
96
  private float mClearDepth;
97 23eecbd9 Leszek Koltunski
  private int mClearStencil;
98 ad16ed3b Leszek Koltunski
  private int mClear;
99 78db8663 Leszek Koltunski
  float mMipmap;
100
101 86e99907 leszek
  private int mDebugLevel;
102
103 61441ce2 Leszek Koltunski
  int mRealWidth;   // the Surface can be backed up with a texture that is
104
  int mRealHeight;  // larger than the viewport we have to it.
105
                    // mWidth,mHeight are the sizes of the Viewport, those -
106
                    // sizes of the backing up texture.
107 a4b182d4 Leszek Koltunski
108 12f45260 Leszek Koltunski
  ////////////////////////////////////////////////////////////////////////////////
109
  // section dealing with Shader Storage Buffer Object (for counting transparency)
110 df4d7edc Leszek Koltunski
  private static final int FRAME_DELAY = 3;
111
  private static int mBufferSize       =10;
112 12f45260 Leszek Koltunski
  private static DistortedObjectCounter mSurfaceCounter = new DistortedObjectCounter();
113
  private static int[] mSSBO = new int[1];
114 66ace7f5 Leszek Koltunski
  private static IntBuffer mIntBuffer;
115 12f45260 Leszek Koltunski
116
  static
117
    {
118 66ace7f5 Leszek Koltunski
    mSSBO[0]= -1;
119 12f45260 Leszek Koltunski
    }
120
121
  private int mSurfaceID;
122
  private int mLastIndex;
123 df4d7edc Leszek Koltunski
  private int[] mLastValue = new int[FRAME_DELAY];
124 2faad666 Leszek Koltunski
  private int mLastDiff = -1;
125
126
  private static final int RUNNING_AVERAGE = 10;
127
  private int[] mRunningAvg = new int[RUNNING_AVERAGE];
128
  private int mAvgIndex;
129
  private int mAvgSum;
130 12f45260 Leszek Koltunski
  // end section
131
  ////////////////////////////////////////////////////////////////////////////////
132
133 86e99907 leszek
///////////////////////////////////////////////////////////////////////////////////////////////////
134
135
  abstract void prepareDebug(long time);
136
  abstract void renderDebug(long time);
137 12f45260 Leszek Koltunski
  abstract void createSurface();
138
  abstract void deleteSurface();
139
  abstract void recreateSurface();
140 86e99907 leszek
141 af4cc5db Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
142
143 9ed80185 Leszek Koltunski
  DistortedOutputSurface(int width, int height, int createColor, int numcolors, int depthStencil, int fbo, int type)
144 af4cc5db Leszek Koltunski
    {
145 9ed80185 Leszek Koltunski
    super(width,height,createColor,numcolors,type);
146 af4cc5db Leszek Koltunski
147 a4b182d4 Leszek Koltunski
    mRealWidth = width;
148
    mRealHeight= height;
149
150 af4cc5db Leszek Koltunski
    mProjectionMatrix = new float[16];
151
152
    mFOV = 60.0f;
153 54fe333a leszek
    mNear=  0.5f;
154 af4cc5db Leszek Koltunski
155 23eecbd9 Leszek Koltunski
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
156 89de975c leszek
    mDepthStencil = depthStencil;
157
158
    mFBOH[0]         = fbo;
159
    mDepthStencilH[0]= 0;
160 a436ccc5 leszek
161 95c441a2 leszek
    mTime = 0;
162 86e99907 leszek
    mDebugLevel = 0;
163 95c441a2 leszek
164 a9f41fa3 leszek
    mClearR = 0.0f;
165
    mClearG = 0.0f;
166
    mClearB = 0.0f;
167
    mClearA = 0.0f;
168
169
    mClearDepth = 1.0f;
170 23eecbd9 Leszek Koltunski
    mClearStencil = 0;
171 e6519ac8 Leszek Koltunski
    mClear = GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_COLOR_BUFFER_BIT;
172 a9f41fa3 leszek
173 70b6a155 Leszek Koltunski
    mBuffer = new DistortedOutputSurface[1+EffectQuality.LENGTH];
174 638b5b5c leszek
175 8426bd6a Leszek Koltunski
    mMipmap = 1.0f;
176 78db8663 Leszek Koltunski
177 af4cc5db Leszek Koltunski
    createProjection();
178
    }
179
180 12f45260 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
181
// Must be called from a thread holding OpenGL Context
182
183
  void create()
184
    {
185
    if( mSSBO[0]<0 )
186
      {
187
      GLES31.glGenBuffers(1,mSSBO,0);
188
189
      // here bind the new SSBO and map it
190
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mSSBO[0]);
191 df4d7edc Leszek Koltunski
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, FRAME_DELAY *mBufferSize*4 , null, GLES31.GL_DYNAMIC_READ);
192
      ByteBuffer buf = (ByteBuffer) GLES31.glMapBufferRange(GLES31.GL_SHADER_STORAGE_BUFFER, 0, FRAME_DELAY *mBufferSize*4, GLES31.GL_MAP_READ_BIT );
193 66ace7f5 Leszek Koltunski
      mIntBuffer = buf.order(ByteOrder.nativeOrder()).asIntBuffer();
194 2ab60f72 Leszek Koltunski
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER,0, mSSBO[0]);
195 12f45260 Leszek Koltunski
      }
196
197
    mSurfaceID = mSurfaceCounter.returnNext();
198
199
    if( mSurfaceID>=mBufferSize )
200
      {
201 51a3cbab Leszek Koltunski
      // increase size of the Buffer, copy over old values, remap.
202 df4d7edc Leszek Koltunski
      int[] tmp = new int[FRAME_DELAY *mBufferSize];
203
      for(int i = 0; i< FRAME_DELAY *mBufferSize; i++) tmp[i] = mIntBuffer.get(i);
204 51a3cbab Leszek Koltunski
205
      mBufferSize*= 2;
206
207
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, 0);
208
      GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER);
209
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER,0);
210
211
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mSSBO[0]);
212 df4d7edc Leszek Koltunski
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, FRAME_DELAY *mBufferSize*4 , null, GLES31.GL_DYNAMIC_READ);
213
      ByteBuffer buf = (ByteBuffer) GLES31.glMapBufferRange(GLES31.GL_SHADER_STORAGE_BUFFER, 0, FRAME_DELAY *mBufferSize*4, GLES31.GL_MAP_READ_BIT );
214 51a3cbab Leszek Koltunski
      mIntBuffer = buf.order(ByteOrder.nativeOrder()).asIntBuffer();
215
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER,0, mSSBO[0]);
216
217
      for(int i=0;i<tmp.length;i++) mIntBuffer.put(i,tmp[i]);
218 12f45260 Leszek Koltunski
      }
219
220
    createSurface();
221
    }
222
223
///////////////////////////////////////////////////////////////////////////////////////////////////
224
// Must be called from a thread holding OpenGL Context
225
226
  void delete()
227
    {
228
    mSurfaceCounter.release(mSurfaceID);
229
    deleteSurface();
230
    }
231
232
///////////////////////////////////////////////////////////////////////////////////////////////////
233
234
  void recreate()
235
    {
236 2faad666 Leszek Koltunski
    mSSBO[0]  = -1;
237
    mLastDiff = -1;
238
239 df4d7edc Leszek Koltunski
    for(int i = 0; i< FRAME_DELAY; i++) mLastValue[i] = 0;
240 12f45260 Leszek Koltunski
    mSurfaceCounter.releaseAll();
241 2faad666 Leszek Koltunski
242 12f45260 Leszek Koltunski
    recreateSurface();
243
    }
244
245 27cd6b98 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
246
247 8a57da61 Leszek Koltunski
  int getNewCounter()
248 27cd6b98 Leszek Koltunski
    {
249 df4d7edc Leszek Koltunski
    return FRAME_DELAY*mSurfaceID + mLastIndex;
250 12f45260 Leszek Koltunski
    }
251
252 c5369f1b leszek
///////////////////////////////////////////////////////////////////////////////////////////////////
253
254 be60d4ff leszek
  private void createProjection()
255 af4cc5db Leszek Koltunski
    {
256
    if( mWidth>0 && mHeight>1 )
257
      {
258
      if( mFOV>0.0f )  // perspective projection
259
        {
260 54fe333a leszek
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
261 8426bd6a Leszek Koltunski
        float q = mWidth*mNear;
262
        float c = mHeight*mNear;
263 54fe333a leszek
264 c2c08950 leszek
        float left   = -q/2;
265
        float right  = +q/2;
266
        float bottom = -c/2;
267
        float top    = +c/2;
268
        float near   =  c/a;
269 54fe333a leszek
270 8426bd6a Leszek Koltunski
        mDistance    = mHeight/a;
271 af4cc5db Leszek Koltunski
        float far    = 2*mDistance-near;
272
273
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
274
        }
275
      else             // parallel projection
276
        {
277 8426bd6a Leszek Koltunski
        float left   = -mWidth/2.0f;
278
        float right  = +mWidth/2.0f;
279
        float bottom = -mHeight/2.0f;
280
        float top    = +mHeight/2.0f;
281
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
282
        mDistance    = mWidth+mHeight;
283
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
284 af4cc5db Leszek Koltunski
285
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
286
        }
287
      }
288
    }
289
290 1d6d261e Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
291
292 6b962e80 Leszek Koltunski
  private void createBuffers()
293 1d6d261e Leszek Koltunski
    {
294
    float mipmap=1.0f;
295
296
    for(int j=0; j<EffectQuality.LENGTH; j++)
297
      {
298 0f011027 Leszek Koltunski
      mBuffer[j] = new DistortedFramebuffer(2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
299
      mBuffer[j].mMipmap = mipmap;
300 73208cab leszek
      mBuffer[j].mNear   = mNear;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
301 7ad20cce Leszek Koltunski
      mBuffer[j].glClearColor(1.0f,1.0f,1.0f,0.0f);
302 a4b182d4 Leszek Koltunski
303 1d6d261e Leszek Koltunski
      mipmap *= EffectQuality.MULTIPLIER;
304
      }
305
306 70b6a155 Leszek Koltunski
    mBuffer[EffectQuality.LENGTH] = this;
307
308 1d6d261e Leszek Koltunski
    DistortedObject.toDo(); // create the FBOs immediately. This is safe as we must be holding the OpenGL context now.
309
310 e6519ac8 Leszek Koltunski
    GLES31.glStencilMask(0xff);
311
    GLES31.glDepthMask(true);
312
    GLES31.glColorMask(true,true,true,true);
313
    GLES31.glClearColor(0.0f,0.0f,0.0f,0.0f);
314
    GLES31.glClearDepthf(1.0f);
315
    GLES31.glClearStencil(0);
316 1d6d261e Leszek Koltunski
317
    for(int j=0; j<EffectQuality.LENGTH; j++)
318
      {
319 0f011027 Leszek Koltunski
      mBuffer[j].setAsOutput();
320 e6519ac8 Leszek Koltunski
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[1], 0);
321
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
322
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[0], 0);
323
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
324 1d6d261e Leszek Koltunski
      }
325
    }
326
327 a4b182d4 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
328
329
  private void cloneSize(DistortedOutputSurface from)
330
    {
331
    mWidth = from.mWidth;
332
    mHeight= from.mHeight;
333
334
    createProjection();
335
336
    int maxw = mWidth >mRealWidth  ? mWidth :mRealWidth ;
337
    int maxh = mHeight>mRealHeight ? mHeight:mRealHeight;
338
339
    if( maxw>mRealWidth || maxh>mRealHeight )
340
      {
341
      mRealWidth = maxw;
342
      mRealHeight= maxh;
343
344
      recreateSurface();
345
      createSurface();
346
      }
347
    }
348
349 6b962e80 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
350
351 70b6a155 Leszek Koltunski
  private int blitWithDepth(long currTime, DistortedOutputSurface buffer)
352 6b962e80 Leszek Koltunski
    {
353 e6519ac8 Leszek Koltunski
    GLES31.glViewport(0, 0, mWidth, mHeight);
354 6b962e80 Leszek Koltunski
    setAsOutput(currTime);
355 e6519ac8 Leszek Koltunski
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
356
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[0]);
357
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
358
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[0]);
359 6b962e80 Leszek Koltunski
360 e6519ac8 Leszek Koltunski
    GLES31.glDisable(GLES31.GL_STENCIL_TEST);
361
    GLES31.glStencilMask(0x00);
362 6b962e80 Leszek Koltunski
363
    DistortedEffects.blitDepthPriv(this);
364 e6519ac8 Leszek Koltunski
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
365
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
366
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
367
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
368 6b962e80 Leszek Koltunski
369
    // clear buffers
370 e6519ac8 Leszek Koltunski
    GLES31.glStencilMask(0xff);
371
    GLES31.glDepthMask(true);
372
    GLES31.glColorMask(true,true,true,true);
373
    GLES31.glClearColor(0.0f,0.0f,0.0f,0.0f);
374
    GLES31.glClearDepthf(1.0f);
375
    GLES31.glClearStencil(0);
376 6b962e80 Leszek Koltunski
377
    buffer.setAsOutput();
378 e6519ac8 Leszek Koltunski
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[1], 0);
379
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
380
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[0], 0);
381
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
382 6b962e80 Leszek Koltunski
383
    return 1;
384
    }
385
386 af4cc5db Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
387 e02264ff leszek
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
388
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
389
// to a whole buffer and merge it.
390 39086ebb leszek
391 8e28b6ff leszek
  int renderChildren(long time, int numChildren, ArrayList<DistortedNode> children)
392 b2939df4 Leszek Koltunski
    {
393 7266d8ef Leszek Koltunski
    int quality=0, internalQuality = 0, numRenders = 0, bucketChange = 0;
394 3f44e745 Leszek Koltunski
    DistortedNode child1, child2;
395 70b6a155 Leszek Koltunski
    EffectQueuePostprocess lastQueue=null, currQueue;
396 915b7b2b leszek
    long lastBucket=0, currBucket;
397 0afc143a leszek
398 8e28b6ff leszek
    for(int i=0; i<numChildren; i++)
399 39086ebb leszek
      {
400 3f44e745 Leszek Koltunski
      child1 = children.get(i);
401 70b6a155 Leszek Koltunski
      currQueue = child1.getPostprocessQueue();
402
      currBucket= currQueue.getID();
403 b9798977 leszek
404 915b7b2b leszek
      if( currBucket==0 ) numRenders += child1.draw(time,this);
405 60c1c622 leszek
      else
406
        {
407 0f011027 Leszek Koltunski
        if( mBuffer[0]==null ) createBuffers();
408 c9a24bfb Leszek Koltunski
409 915b7b2b leszek
        if( lastBucket!=currBucket )
410 c9a24bfb Leszek Koltunski
          {
411 915b7b2b leszek
          if( lastBucket!=0 )
412 c9a24bfb Leszek Koltunski
            {
413
            for(int j=bucketChange; j<i; j++)
414
              {
415 3f44e745 Leszek Koltunski
              child2 = children.get(j);
416 70b6a155 Leszek Koltunski
              numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],lastQueue);
417 c9a24bfb Leszek Koltunski
              }
418
419 61441ce2 Leszek Koltunski
            numRenders += lastQueue.postprocess(mBuffer);
420 bed13bea leszek
            numRenders += blitWithDepth(time, mBuffer[quality]);
421 c9a24bfb Leszek Koltunski
            }
422 660cd468 leszek
423 70b6a155 Leszek Koltunski
          internalQuality = currQueue.getInternalQuality();
424
          quality         = currQueue.getQuality();
425
          bucketChange    = i;
426 c9a24bfb Leszek Koltunski
          }
427
428 70b6a155 Leszek Koltunski
        child1.draw(time,mBuffer[quality]);
429 c9a24bfb Leszek Koltunski
430 8e28b6ff leszek
        if( i==numChildren-1 )
431 cf7394cc leszek
          {
432 8e28b6ff leszek
          for(int j=bucketChange; j<numChildren; j++)
433 c9a24bfb Leszek Koltunski
            {
434 3f44e745 Leszek Koltunski
            child2 = children.get(j);
435 70b6a155 Leszek Koltunski
            numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],currQueue);
436 c9a24bfb Leszek Koltunski
            }
437
438 61441ce2 Leszek Koltunski
          numRenders += currQueue.postprocess(mBuffer);
439 7266d8ef Leszek Koltunski
          numRenders += blitWithDepth(time, mBuffer[quality]);
440 cf7394cc leszek
          }
441 60c1c622 leszek
        }
442 b9798977 leszek
443 70b6a155 Leszek Koltunski
      lastQueue = currQueue;
444
      lastBucket= currBucket;
445 95c441a2 leszek
      }
446 270c27bc Leszek Koltunski
447 39086ebb leszek
    return numRenders;
448
    }
449
450 be60d4ff leszek
///////////////////////////////////////////////////////////////////////////////////////////////////
451
452 26a4e5f6 leszek
  ArrayList<DistortedNode> getChildren()
453 be60d4ff leszek
    {
454 26a4e5f6 leszek
    return mChildren;
455 be60d4ff leszek
    }
456
457 b2939df4 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
458
// PUBLIC API
459 39086ebb leszek
///////////////////////////////////////////////////////////////////////////////////////////////////
460 86e99907 leszek
/**
461
 * Make the library show various debugging information.
462
 * <p>
463
 * Currently only DEBUG_FPS - show FPS in the upper-left corner of every Screen - is defined.
464
 *
465
 * @param bitmask 0, or a bitmask of DEBUG_** flags to enable (currently only DEBUG_FPS defined)
466
 */
467
  public void setDebug(int bitmask)
468
    {
469 26a4e5f6 leszek
    if( this instanceof DistortedScreen )
470
      mDebugLevel = bitmask;
471 86e99907 leszek
    }
472
473
///////////////////////////////////////////////////////////////////////////////////////////////////
474
475 c5369f1b leszek
/**
476 d9706fd2 Leszek Koltunski
 * Draws all the attached children to this OutputSurface.
477 af4cc5db Leszek Koltunski
 * <p>
478
 * Must be called from a thread holding OpenGL Context.
479
 *
480 d9706fd2 Leszek Koltunski
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
481 7691a39f leszek
 * @return Number of objects rendered.
482 c5369f1b leszek
 */
483 b2939df4 Leszek Koltunski
  public int render(long time)
484 af4cc5db Leszek Koltunski
    {
485 26a4e5f6 leszek
    if( mDebugLevel!=0 ) prepareDebug(time);
486 86e99907 leszek
487 c204c69d leszek
    // change tree topology (attach and detach children)
488 889cce10 Leszek Koltunski
/*
489 42571056 Leszek Koltunski
    boolean changed1 =
490 889cce10 Leszek Koltunski
*/
491 efe3d8fe leszek
    DistortedMaster.toDo();
492 eadf0859 leszek
/*
493 42571056 Leszek Koltunski
    if( changed1 )
494 c204c69d leszek
      {
495
      for(int i=0; i<mNumChildren; i++)
496
        {
497 af27df87 leszek
        mChildren.get(i).debug(0);
498 c204c69d leszek
        }
499 af27df87 leszek
500 7691a39f leszek
      DistortedNode.debugMap();
501 c204c69d leszek
      }
502 eadf0859 leszek
*/
503 09ab7524 Leszek Koltunski
    // create and delete all underlying OpenGL resources
504
    // Watch out: FIRST change topology, only then deal
505
    // with OpenGL resources. That's because changing Tree
506
    // can result in additional Framebuffers that would need
507
    // to be created immediately, before the calls to drawRecursive()
508 42571056 Leszek Koltunski
/*
509
    boolean changed2 =
510
*/
511 f8377ef8 leszek
    toDo();
512 eadf0859 leszek
/*
513 42571056 Leszek Koltunski
    if( changed2 )
514 af27df87 leszek
      {
515 226144d0 leszek
      DistortedObject.debugLists();
516 42571056 Leszek Koltunski
      }
517 eadf0859 leszek
*/
518 c834348d leszek
    // mark OpenGL state as unknown
519
    DistortedRenderState.reset();
520 2ed1c692 leszek
521 b2939df4 Leszek Koltunski
    int numRenders=0;
522 7691a39f leszek
523 d9706fd2 Leszek Koltunski
    for(int i=0; i<mNumChildren; i++)
524 af4cc5db Leszek Koltunski
      {
525 b2939df4 Leszek Koltunski
      numRenders += mChildren.get(i).renderRecursive(time);
526 af4cc5db Leszek Koltunski
      }
527 7691a39f leszek
528 070695a5 Leszek Koltunski
    setAsOutput(time);
529 b2939df4 Leszek Koltunski
    numRenders += renderChildren(time,mNumChildren,mChildren);
530
531 26a4e5f6 leszek
    if( mDebugLevel != 0 ) renderDebug(time);
532 b28c6c21 leszek
533 7691a39f leszek
    return numRenders;
534 af4cc5db Leszek Koltunski
    }
535
536
///////////////////////////////////////////////////////////////////////////////////////////////////
537 c5369f1b leszek
/**
538
 * Bind this Surface as a Framebuffer we can render to.
539 02ab6f9d leszek
 *
540
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
541
 *             out if this is the first time during present frame that this FBO is being set as output.
542
 *             If so, the library, in addition to binding the Surface for output, also clears the
543
 *             Surface's color and depth attachments.
544 c5369f1b leszek
 */
545 95c441a2 leszek
  public void setAsOutput(long time)
546 a436ccc5 leszek
    {
547 e6519ac8 Leszek Koltunski
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[0]);
548 95c441a2 leszek
549
    if( mTime!=time )
550
      {
551
      mTime = time;
552 23eecbd9 Leszek Koltunski
      DistortedRenderState.colorDepthStencilOn();
553 e6519ac8 Leszek Koltunski
      GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
554
      GLES31.glClearDepthf(mClearDepth);
555
      GLES31.glClearStencil(mClearStencil);
556
      GLES31.glClear(mClear);
557 144d252c Leszek Koltunski
      DistortedRenderState.colorDepthStencilRestore();
558 c14e495b Leszek Koltunski
559 2faad666 Leszek Koltunski
      if( mSSBO[0]>=0 )
560 df4d7edc Leszek Koltunski
        {
561
        // yes, this DOES keep on working when 'value' overflows into negative territory.
562 2faad666 Leszek Koltunski
        int value = mIntBuffer.get(FRAME_DELAY*mSurfaceID+mLastIndex);
563
564
        if( value-mLastValue[mLastIndex]!=mLastDiff )
565
          {
566
          android.util.Log.d("surface", "id " + mSurfaceID +
567
              (mType == TYPE_USER ? " USER" : (mType == TYPE_SYST ? " SYST" : " TREE")) +
568 a4b182d4 Leszek Koltunski
              "viewport: (" + mWidth + "x" + mHeight + ") last frame: " + (value - mLastValue[mLastIndex])
569 2faad666 Leszek Koltunski
              + " avg: " + (mAvgSum/RUNNING_AVERAGE)
570
          );
571
          }
572
573
        mLastDiff = value-mLastValue[mLastIndex];
574
        mLastValue[mLastIndex] = value;
575
576
        mAvgSum += (mLastDiff-mRunningAvg[mAvgIndex]);
577
        mRunningAvg[mAvgIndex] = mLastDiff;
578
        if( ++mAvgIndex>=RUNNING_AVERAGE ) mAvgIndex =0;
579 df4d7edc Leszek Koltunski
        }
580 2faad666 Leszek Koltunski
581
      if( ++mLastIndex >= FRAME_DELAY ) mLastIndex=0;
582 95c441a2 leszek
      }
583 a436ccc5 leszek
    }
584 af4cc5db Leszek Koltunski
585 1dfc9074 leszek
///////////////////////////////////////////////////////////////////////////////////////////////////
586
/**
587
 * Bind this Surface as a Framebuffer we can render to.
588
 * <p>
589
 * This version does not attempt to clear anything.
590
 */
591
592
  public void setAsOutput()
593
    {
594 e6519ac8 Leszek Koltunski
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[0]);
595 1dfc9074 leszek
    }
596
597
///////////////////////////////////////////////////////////////////////////////////////////////////
598
/**
599
 * Return the Near plane of the Projection included in the Surface.
600
 *
601
 * @return the Near plane.
602
 */
603
  public float getNear()
604
    {
605
    return mNear;
606
    }
607
608 638b5b5c leszek
///////////////////////////////////////////////////////////////////////////////////////////////////
609
/**
610
 * Set mipmap level.
611
 * <p>
612
 * Trick for speeding up your renders - one can create a pyramid of OutputSurface objects, each next
613
 * one some constant FACTOR smaller than the previous (0.5 is the common value), then set the Mipmap
614
 * Level of the i-th object to be FACTOR^i (we start counting from 0). When rendering any scene into
615
 * such prepared OutputSurface, the library will make sure to scale any Effects used so that the end
616
 * scene will end up looking identical no matter which object we render to. Identical, that is, except
617
 * for the loss of quality and gain in speed associated with rendering to a smaller Surface.
618 8426bd6a Leszek Koltunski
 * <p>
619
 * Example: if you create two FBOs, one 1000x1000 and another 500x500 in size, and set the second one
620
 * mipmap to 0.5 (the first one's is 1.0 by default), define Effects to be a single move by (100,100),
621
 * and render a skinned Mesh into both FBO, the end result will look proportionally the same, because
622
 * in the second case the move vector (100,100) will be auto-scaled to (50,50).
623 638b5b5c leszek
 *
624
 * @param mipmap The mipmap level. Acceptable range: 0&lt;mipmap&lt;infinity, although mipmap&gt;1
625
 *               does not make any sense (that would result in loss of speed and no gain in quality)
626
 */
627
  public void setMipmap(float mipmap)
628
    {
629
    mMipmap = mipmap;
630
    }
631
632 a9f41fa3 leszek
///////////////////////////////////////////////////////////////////////////////////////////////////
633
/**
634 e6519ac8 Leszek Koltunski
 * Set the (R,G,B,A) values of GLES31.glClearColor() to set up color with which to clear
635 ad16ed3b Leszek Koltunski
 * this Surface at the beginning of each frame.
636 a9f41fa3 leszek
 *
637
 * @param r the Red component. Default: 0.0f
638
 * @param g the Green component. Default: 0.0f
639
 * @param b the Blue component. Default: 0.0f
640
 * @param a the Alpha component. Default: 0.0f
641
 */
642
  public void glClearColor(float r, float g, float b, float a)
643
    {
644
    mClearR = r;
645
    mClearG = g;
646
    mClearB = b;
647
    mClearA = a;
648
    }
649
650
///////////////////////////////////////////////////////////////////////////////////////////////////
651
/**
652 23eecbd9 Leszek Koltunski
 * Uses glClearDepthf() to set up a value with which to clear
653
 * the Depth buffer of our Surface at the beginning of each frame.
654 a9f41fa3 leszek
 *
655
 * @param d the Depth. Default: 1.0f
656
 */
657
  public void glClearDepthf(float d)
658
    {
659
    mClearDepth = d;
660
    }
661
662 23eecbd9 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
663
/**
664
 * Uses glClearStencil() to set up a value with which to clear the
665
 * Stencil buffer of our Surface at the beginning of each frame.
666
 *
667
 * @param s the Stencil. Default: 0
668
 */
669
  public void glClearStencil(int s)
670
    {
671
    mClearStencil = s;
672
    }
673
674 ad16ed3b Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
675
/**
676
 * Which buffers to Clear at the beginning of each frame?
677
 * <p>
678
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
679
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
680
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
681
 *
682
 * @param mask bitwise OR of BUFFER_BITs to clear.
683
 */
684
  public void glClear(int mask)
685
    {
686
    mClear = mask;
687
    }
688
689 af4cc5db Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
690
/**
691
 * Create new Projection matrix.
692
 *
693
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
694 54fe333a leszek
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
695
 * @param near Distance between the screen plane and the near plane.
696 61441ce2 Leszek Koltunski
 *             Valid vaules: 0<near<1. When near==0 (illegal!), the Near Plane is exactly at the tip of
697
 *             the pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
698 af4cc5db Leszek Koltunski
 */
699 54fe333a leszek
  public void setProjection(float fov, float near)
700 af4cc5db Leszek Koltunski
    {
701 8069e806 Leszek Koltunski
    if( fov < 180.0f && fov >=0.0f )
702
      {
703
      mFOV = fov;
704
      }
705
706
    if( near<   1.0f && near> 0.0f )
707
      {
708
      mNear= near;
709
      }
710
    else if( near<=0.0f )
711
      {
712
      mNear = 0.01f;
713
      }
714
    else if( near>=1.0f )
715
      {
716
      mNear=0.99f;
717
      }
718 af4cc5db Leszek Koltunski
719 1dfc9074 leszek
    if( mBuffer[0]!=null )
720
      {
721
      for(int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].mNear = mNear;
722
      }
723
724 af4cc5db Leszek Koltunski
    createProjection();
725
    }
726
727
///////////////////////////////////////////////////////////////////////////////////////////////////
728 c5369f1b leszek
/**
729 af4cc5db Leszek Koltunski
 * Resize the underlying Framebuffer.
730 c7da4e65 leszek
 * <p>
731
 * This method can be safely called mid-render as it doesn't interfere with rendering.
732 af4cc5db Leszek Koltunski
 *
733
 * @param width The new width.
734
 * @param height The new height.
735 c5369f1b leszek
 */
736 af4cc5db Leszek Koltunski
  public void resize(int width, int height)
737
    {
738
    if( mWidth!=width || mHeight!=height )
739
      {
740 a4b182d4 Leszek Koltunski
      mWidth = mRealWidth = width;
741
      mHeight= mRealHeight= height;
742 f8377ef8 leszek
743
      createProjection();
744
745 c7da4e65 leszek
      if( mColorCreated==CREATED )
746 f8377ef8 leszek
        {
747 f28fffc2 Leszek Koltunski
        markForCreation();
748 f8377ef8 leszek
        recreate();
749
        }
750 af4cc5db Leszek Koltunski
      }
751
    }
752 a09ada4c Leszek Koltunski
753 a436ccc5 leszek
///////////////////////////////////////////////////////////////////////////////////////////////////
754
/**
755 89de975c leszek
 * Return true if the Surface contains a DEPTH attachment.
756 a436ccc5 leszek
 *
757 89de975c leszek
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
758 a436ccc5 leszek
 */
759 89de975c leszek
  public boolean hasDepth()
760 a436ccc5 leszek
    {
761 89de975c leszek
    return mDepthStencilCreated==CREATED;
762 a436ccc5 leszek
    }
763
764
///////////////////////////////////////////////////////////////////////////////////////////////////
765
/**
766 89de975c leszek
 * Return true if the Surface contains a STENCIL attachment.
767 a436ccc5 leszek
 *
768 89de975c leszek
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
769 a436ccc5 leszek
 */
770 89de975c leszek
  public boolean hasStencil()
771 a436ccc5 leszek
    {
772 89de975c leszek
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
773 a436ccc5 leszek
    }
774
775 a09ada4c Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
776
/**
777
 * Adds a new child to the last position in the list of our Surface's children.
778 c204c69d leszek
 * <p>
779
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
780 efe3d8fe leszek
 * DistortedMaster (by calling doWork())
781 a09ada4c Leszek Koltunski
 *
782
 * @param node The new Node to add.
783
 */
784 c204c69d leszek
  public void attach(DistortedNode node)
785 a09ada4c Leszek Koltunski
    {
786 ffbe7ecf Leszek Koltunski
    mJobs.add(new Job(ATTACH,node));
787 efe3d8fe leszek
    DistortedMaster.newSlave(this);
788 a09ada4c Leszek Koltunski
    }
789
790
///////////////////////////////////////////////////////////////////////////////////////////////////
791
/**
792
 * Adds a new child to the last position in the list of our Surface's children.
793 c204c69d leszek
 * <p>
794
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
795 efe3d8fe leszek
 * DistortedMaster (by calling doWork())
796 a09ada4c Leszek Koltunski
 *
797
 * @param surface InputSurface to initialize our child Node with.
798
 * @param effects DistortedEffects to initialize our child Node with.
799
 * @param mesh MeshObject to initialize our child Node with.
800
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
801
 */
802 c204c69d leszek
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
803 a09ada4c Leszek Koltunski
    {
804
    DistortedNode node = new DistortedNode(surface,effects,mesh);
805 ffbe7ecf Leszek Koltunski
    mJobs.add(new Job(ATTACH,node));
806 efe3d8fe leszek
    DistortedMaster.newSlave(this);
807 c204c69d leszek
    return node;
808
    }
809
810 af27df87 leszek
///////////////////////////////////////////////////////////////////////////////////////////////////
811
/**
812
 * Removes the first occurrence of a specified child from the list of children of our Surface.
813
 * <p>
814
 * A bit questionable method as there can be many different Nodes attached as children, some
815
 * of them having the same Effects but - for instance - different Mesh. Use with care.
816
 * <p>
817
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
818 efe3d8fe leszek
 * DistortedMaster (by calling doWork())
819 af27df87 leszek
 *
820
 * @param effects DistortedEffects to remove.
821
 */
822
  public void detach(DistortedEffects effects)
823
    {
824
    long id = effects.getID();
825
    DistortedNode node;
826 8baa1fe6 Leszek Koltunski
    boolean detached = false;
827 af27df87 leszek
828
    for(int i=0; i<mNumChildren; i++)
829
      {
830
      node = mChildren.get(i);
831
832
      if( node.getEffects().getID()==id )
833
        {
834 8baa1fe6 Leszek Koltunski
        detached = true;
835 ffbe7ecf Leszek Koltunski
        mJobs.add(new Job(DETACH,node));
836 efe3d8fe leszek
        DistortedMaster.newSlave(this);
837 af27df87 leszek
        break;
838
        }
839
      }
840 8baa1fe6 Leszek Koltunski
841
    if( !detached )
842
      {
843
      // if we failed to detach any, it still might be the case that
844 efe3d8fe leszek
      // there's an ATTACH job that we need to cancel.
845
      int num = mJobs.size();
846
      Job job;
847
848
      for(int i=0; i<num; i++)
849
        {
850
        job = mJobs.get(i);
851
852
        if( job.type==ATTACH && job.node.getEffects()==effects )
853
          {
854
          mJobs.remove(i);
855
          break;
856
          }
857
        }
858 8baa1fe6 Leszek Koltunski
      }
859 af27df87 leszek
    }
860
861 a09ada4c Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
862
/**
863
 * Removes the first occurrence of a specified child from the list of children of our Surface.
864 c204c69d leszek
 * <p>
865
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
866 efe3d8fe leszek
 * DistortedMaster (by calling doWork())
867 c204c69d leszek
 *
868
 * @param node The Node to remove.
869
 */
870
  public void detach(DistortedNode node)
871
    {
872 ffbe7ecf Leszek Koltunski
    mJobs.add(new Job(DETACH,node));
873 efe3d8fe leszek
    DistortedMaster.newSlave(this);
874 a09ada4c Leszek Koltunski
    }
875
876
///////////////////////////////////////////////////////////////////////////////////////////////////
877
/**
878
 * Removes all children Nodes.
879 c204c69d leszek
 * <p>
880
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
881 efe3d8fe leszek
 * DistortedMaster (by calling doWork())
882 c204c69d leszek
 */
883
  public void detachAll()
884
    {
885 ffbe7ecf Leszek Koltunski
    mJobs.add(new Job(DETALL,null));
886 efe3d8fe leszek
    DistortedMaster.newSlave(this);
887 c204c69d leszek
    }
888
889
///////////////////////////////////////////////////////////////////////////////////////////////////
890
/**
891
 * This is not really part of the public API. Has to be public only because it is a part of the
892 efe3d8fe leszek
 * DistortedSlave interface, which should really be a class that we extend here instead but
893 c204c69d leszek
 * Java has no multiple inheritance.
894 43fbf0dd leszek
 *
895
 * @y.exclude
896 a09ada4c Leszek Koltunski
 */
897 efe3d8fe leszek
  public void doWork()
898 a09ada4c Leszek Koltunski
    {
899 efe3d8fe leszek
    int num = mJobs.size();
900
    Job job;
901
902
    for(int i=0; i<num; i++)
903
      {
904
      job = mJobs.remove(0);
905
906
      switch(job.type)
907
        {
908 be60d4ff leszek
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
909
                     job.node.setSurfaceParent(this);
910
                     DistortedMaster.addSorted(mChildren,job.node);
911 efe3d8fe leszek
                     mNumChildren++;
912
                     break;
913 be60d4ff leszek
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
914 efe3d8fe leszek
                       {
915 be60d4ff leszek
                       job.node.setSurfaceParent(null);
916 efe3d8fe leszek
                       mNumChildren--;
917
                       }
918
                     break;
919 be60d4ff leszek
        case DETALL: if( mNumChildren>0 )
920 efe3d8fe leszek
                       {
921 be60d4ff leszek
                       DistortedNode tmp;
922
923
                       for(int j=mNumChildren-1; j>=0; j--)
924
                         {
925
                         tmp = mChildren.remove(j);
926
                         tmp.setSurfaceParent(null);
927
                         }
928
929 efe3d8fe leszek
                       mNumChildren = 0;
930
                       }
931
                     break;
932 ffbe7ecf Leszek Koltunski
        case SORT  : mChildren.remove(job.node);
933 be60d4ff leszek
                     DistortedMaster.addSorted(mChildren,job.node);
934 efe3d8fe leszek
                     break;
935
        }
936
      }
937 a09ada4c Leszek Koltunski
    }
938 af4cc5db Leszek Koltunski
}