Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedOutputSurface.java @ 2faad666

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