Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedOutputSurface.java @ a07e0204

1
///////////////////////////////////////////////////////////////////////////////////////////////////
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
package org.distorted.library.main;
21

    
22
import android.opengl.GLES31;
23
import android.opengl.Matrix;
24

    
25
import org.distorted.library.effect.EffectQuality;
26

    
27
import java.util.ArrayList;
28

    
29
///////////////////////////////////////////////////////////////////////////////////////////////////
30
/**
31
 * This is not really part of the public API.
32
 *
33
 * @y.exclude
34
 */
35
public abstract class DistortedOutputSurface extends DistortedSurface implements DistortedMaster.Slave
36
{
37
/**
38
 * Do not create DEPTH or STENCIL attachment
39
 */
40
  public static final int NO_DEPTH_NO_STENCIL = 0;
41
/**
42
 * Create DEPTH, but not STENCIL
43
 */
44
  public static final int DEPTH_NO_STENCIL    = 1;
45
/**
46
 * Create both DEPTH and STENCIL
47
 */
48
  public static final int BOTH_DEPTH_STENCIL  = 2;
49

    
50
  private static final int ATTACH = 0;
51
  private static final int DETACH = 1;
52
  private static final int DETALL = 2;
53
  private static final int SORT   = 3;
54

    
55
  private ArrayList<DistortedNode> mChildren;
56
  private int mNumChildren;   // ==mChildren.length(), but we only create mChildren if the first one gets added
57

    
58
  private class Job
59
    {
60
    int type;
61
    DistortedNode node;
62

    
63
    Job(int t, DistortedNode n)
64
      {
65
      type = t;
66
      node = n;
67
      }
68
    }
69

    
70
  private ArrayList<Job> mJobs = new ArrayList<>();
71

    
72
  // Global buffers used for postprocessing.
73
  private static DistortedOutputSurface[] mBuffer = new DistortedOutputSurface[EffectQuality.LENGTH];
74

    
75
  private float mFOV;
76
  float mDistance, mNear;
77
  float[] mProjectionMatrix;
78

    
79
  int mDepthStencilCreated;
80
  int mDepthStencil;
81
  int[] mDepthStencilH;
82
  int[] mFBOH;
83
  private long[] mTime;
84

    
85
  private float mClearR, mClearG, mClearB, mClearA;
86
  private float mClearDepth;
87
  private int mClearStencil;
88
  private int mClear;
89
  float mMipmap;
90

    
91
  int mRealWidth;   // the Surface can be backed up with a texture that is
92
  int mRealHeight;  // larger than the viewport we have to it.
93
                    // mWidth,mHeight are the sizes of the Viewport, those -
94
                    // sizes of the backing up texture.
95

    
96
///////////////////////////////////////////////////////////////////////////////////////////////////
97

    
98
  DistortedOutputSurface(int width, int height, int createColor, int numfbos, int numcolors, int depthStencil, int fbo, int type)
99
    {
100
    super(width,height,createColor,numfbos,numcolors,type);
101

    
102
    mDepthStencilH = new int[numfbos];
103
    mFBOH          = new int[numfbos];
104

    
105
    mTime = new long[numfbos];
106
    for(int i=0; i<mNumFBOs;i++) mTime[i]=0;
107

    
108
    mRealWidth = width;
109
    mRealHeight= height;
110

    
111
    mProjectionMatrix = new float[16];
112

    
113
    mFOV = 60.0f;
114
    mNear=  0.5f;
115

    
116
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
117
    mDepthStencil = depthStencil;
118

    
119
    mFBOH[0]         = fbo;
120
    mDepthStencilH[0]= 0;
121

    
122
    mClearR = 0.0f;
123
    mClearG = 0.0f;
124
    mClearB = 0.0f;
125
    mClearA = 0.0f;
126

    
127
    mClearDepth = 1.0f;
128
    mClearStencil = 0;
129
    mClear = GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_COLOR_BUFFER_BIT;
130

    
131
    mMipmap = 1.0f;
132

    
133
    createProjection();
134
    }
135

    
136
///////////////////////////////////////////////////////////////////////////////////////////////////
137

    
138
  private void createProjection()
139
    {
140
    if( mWidth>0 && mHeight>1 )
141
      {
142
      if( mFOV>0.0f )  // perspective projection
143
        {
144
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
145
        float q = mWidth*mNear;
146
        float c = mHeight*mNear;
147

    
148
        float left   = -q/2;
149
        float right  = +q/2;
150
        float bottom = -c/2;
151
        float top    = +c/2;
152
        float near   =  c/a;
153

    
154
        mDistance    = mHeight/a;
155
        float far    = 2*mDistance-near;
156

    
157
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
158
        }
159
      else             // parallel projection
160
        {
161
        float left   = -mWidth/2.0f;
162
        float right  = +mWidth/2.0f;
163
        float bottom = -mHeight/2.0f;
164
        float top    = +mHeight/2.0f;
165
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
166
        mDistance    = mWidth+mHeight;
167
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
168

    
169
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
170
        }
171
      }
172
    }
173

    
174
///////////////////////////////////////////////////////////////////////////////////////////////////
175

    
176
  private static void createPostprocessingBuffers(int width, int height, float near)
177
    {
178
    float mipmap=1.0f;
179

    
180
    for (int j=0; j<EffectQuality.LENGTH; j++)
181
      {
182
      mBuffer[j] = new DistortedFramebuffer(Distorted.FBO_QUEUE_SIZE,2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(width*mipmap), (int)(height*mipmap) );
183
      mBuffer[j].mMipmap = mipmap;
184
      mBuffer[j].mNear = near;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
185
      mBuffer[j].glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
186

    
187
      mipmap *= EffectQuality.MULTIPLIER;
188
      }
189

    
190
    DistortedObject.toDo(); // create the FBOs immediately. This is safe as we must be holding the OpenGL context now.
191

    
192
    GLES31.glStencilMask(0xff);
193
    GLES31.glDepthMask(true);
194
    GLES31.glColorMask(true, true, true, true);
195
    GLES31.glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
196
    GLES31.glClearDepthf(1.0f);
197
    GLES31.glClearStencil(0);
198

    
199
    for (int j=0; j<EffectQuality.LENGTH; j++)
200
      {
201
      for(int k=0; k<Distorted.FBO_QUEUE_SIZE; k++)
202
        {
203
        GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mBuffer[j].mFBOH[k]);
204
        GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[2*k+1], 0);
205
        GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT | GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_STENCIL_BUFFER_BIT);
206
        GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[2*k  ], 0);
207
        GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
208
        }
209
      }
210

    
211
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, 0);
212
    }
213

    
214
///////////////////////////////////////////////////////////////////////////////////////////////////
215

    
216
  static synchronized void onDestroy()
217
    {
218
    for(int j=0; j<EffectQuality.LENGTH; j++)
219
      {
220
      mBuffer[j] = null;
221
      }
222
    }
223

    
224
///////////////////////////////////////////////////////////////////////////////////////////////////
225
// The postprocessing buffers mBuffer[] are generally speaking too large (there's just one static
226
// set of them) so before we use them for output, we need to adjust the Viewport as if they were
227
// smaller. That takes care of outputting pixels to them. When we use them as input, we have to
228
// adjust the texture coords - see the get{Width|Height}Correction functions.
229

    
230
  private static void clonePostprocessingViewport(DistortedOutputSurface from)
231
    {
232
    if( mBuffer[0].mWidth != from.mWidth || mBuffer[0].mHeight != from.mHeight )
233
      {
234
      DistortedOutputSurface surface;
235

    
236
      for(int i=0; i<EffectQuality.LENGTH; i++)
237
        {
238
        surface = mBuffer[i];
239

    
240
        surface.mWidth  = (int)(from.mWidth *surface.mMipmap);
241
        surface.mHeight = (int)(from.mHeight*surface.mMipmap);
242

    
243
        surface.mNear   = from.mNear;  // Near plane is independent of the mipmap level
244

    
245
        //android.util.Log.e("surface", "viewport "+i+" to ("+from.mWidth+"x"+from.mHeight+")");
246

    
247
        surface.createProjection();
248

    
249
        int maxw = surface.mWidth  > surface.mRealWidth  ? surface.mWidth  : surface.mRealWidth;
250
        int maxh = surface.mHeight > surface.mRealHeight ? surface.mHeight : surface.mRealHeight;
251

    
252
        if (maxw > surface.mRealWidth || maxh > surface.mRealHeight)
253
          {
254
          surface.mRealWidth = maxw;
255
          surface.mRealHeight = maxh;
256

    
257
          surface.recreate();
258
          surface.create();
259
          }
260
        }
261
      }
262
    }
263

    
264
///////////////////////////////////////////////////////////////////////////////////////////////////
265

    
266
  private int blitWithDepth(long currTime, DistortedOutputSurface buffer,int fbo)
267
    {
268
    GLES31.glViewport(0, 0, mWidth, mHeight);
269
    setAsOutputFBO(currTime,fbo);
270
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
271
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
272
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
273
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
274

    
275
    GLES31.glDisable(GLES31.GL_STENCIL_TEST);
276
    GLES31.glStencilMask(0x00);
277

    
278
    DistortedEffects.blitDepthPriv(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
279
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
280
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
281
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
282
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
283

    
284
    // clear buffers
285
    GLES31.glStencilMask(0xff);
286
    GLES31.glDepthMask(true);
287
    GLES31.glColorMask(true,true,true,true);
288
    GLES31.glClearColor(0.0f,0.0f,0.0f,0.0f);
289
    GLES31.glClearDepthf(1.0f);
290
    GLES31.glClearStencil(0);
291

    
292
    buffer.setAsOutputFBO(fbo);
293
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo+1], 0);
294
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
295
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo  ], 0);
296
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
297

    
298
    return 1;
299
    }
300

    
301
///////////////////////////////////////////////////////////////////////////////////////////////////
302

    
303
  private static void oitClear(DistortedOutputSurface buffer)
304
    {
305
    DistortedEffects.zeroOutAtomic();
306
    DistortedEffects.oitClear(buffer);
307
    GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT|GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
308
    }
309

    
310
///////////////////////////////////////////////////////////////////////////////////////////////////
311

    
312
  private int oitBuild(long time, DistortedOutputSurface buffer, int fbo)
313
    {
314
    GLES31.glViewport(0, 0, mWidth, mHeight);
315
    setAsOutputFBO(time,fbo);
316
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
317
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
318
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
319
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
320

    
321
    DistortedRenderState.colorDepthStencilOn();
322
    DistortedRenderState.enableDepthTest();
323

    
324
    DistortedEffects.oitBuild(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
325
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
326
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
327
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
328
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
329

    
330
    DistortedRenderState.colorDepthStencilRestore();
331
    DistortedRenderState.restoreDepthTest();
332

    
333
    return 1;
334
    }
335

    
336
///////////////////////////////////////////////////////////////////////////////////////////////////
337
// two phases: 1. collapse the SSBO 2. blend the ssbo's color
338

    
339
  private int oitRender(long currTime, int fbo)
340
    {
341
    float corrW = getWidthCorrection();
342
    float corrH = getHeightCorrection();
343

    
344
    // Do the Collapse Pass only if we do have a Depth attachment.
345
    // Otherwise there's no point (in fact we then would create a feedback loop!)
346

    
347
    if( mDepthStencilH[fbo] != 0 )
348
      {
349
      GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, 0);
350
      GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
351
      GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, mDepthStencilH[fbo]);
352
      DistortedRenderState.switchOffColorDepthStencil();
353
      DistortedEffects.oitCollapse(this, corrW, corrH);
354
      GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
355
      }
356

    
357
    setAsOutputFBO(currTime,fbo);
358
    DistortedRenderState.switchColorDepthOnStencilOff();
359
    DistortedEffects.oitRender(this, corrW, corrH);
360
    DistortedRenderState.restoreColorDepthStencil();
361

    
362
    return 1;
363
    }
364

    
365
///////////////////////////////////////////////////////////////////////////////////////////////////
366

    
367
  void clear()
368
    {
369
    DistortedRenderState.colorDepthStencilOn();
370
    GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
371
    GLES31.glClearDepthf(mClearDepth);
372
    GLES31.glClearStencil(mClearStencil);
373
    GLES31.glClear(mClear);
374
    DistortedRenderState.colorDepthStencilRestore();
375
    }
376

    
377
///////////////////////////////////////////////////////////////////////////////////////////////////
378
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
379
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
380
// to a whole buffer (lastQueue.postprocess) and merge it (this.oitBuild).
381

    
382
  int renderChildren(long time, int numChildren, ArrayList<DistortedNode> children, int fbo)
383
    {
384
    int quality=0, internalQuality = 0, numRenders = 0, bucketChange = 0;
385
    DistortedNode child1, child2;
386
    EffectQueuePostprocess lastQueue=null, currQueue;
387
    long lastBucket=0, currBucket;
388

    
389
    for(int i=0; i<numChildren; i++)
390
      {
391
      child1 = children.get(i);
392
      currQueue = child1.getPostprocessQueue();
393
      currBucket= currQueue.getID();
394

    
395
      if( currBucket==0 )
396
        {
397
        setAsOutputFBO(time,fbo);
398
        numRenders += child1.draw(time,this);
399
        }
400
      else
401
        {
402
        if( mBuffer[0]==null ) createPostprocessingBuffers(mWidth,mHeight,mNear);
403

    
404
        if( lastBucket!=currBucket )
405
          {
406
          if( lastBucket==0 )
407
            {
408
            clonePostprocessingViewport(this);
409
            oitClear(this);
410
            }
411
          else
412
            {
413
            for(int j=bucketChange; j<i; j++)
414
              {
415
              child2 = children.get(j);
416
              mBuffer[internalQuality].setAsOutputFBO(fbo);
417
              numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],lastQueue);
418
              }
419

    
420
            numRenders += lastQueue.postprocess(mBuffer,fbo);
421
            numRenders += oitBuild(time,mBuffer[quality],fbo);
422
            GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT|GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
423
            mBuffer[quality].clearBuffer(fbo);
424
            }
425

    
426
          internalQuality = currQueue.getInternalQuality();
427
          quality         = currQueue.getQuality();
428
          bucketChange    = i;
429
          }
430

    
431
        mBuffer[quality].setAsOutputFBO(time,fbo);
432
        child1.drawNoBlend(time,mBuffer[quality]);
433

    
434
        if( i==numChildren-1 )
435
          {
436
          for(int j=bucketChange; j<numChildren; j++)
437
            {
438
            child2 = children.get(j);
439
            mBuffer[internalQuality].setAsOutputFBO(fbo);
440
            numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],currQueue);
441
            }
442

    
443
          numRenders += currQueue.postprocess(mBuffer,fbo);
444
          numRenders += oitBuild(time,mBuffer[quality],fbo);
445
          GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT|GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
446
          numRenders += oitRender(time,fbo);  // merge the OIT linked list
447
          mBuffer[quality].clearBuffer(fbo);
448
          }
449
        } // end else (postprocessed child)
450

    
451
      lastQueue = currQueue;
452
      lastBucket= currBucket;
453
      } // end main for loop
454

    
455
    return numRenders;
456
    }
457

    
458
///////////////////////////////////////////////////////////////////////////////////////////////////
459

    
460
  ArrayList<DistortedNode> getChildren()
461
    {
462
    return mChildren;
463
    }
464

    
465
///////////////////////////////////////////////////////////////////////////////////////////////////
466
/**
467
 * Not part of the Public API.
468
 *
469
 * @y.exclude
470
 */
471
  public float getWidthCorrection()
472
    {
473
    return (float)mWidth/mRealWidth;
474
    }
475

    
476
///////////////////////////////////////////////////////////////////////////////////////////////////
477
/**
478
 * Not part of the Public API.
479
 *
480
 * @y.exclude
481
 */
482
  public float getHeightCorrection()
483
    {
484
    return (float)mHeight/mRealHeight;
485
    }
486

    
487
///////////////////////////////////////////////////////////////////////////////////////////////////
488

    
489
  private void clearBuffer(int fbo)
490
    {
491
    DistortedRenderState.colorDepthStencilOn();
492

    
493
    GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
494
    GLES31.glClearDepthf(mClearDepth);
495
    GLES31.glClearStencil(mClearStencil);
496

    
497
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[fbo]);
498
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mColorH[2*fbo+1], 0);
499
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
500
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mColorH[2*fbo  ], 0);
501
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
502

    
503
    DistortedRenderState.colorDepthStencilRestore();
504
    }
505

    
506
///////////////////////////////////////////////////////////////////////////////////////////////////
507

    
508
  private void setAsOutputFBO(long time, int fbo)
509
    {
510
    if( fbo>=0 && fbo<mNumFBOs )
511
      {
512
      GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[fbo]);
513

    
514
      if (mTime[fbo] != time)
515
        {
516
        mTime[fbo] = time;
517
        clear();
518
        }
519
      }
520
    else
521
      {
522
      android.util.Log.e("surface", "error in setAsOutput1, fbo="+fbo);
523
      }
524
    }
525

    
526
///////////////////////////////////////////////////////////////////////////////////////////////////
527
/**
528
 * Not part of the Public API.
529
 *
530
 * @y.exclude
531
 */
532
  public void setAsOutputFBO(int fbo)
533
    {
534
    if( fbo>=0 && fbo<mNumFBOs )
535
      {
536
      GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[fbo]);
537
      }
538
    else
539
      {
540
      android.util.Log.e("surface", "error in setAsOutput2, fbo="+fbo);
541
      }
542
    }
543

    
544
///////////////////////////////////////////////////////////////////////////////////////////////////
545
// PUBLIC API
546
///////////////////////////////////////////////////////////////////////////////////////////////////
547
/**
548
 * Draws all the attached children to this OutputSurface's 0th FBO.
549
 * <p>
550
 * Must be called from a thread holding OpenGL Context.
551
 *
552
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
553
 * @return Number of objects rendered.
554
 */
555
  public int render(long time)
556
    {
557
    return render(time,0);
558
    }
559

    
560
///////////////////////////////////////////////////////////////////////////////////////////////////
561
/**
562
 * Draws all the attached children to this OutputSurface.
563
 * <p>
564
 * Must be called from a thread holding OpenGL Context.
565
 *
566
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
567
 * @param fbo The surface can have many FBOs backing it up - render this to FBO number 'fbo'.
568
 * @return Number of objects rendered.
569
 */
570
  public int render(long time, int fbo)
571
    {
572
    // change tree topology (attach and detach children)
573
/*
574
    boolean changed1 =
575
*/
576
    DistortedMaster.toDo();
577
/*
578
    if( changed1 )
579
      {
580
      for(int i=0; i<mNumChildren; i++)
581
        {
582
        mChildren.get(i).debug(0);
583
        }
584

    
585
      DistortedNode.debugMap();
586
      }
587
*/
588
    // create and delete all underlying OpenGL resources
589
    // Watch out: FIRST change topology, only then deal
590
    // with OpenGL resources. That's because changing Tree
591
    // can result in additional Framebuffers that would need
592
    // to be created immediately, before the calls to drawRecursive()
593
/*
594
    boolean changed2 =
595
*/
596
    toDo();
597
/*
598
    if( changed2 )
599
      {
600
      DistortedObject.debugLists();
601
      }
602
*/
603
    // mark OpenGL state as unknown
604
    DistortedRenderState.reset();
605

    
606
    int numRenders=0;
607

    
608
    for(int i=0; i<mNumChildren; i++)
609
      {
610
      numRenders += mChildren.get(i).renderRecursive(time);
611
      }
612

    
613
    numRenders += renderChildren(time,mNumChildren,mChildren,fbo);
614

    
615
    return numRenders;
616
    }
617

    
618
///////////////////////////////////////////////////////////////////////////////////////////////////
619
/**
620
 * Bind this Surface as a Framebuffer we can render to.
621
 *
622
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
623
 *             out if this is the first time during present frame that this FBO is being set as output.
624
 *             If so, the library, in addition to binding the Surface for output, also clears the
625
 *             Surface's color and depth attachments.
626
 */
627
  public void setAsOutput(long time)
628
    {
629
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[0]);
630

    
631
    if( mTime[0]!=time )
632
      {
633
      mTime[0] = time;
634
      clear();
635
      }
636
    }
637

    
638
///////////////////////////////////////////////////////////////////////////////////////////////////
639
/**
640
 * Bind this Surface as a Framebuffer we can render to.
641
 * <p>
642
 * This version does not attempt to clear anything.
643
 */
644
  public void setAsOutput()
645
    {
646
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[0]);
647
    }
648

    
649
///////////////////////////////////////////////////////////////////////////////////////////////////
650
/**
651
 * Return the Near plane of the Projection included in the Surface.
652
 *
653
 * @return the Near plane.
654
 */
655
  public float getNear()
656
    {
657
    return mNear;
658
    }
659

    
660
///////////////////////////////////////////////////////////////////////////////////////////////////
661
/**
662
 * Set mipmap level.
663
 * <p>
664
 * Trick for speeding up your renders - one can create a pyramid of OutputSurface objects, each next
665
 * one some constant FACTOR smaller than the previous (0.5 is the common value), then set the Mipmap
666
 * Level of the i-th object to be FACTOR^i (we start counting from 0). When rendering any scene into
667
 * such prepared OutputSurface, the library will make sure to scale any Effects used so that the end
668
 * scene will end up looking identical no matter which object we render to. Identical, that is, except
669
 * for the loss of quality and gain in speed associated with rendering to a smaller Surface.
670
 * <p>
671
 * Example: if you create two FBOs, one 1000x1000 and another 500x500 in size, and set the second one
672
 * mipmap to 0.5 (the first one's is 1.0 by default), define Effects to be a single move by (100,100),
673
 * and render a skinned Mesh into both FBO, the end result will look proportionally the same, because
674
 * in the second case the move vector (100,100) will be auto-scaled to (50,50).
675
 *
676
 * @param mipmap The mipmap level. Acceptable range: 0&lt;mipmap&lt;infinity, although mipmap&gt;1
677
 *               does not make any sense (that would result in loss of speed and no gain in quality)
678
 */
679
  public void setMipmap(float mipmap)
680
    {
681
    mMipmap = mipmap;
682
    }
683

    
684
///////////////////////////////////////////////////////////////////////////////////////////////////
685
/**
686
 * Set the (R,G,B,A) values of GLES31.glClearColor() to set up color with which to clear
687
 * this Surface at the beginning of each frame.
688
 *
689
 * @param r the Red component. Default: 0.0f
690
 * @param g the Green component. Default: 0.0f
691
 * @param b the Blue component. Default: 0.0f
692
 * @param a the Alpha component. Default: 0.0f
693
 */
694
  public void glClearColor(float r, float g, float b, float a)
695
    {
696
    mClearR = r;
697
    mClearG = g;
698
    mClearB = b;
699
    mClearA = a;
700
    }
701

    
702
///////////////////////////////////////////////////////////////////////////////////////////////////
703
/**
704
 * Uses glClearDepthf() to set up a value with which to clear
705
 * the Depth buffer of our Surface at the beginning of each frame.
706
 *
707
 * @param d the Depth. Default: 1.0f
708
 */
709
  public void glClearDepthf(float d)
710
    {
711
    mClearDepth = d;
712
    }
713

    
714
///////////////////////////////////////////////////////////////////////////////////////////////////
715
/**
716
 * Uses glClearStencil() to set up a value with which to clear the
717
 * Stencil buffer of our Surface at the beginning of each frame.
718
 *
719
 * @param s the Stencil. Default: 0
720
 */
721
  public void glClearStencil(int s)
722
    {
723
    mClearStencil = s;
724
    }
725

    
726
///////////////////////////////////////////////////////////////////////////////////////////////////
727
/**
728
 * Which buffers to Clear at the beginning of each frame?
729
 * <p>
730
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
731
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
732
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
733
 *
734
 * @param mask bitwise OR of BUFFER_BITs to clear.
735
 */
736
  public void glClear(int mask)
737
    {
738
    mClear = mask;
739
    }
740

    
741
///////////////////////////////////////////////////////////////////////////////////////////////////
742
/**
743
 * Create new Projection matrix.
744
 *
745
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
746
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
747
 * @param near Distance between the screen plane and the near plane.
748
 *             Valid vaules: 0<near<1. When near==0 (illegal!), the Near Plane is exactly at the tip of
749
 *             the pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
750
 */
751
  public void setProjection(float fov, float near)
752
    {
753
    if( fov < 180.0f && fov >=0.0f )
754
      {
755
      mFOV = fov;
756
      }
757

    
758
    if( near<   1.0f && near> 0.0f )
759
      {
760
      mNear= near;
761
      }
762
    else if( near<=0.0f )
763
      {
764
      mNear = 0.01f;
765
      }
766
    else if( near>=1.0f )
767
      {
768
      mNear=0.99f;
769
      }
770

    
771
    if( mBuffer!=null )
772
      {
773
      for(int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].mNear = mNear;
774
      }
775

    
776
    createProjection();
777
    }
778

    
779
///////////////////////////////////////////////////////////////////////////////////////////////////
780
/**
781
 * Resize the underlying Framebuffer.
782
 * <p>
783
 * This method can be safely called mid-render as it doesn't interfere with rendering.
784
 *
785
 * @param width The new width.
786
 * @param height The new height.
787
 */
788
  public void resize(int width, int height)
789
    {
790
    if( mWidth!=width || mHeight!=height )
791
      {
792
      mWidth = mRealWidth = width;
793
      mHeight= mRealHeight= height;
794

    
795
      createProjection();
796

    
797
      if( mColorCreated==CREATED )
798
        {
799
        markForCreation();
800
        recreate();
801
        }
802
      }
803
    }
804

    
805
///////////////////////////////////////////////////////////////////////////////////////////////////
806
/**
807
 * Return true if the Surface contains a DEPTH attachment.
808
 *
809
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
810
 */
811
  public boolean hasDepth()
812
    {
813
    return mDepthStencilCreated==CREATED;
814
    }
815

    
816
///////////////////////////////////////////////////////////////////////////////////////////////////
817
/**
818
 * Return true if the Surface contains a STENCIL attachment.
819
 *
820
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
821
 */
822
  public boolean hasStencil()
823
    {
824
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
825
    }
826

    
827
///////////////////////////////////////////////////////////////////////////////////////////////////
828
/**
829
 * Adds a new child to the last position in the list of our Surface's children.
830
 * <p>
831
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
832
 * DistortedMaster (by calling doWork())
833
 *
834
 * @param node The new Node to add.
835
 */
836
  public void attach(DistortedNode node)
837
    {
838
    mJobs.add(new Job(ATTACH,node));
839
    DistortedMaster.newSlave(this);
840
    }
841

    
842
///////////////////////////////////////////////////////////////////////////////////////////////////
843
/**
844
 * Adds a new child to the last position in the list of our Surface's children.
845
 * <p>
846
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
847
 * DistortedMaster (by calling doWork())
848
 *
849
 * @param surface InputSurface to initialize our child Node with.
850
 * @param effects DistortedEffects to initialize our child Node with.
851
 * @param mesh MeshObject to initialize our child Node with.
852
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
853
 */
854
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
855
    {
856
    DistortedNode node = new DistortedNode(surface,effects,mesh);
857
    mJobs.add(new Job(ATTACH,node));
858
    DistortedMaster.newSlave(this);
859
    return node;
860
    }
861

    
862
///////////////////////////////////////////////////////////////////////////////////////////////////
863
/**
864
 * Removes the first occurrence of a specified child from the list of children of our Surface.
865
 * <p>
866
 * A bit questionable method as there can be many different Nodes attached as children, some
867
 * of them having the same Effects but - for instance - different Mesh. Use with care.
868
 * <p>
869
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
870
 * DistortedMaster (by calling doWork())
871
 *
872
 * @param effects DistortedEffects to remove.
873
 */
874
  public void detach(DistortedEffects effects)
875
    {
876
    long id = effects.getID();
877
    DistortedNode node;
878
    boolean detached = false;
879

    
880
    for(int i=0; i<mNumChildren; i++)
881
      {
882
      node = mChildren.get(i);
883

    
884
      if( node.getEffects().getID()==id )
885
        {
886
        detached = true;
887
        mJobs.add(new Job(DETACH,node));
888
        DistortedMaster.newSlave(this);
889
        break;
890
        }
891
      }
892

    
893
    if( !detached )
894
      {
895
      // if we failed to detach any, it still might be the case that
896
      // there's an ATTACH job that we need to cancel.
897
      int num = mJobs.size();
898
      Job job;
899

    
900
      for(int i=0; i<num; i++)
901
        {
902
        job = mJobs.get(i);
903

    
904
        if( job.type==ATTACH && job.node.getEffects()==effects )
905
          {
906
          mJobs.remove(i);
907
          break;
908
          }
909
        }
910
      }
911
    }
912

    
913
///////////////////////////////////////////////////////////////////////////////////////////////////
914
/**
915
 * Removes the first occurrence of a specified child from the list of children of our Surface.
916
 * <p>
917
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
918
 * DistortedMaster (by calling doWork())
919
 *
920
 * @param node The Node to remove.
921
 */
922
  public void detach(DistortedNode node)
923
    {
924
    mJobs.add(new Job(DETACH,node));
925
    DistortedMaster.newSlave(this);
926
    }
927

    
928
///////////////////////////////////////////////////////////////////////////////////////////////////
929
/**
930
 * Removes all children Nodes.
931
 * <p>
932
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
933
 * DistortedMaster (by calling doWork())
934
 */
935
  public void detachAll()
936
    {
937
    mJobs.add(new Job(DETALL,null));
938
    DistortedMaster.newSlave(this);
939
    }
940

    
941
///////////////////////////////////////////////////////////////////////////////////////////////////
942
/**
943
 * This is not really part of the public API. Has to be public only because it is a part of the
944
 * DistortedSlave interface, which should really be a class that we extend here instead but
945
 * Java has no multiple inheritance.
946
 *
947
 * @y.exclude
948
 */
949
  public void doWork()
950
    {
951
    int num = mJobs.size();
952
    Job job;
953

    
954
    for(int i=0; i<num; i++)
955
      {
956
      job = mJobs.remove(0);
957

    
958
      switch(job.type)
959
        {
960
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
961
                     job.node.setSurfaceParent(this);
962
                     DistortedMaster.addSortingByBuckets(mChildren,job.node);
963
                     mNumChildren++;
964
                     break;
965
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
966
                       {
967
                       job.node.setSurfaceParent(null);
968
                       mNumChildren--;
969
                       }
970
                     break;
971
        case DETALL: if( mNumChildren>0 )
972
                       {
973
                       DistortedNode tmp;
974

    
975
                       for(int j=mNumChildren-1; j>=0; j--)
976
                         {
977
                         tmp = mChildren.remove(j);
978
                         tmp.setSurfaceParent(null);
979
                         }
980

    
981
                       mNumChildren = 0;
982
                       }
983
                     break;
984
        case SORT  : mChildren.remove(job.node);
985
                     DistortedMaster.addSortingByBuckets(mChildren,job.node);
986
                     break;
987
        }
988
      }
989
    }
990
}
(8-8/21)