Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedOutputSurface.java @ 66a0fa17

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
//////////// DEBUG FLAGS /////////////////////////////////////////////
38
/**
39
 * When rendering a Screen, show FPS in the upper-left corner?
40
 */
41
public static final int DEBUG_FPS = 1;
42
//////////// END DEBUG FLAGS /////////////////////////////////////////
43

    
44
/**
45
 * Do not create DEPTH or STENCIL attachment
46
 */
47
  public static final int NO_DEPTH_NO_STENCIL = 0;
48
/**
49
 * Create DEPTH, but not STENCIL
50
 */
51
  public static final int DEPTH_NO_STENCIL    = 1;
52
/**
53
 * Create both DEPTH and STENCIL
54
 */
55
  public static final int BOTH_DEPTH_STENCIL  = 2;
56

    
57
  private static final int ATTACH = 0;
58
  private static final int DETACH = 1;
59
  private static final int DETALL = 2;
60
  private static final int SORT   = 3;
61

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

    
65
  private class Job
66
    {
67
    int type;
68
    DistortedNode node;
69

    
70
    Job(int t, DistortedNode n)
71
      {
72
      type = t;
73
      node = n;
74
      }
75
    }
76

    
77
  private ArrayList<Job> mJobs = new ArrayList<>();
78

    
79
  // Global buffers used for postprocessing.
80
  private static DistortedOutputSurface[] mBuffer = new DistortedOutputSurface[EffectQuality.LENGTH];
81
  private static DistortedOutputSurface   mBufferOIT;
82

    
83
  private long mTime;
84
  private float mFOV;
85
  float mDistance, mNear;
86
  float[] mProjectionMatrix;
87

    
88
  int mDepthStencilCreated;
89
  int mDepthStencil;
90
  int[] mDepthStencilH = new int[1];
91
  int[] mFBOH          = new int[1];
92

    
93
  private float mClearR, mClearG, mClearB, mClearA;
94
  private float mClearDepth;
95
  private int mClearStencil;
96
  private int mClear;
97
  float mMipmap;
98

    
99
  private int mDebugLevel;
100

    
101
  int mRealWidth;   // the Surface can be backed up with a texture that is
102
  int mRealHeight;  // larger than the viewport we have to it.
103
                    // mWidth,mHeight are the sizes of the Viewport, those -
104
                    // sizes of the backing up texture.
105

    
106
///////////////////////////////////////////////////////////////////////////////////////////////////
107

    
108
  abstract void prepareDebug(long time);
109
  abstract void renderDebug(long time);
110

    
111
///////////////////////////////////////////////////////////////////////////////////////////////////
112

    
113
  DistortedOutputSurface(int width, int height, int createColor, int numcolors, int depthStencil, int fbo, int type)
114
    {
115
    super(width,height,createColor,numcolors,type);
116

    
117
    mRealWidth = width;
118
    mRealHeight= height;
119

    
120
    mProjectionMatrix = new float[16];
121

    
122
    mFOV = 60.0f;
123
    mNear=  0.5f;
124

    
125
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
126
    mDepthStencil = depthStencil;
127

    
128
    mFBOH[0]         = fbo;
129
    mDepthStencilH[0]= 0;
130

    
131
    mTime = 0;
132
    mDebugLevel = 0;
133

    
134
    mClearR = 0.0f;
135
    mClearG = 0.0f;
136
    mClearB = 0.0f;
137
    mClearA = 0.0f;
138

    
139
    mClearDepth = 1.0f;
140
    mClearStencil = 0;
141
    mClear = GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_COLOR_BUFFER_BIT;
142

    
143
    mMipmap = 1.0f;
144

    
145
    createProjection();
146
    }
147

    
148
///////////////////////////////////////////////////////////////////////////////////////////////////
149

    
150
  private void createProjection()
151
    {
152
    if( mWidth>0 && mHeight>1 )
153
      {
154
      if( mFOV>0.0f )  // perspective projection
155
        {
156
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
157
        float q = mWidth*mNear;
158
        float c = mHeight*mNear;
159

    
160
        float left   = -q/2;
161
        float right  = +q/2;
162
        float bottom = -c/2;
163
        float top    = +c/2;
164
        float near   =  c/a;
165

    
166
        mDistance    = mHeight/a;
167
        float far    = 2*mDistance-near;
168

    
169
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
170
        }
171
      else             // parallel projection
172
        {
173
        float left   = -mWidth/2.0f;
174
        float right  = +mWidth/2.0f;
175
        float bottom = -mHeight/2.0f;
176
        float top    = +mHeight/2.0f;
177
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
178
        mDistance    = mWidth+mHeight;
179
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
180

    
181
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
182
        }
183
      }
184
    }
185

    
186
///////////////////////////////////////////////////////////////////////////////////////////////////
187

    
188
  private static void createPostprocessingBuffers(int width, int height, float near)
189
    {
190
    float mipmap=1.0f;
191

    
192
    for (int j=0; j<EffectQuality.LENGTH; j++)
193
      {
194
      mBuffer[j] = new DistortedFramebuffer(2, BOTH_DEPTH_STENCIL, TYPE_SYST, (int) (width * mipmap), (int) (height * mipmap));
195
      mBuffer[j].mMipmap = mipmap;
196
      mBuffer[j].mNear = near;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
197
      mBuffer[j].glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
198

    
199
      mipmap *= EffectQuality.MULTIPLIER;
200
      }
201

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

    
204
    GLES31.glStencilMask(0xff);
205
    GLES31.glDepthMask(true);
206
    GLES31.glColorMask(true, true, true, true);
207
    GLES31.glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
208
    GLES31.glClearDepthf(1.0f);
209
    GLES31.glClearStencil(0);
210

    
211
    for (int j=0; j<EffectQuality.LENGTH; j++)
212
      {
213
      mBuffer[j].setAsOutput();
214
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[1], 0);
215
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT | GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_STENCIL_BUFFER_BIT);
216
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[0], 0);
217
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
218
      }
219
    }
220

    
221
///////////////////////////////////////////////////////////////////////////////////////////////////
222

    
223
  static synchronized void onDestroy()
224
    {
225
    for(int j=0; j<EffectQuality.LENGTH; j++)
226
      {
227
      mBuffer[j] = null;
228
      }
229

    
230
    mBufferOIT = null;
231
    }
232

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

    
239
  private static void clonePostprocessingViewport(DistortedOutputSurface from)
240
    {
241
    if( mBuffer[0].mWidth != from.mWidth || mBuffer[0].mHeight != from.mHeight )
242
      {
243
      DistortedOutputSurface surface;
244

    
245
      for(int i=0; i<EffectQuality.LENGTH; i++)
246
        {
247
        surface = mBuffer[i];
248

    
249
        surface.mWidth  = (int)(from.mWidth *surface.mMipmap);
250
        surface.mHeight = (int)(from.mHeight*surface.mMipmap);
251

    
252
        surface.mNear   = from.mNear;  // Near plane is independent of the mipmap level
253

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

    
256
        surface.createProjection();
257

    
258
        int maxw = surface.mWidth  > surface.mRealWidth  ? surface.mWidth  : surface.mRealWidth;
259
        int maxh = surface.mHeight > surface.mRealHeight ? surface.mHeight : surface.mRealHeight;
260

    
261
        if (maxw > surface.mRealWidth || maxh > surface.mRealHeight)
262
          {
263
          surface.mRealWidth = maxw;
264
          surface.mRealHeight = maxh;
265

    
266
          surface.recreate();
267
          surface.create();
268
          }
269
        }
270
      }
271
    }
272

    
273
///////////////////////////////////////////////////////////////////////////////////////////////////
274

    
275
  private static void oitClear(DistortedOutputSurface buffer)
276
    {
277
    if( mBufferOIT==null )
278
      {
279
      mBufferOIT = new DistortedFramebuffer(1, BOTH_DEPTH_STENCIL, TYPE_SYST, buffer.mWidth, buffer.mHeight);
280
      mBufferOIT.mMipmap = 1.0f;
281
      mBufferOIT.mNear = buffer.mNear;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
282
      mBufferOIT.glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
283

    
284
      DistortedObject.toDo(); // create the FBOs immediately. This is safe as we must be holding the OpenGL context now.
285
      }
286

    
287
    if( mBufferOIT.mWidth != buffer.mWidth || mBufferOIT.mHeight != buffer.mHeight )
288
      {
289
      mBufferOIT.mWidth  = (int)(buffer.mWidth *mBufferOIT.mMipmap);
290
      mBufferOIT.mHeight = (int)(buffer.mHeight*mBufferOIT.mMipmap);
291

    
292
      mBufferOIT.mNear   = buffer.mNear;  // Near plane is independent of the mipmap level
293

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

    
296
      mBufferOIT.createProjection();
297

    
298
      int maxw = mBufferOIT.mWidth  > mBufferOIT.mRealWidth  ? mBufferOIT.mWidth  : mBufferOIT.mRealWidth;
299
      int maxh = mBufferOIT.mHeight > mBufferOIT.mRealHeight ? mBufferOIT.mHeight : mBufferOIT.mRealHeight;
300

    
301
      if (maxw > mBufferOIT.mRealWidth || maxh > mBufferOIT.mRealHeight)
302
        {
303
        mBufferOIT.mRealWidth = maxw;
304
        mBufferOIT.mRealHeight = maxh;
305

    
306
        mBufferOIT.recreate();
307
        mBufferOIT.create();
308
        }
309
      }
310

    
311
    if( mBufferOIT.mNear != buffer.mNear || mBufferOIT.mFOV != buffer.mFOV )
312
      {
313
      mBufferOIT.mNear = buffer.mNear;
314
      mBufferOIT.mFOV  = buffer.mFOV;
315
      mBufferOIT.createProjection();
316
      }
317

    
318
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mBufferOIT.mFBOH[0]);
319
    DistortedRenderState.colorDepthStencilOn();
320
    GLES31.glClearColor(buffer.mClearR, buffer.mClearG, buffer.mClearB, buffer.mClearA);
321
    GLES31.glClearDepthf(buffer.mClearDepth);
322
    GLES31.glClearStencil(buffer.mClearStencil);
323
    GLES31.glClear(buffer.mClear);
324
    DistortedRenderState.colorDepthStencilRestore();
325

    
326
    DistortedEffects.zeroOutAtomic();
327
    DistortedEffects.oitClear(buffer);
328

    
329
    GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT|GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
330
    }
331

    
332
///////////////////////////////////////////////////////////////////////////////////////////////////
333

    
334
  private int oitBuild(DistortedOutputSurface buffer)
335
    {
336
    GLES31.glViewport(0, 0, mWidth, mHeight);
337
    setAsOutput();
338
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
339
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[0]);
340
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
341
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[0]);
342

    
343
    //GLES31.glDisable(GLES31.GL_STENCIL_TEST);
344
    //GLES31.glStencilMask(0x00);
345

    
346
    DistortedRenderState.colorDepthStencilOn();
347
    DistortedRenderState.enableDepthTest();
348

    
349
    DistortedEffects.oitBuild(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
350
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
351
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
352
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
353
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
354

    
355
    DistortedRenderState.colorDepthStencilRestore();
356
    DistortedRenderState.restoreDepthTest();
357

    
358
    return 1;
359
    }
360

    
361
///////////////////////////////////////////////////////////////////////////////////////////////////
362

    
363
  private int oitRender(long currTime, DistortedOutputSurface buffer)
364
    {
365
    GLES31.glViewport(0, 0, mWidth, mHeight);
366
    setAsOutput(currTime);
367
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
368
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[0]);
369
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
370
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[0]);
371

    
372
    DistortedRenderState.enableStencil();
373

    
374
    DistortedEffects.oitRender(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
375
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
376
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
377

    
378
    DistortedRenderState.restoreStencil();
379

    
380
    return 1;
381
    }
382

    
383
///////////////////////////////////////////////////////////////////////////////////////////////////
384

    
385
  private static void clearBuffer(DistortedOutputSurface buffer)
386
    {
387
    GLES31.glStencilMask(0xff);
388
    GLES31.glDepthMask(true);
389
    GLES31.glColorMask(true,true,true,true);
390
    GLES31.glClearColor(1.0f,1.0f,1.0f,0.0f);
391
    GLES31.glClearDepthf(1.0f);
392
    GLES31.glClearStencil(0);
393

    
394
    buffer.setAsOutput();
395
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[buffer.mNumColors-1], 0);
396
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
397

    
398
    for(int i=buffer.mNumColors-2; i>=0; i--)
399
      {
400
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[i], 0);
401
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
402
      }
403
    }
404

    
405
///////////////////////////////////////////////////////////////////////////////////////////////////
406
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
407
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
408
// to a whole buffer (lastQueue.postprocess) and merge it (this.oitBuild).
409

    
410
  int renderChildren(long time, int numChildren, ArrayList<DistortedNode> children)
411
    {
412
    int quality=0, internalQuality = 0, numRenders = 0, bucketChange = 0;
413
    DistortedNode child1, child2;
414
    EffectQueuePostprocess lastQueue=null, currQueue;
415
    long lastBucket=0, currBucket=0;
416

    
417
    oitClear(this);
418

    
419
    for(int i=0; i<numChildren; i++)
420
      {
421
      child1 = children.get(i);
422
      currQueue = child1.getPostprocessQueue();
423
      currBucket= currQueue.getID();
424

    
425
      if( currBucket==0 )
426
        {
427
        GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mBufferOIT.mFBOH[0]);
428
        numRenders += child1.draw(time, mBufferOIT);
429

    
430
        //setAsOutput(time);
431
        //numRenders += child1.draw(time,this);
432
        }
433
      else
434
        {
435
        if( mBuffer[0]==null ) createPostprocessingBuffers(mWidth,mHeight,mNear);
436

    
437
        if( lastBucket!=currBucket )
438
          {
439
          if( lastBucket==0 )
440
            {
441
            clonePostprocessingViewport(this);
442
            }
443
          else
444
            {
445
            for(int j=bucketChange; j<i; j++)
446
              {
447
              child2 = children.get(j);
448
              numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],lastQueue);
449
              }
450

    
451
            numRenders += lastQueue.postprocess(mBuffer);
452
            numRenders += mBufferOIT.oitBuild(mBuffer[quality]);
453
            clearBuffer(mBuffer[quality]);
454
            }
455

    
456
          internalQuality = currQueue.getInternalQuality();
457
          quality         = currQueue.getQuality();
458
          bucketChange    = i;
459
          }
460

    
461
        mBuffer[quality].setAsOutput(time);
462
        child1.drawNoBlend(time,mBuffer[quality]);
463

    
464
        if( i==numChildren-1 )
465
          {
466
          for(int j=bucketChange; j<numChildren; j++)
467
            {
468
            child2 = children.get(j);
469
            numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],currQueue);
470
            }
471

    
472
          numRenders += currQueue.postprocess(mBuffer);
473
          numRenders += mBufferOIT.oitBuild(mBuffer[quality]);
474
          GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT);
475
          numRenders += oitRender(time,mBufferOIT);  // merge the OIT linked list
476
          clearBuffer(mBuffer[quality]);
477
          }
478
        } // end else (postprocessed child)
479

    
480
      lastQueue = currQueue;
481
      lastBucket= currBucket;
482
      } // end main for loop
483

    
484
    if( currBucket==0 ) // there was no postprocessing - we need to merge the main buffer
485
      {
486
      numRenders += oitRender(time,mBufferOIT);
487
      }
488

    
489
    return numRenders;
490
    }
491

    
492
///////////////////////////////////////////////////////////////////////////////////////////////////
493

    
494
  ArrayList<DistortedNode> getChildren()
495
    {
496
    return mChildren;
497
    }
498

    
499
///////////////////////////////////////////////////////////////////////////////////////////////////
500
/**
501
 * Not part of the Public API.
502
 *
503
 * @y.exclude
504
 */
505
  public float getWidthCorrection()
506
    {
507
    return (float)mWidth/mRealWidth;
508
    }
509

    
510
///////////////////////////////////////////////////////////////////////////////////////////////////
511
/**
512
 * Not part of the Public API.
513
 *
514
 * @y.exclude
515
 */
516
  public float getHeightCorrection()
517
    {
518
    return (float)mHeight/mRealHeight;
519
    }
520

    
521
///////////////////////////////////////////////////////////////////////////////////////////////////
522
// PUBLIC API
523
///////////////////////////////////////////////////////////////////////////////////////////////////
524
/**
525
 * Make the library show various debugging information.
526
 * <p>
527
 * Currently only DEBUG_FPS - show FPS in the upper-left corner of every Screen - is defined.
528
 *
529
 * @param bitmask 0, or a bitmask of DEBUG_** flags to enable (currently only DEBUG_FPS defined)
530
 */
531
  public void setDebug(int bitmask)
532
    {
533
    if( this instanceof DistortedScreen )
534
      mDebugLevel = bitmask;
535
    }
536

    
537
///////////////////////////////////////////////////////////////////////////////////////////////////
538

    
539
/**
540
 * Draws all the attached children to this OutputSurface.
541
 * <p>
542
 * Must be called from a thread holding OpenGL Context.
543
 *
544
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
545
 * @return Number of objects rendered.
546
 */
547
  public int render(long time)
548
    {
549
    if( mDebugLevel!=0 ) prepareDebug(time);
550

    
551
    // change tree topology (attach and detach children)
552
/*
553
    boolean changed1 =
554
*/
555
    DistortedMaster.toDo();
556
/*
557
    if( changed1 )
558
      {
559
      for(int i=0; i<mNumChildren; i++)
560
        {
561
        mChildren.get(i).debug(0);
562
        }
563

    
564
      DistortedNode.debugMap();
565
      }
566
*/
567
    // create and delete all underlying OpenGL resources
568
    // Watch out: FIRST change topology, only then deal
569
    // with OpenGL resources. That's because changing Tree
570
    // can result in additional Framebuffers that would need
571
    // to be created immediately, before the calls to drawRecursive()
572
/*
573
    boolean changed2 =
574
*/
575
    toDo();
576
/*
577
    if( changed2 )
578
      {
579
      DistortedObject.debugLists();
580
      }
581
*/
582
    // mark OpenGL state as unknown
583
    DistortedRenderState.reset();
584

    
585
    int numRenders=0;
586

    
587
    for(int i=0; i<mNumChildren; i++)
588
      {
589
      numRenders += mChildren.get(i).renderRecursive(time);
590
      }
591

    
592
    setAsOutput(time);
593
    numRenders += renderChildren(time,mNumChildren,mChildren);
594

    
595
    if( mDebugLevel != 0 ) renderDebug(time);
596

    
597
    return numRenders;
598
    }
599

    
600
///////////////////////////////////////////////////////////////////////////////////////////////////
601
/**
602
 * Bind this Surface as a Framebuffer we can render to.
603
 *
604
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
605
 *             out if this is the first time during present frame that this FBO is being set as output.
606
 *             If so, the library, in addition to binding the Surface for output, also clears the
607
 *             Surface's color and depth attachments.
608
 */
609
  public void setAsOutput(long time)
610
    {
611
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[0]);
612

    
613
    if( mTime!=time )
614
      {
615
      mTime = time;
616
      DistortedRenderState.colorDepthStencilOn();
617
      GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
618
      GLES31.glClearDepthf(mClearDepth);
619
      GLES31.glClearStencil(mClearStencil);
620
      GLES31.glClear(mClear);
621
      DistortedRenderState.colorDepthStencilRestore();
622
      }
623
    }
624

    
625
///////////////////////////////////////////////////////////////////////////////////////////////////
626
/**
627
 * Bind this Surface as a Framebuffer we can render to.
628
 * <p>
629
 * This version does not attempt to clear anything.
630
 */
631

    
632
  public void setAsOutput()
633
    {
634
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[0]);
635
    }
636

    
637
///////////////////////////////////////////////////////////////////////////////////////////////////
638
/**
639
 * Return the Near plane of the Projection included in the Surface.
640
 *
641
 * @return the Near plane.
642
 */
643
  public float getNear()
644
    {
645
    return mNear;
646
    }
647

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

    
672
///////////////////////////////////////////////////////////////////////////////////////////////////
673
/**
674
 * Set the (R,G,B,A) values of GLES31.glClearColor() to set up color with which to clear
675
 * this Surface at the beginning of each frame.
676
 *
677
 * @param r the Red component. Default: 0.0f
678
 * @param g the Green component. Default: 0.0f
679
 * @param b the Blue component. Default: 0.0f
680
 * @param a the Alpha component. Default: 0.0f
681
 */
682
  public void glClearColor(float r, float g, float b, float a)
683
    {
684
    mClearR = r;
685
    mClearG = g;
686
    mClearB = b;
687
    mClearA = a;
688
    }
689

    
690
///////////////////////////////////////////////////////////////////////////////////////////////////
691
/**
692
 * Uses glClearDepthf() to set up a value with which to clear
693
 * the Depth buffer of our Surface at the beginning of each frame.
694
 *
695
 * @param d the Depth. Default: 1.0f
696
 */
697
  public void glClearDepthf(float d)
698
    {
699
    mClearDepth = d;
700
    }
701

    
702
///////////////////////////////////////////////////////////////////////////////////////////////////
703
/**
704
 * Uses glClearStencil() to set up a value with which to clear the
705
 * Stencil buffer of our Surface at the beginning of each frame.
706
 *
707
 * @param s the Stencil. Default: 0
708
 */
709
  public void glClearStencil(int s)
710
    {
711
    mClearStencil = s;
712
    }
713

    
714
///////////////////////////////////////////////////////////////////////////////////////////////////
715
/**
716
 * Which buffers to Clear at the beginning of each frame?
717
 * <p>
718
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
719
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
720
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
721
 *
722
 * @param mask bitwise OR of BUFFER_BITs to clear.
723
 */
724
  public void glClear(int mask)
725
    {
726
    mClear = mask;
727
    }
728

    
729
///////////////////////////////////////////////////////////////////////////////////////////////////
730
/**
731
 * Create new Projection matrix.
732
 *
733
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
734
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
735
 * @param near Distance between the screen plane and the near plane.
736
 *             Valid vaules: 0<near<1. When near==0 (illegal!), the Near Plane is exactly at the tip of
737
 *             the pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
738
 */
739
  public void setProjection(float fov, float near)
740
    {
741
    if( fov < 180.0f && fov >=0.0f )
742
      {
743
      mFOV = fov;
744
      }
745

    
746
    if( near<   1.0f && near> 0.0f )
747
      {
748
      mNear= near;
749
      }
750
    else if( near<=0.0f )
751
      {
752
      mNear = 0.01f;
753
      }
754
    else if( near>=1.0f )
755
      {
756
      mNear=0.99f;
757
      }
758

    
759
    createProjection();
760
    }
761

    
762
///////////////////////////////////////////////////////////////////////////////////////////////////
763
/**
764
 * Resize the underlying Framebuffer.
765
 * <p>
766
 * This method can be safely called mid-render as it doesn't interfere with rendering.
767
 *
768
 * @param width The new width.
769
 * @param height The new height.
770
 */
771
  public void resize(int width, int height)
772
    {
773
    if( mWidth!=width || mHeight!=height )
774
      {
775
      mWidth = mRealWidth = width;
776
      mHeight= mRealHeight= height;
777

    
778
      createProjection();
779

    
780
      if( mColorCreated==CREATED )
781
        {
782
        markForCreation();
783
        recreate();
784
        }
785
      }
786
    }
787

    
788
///////////////////////////////////////////////////////////////////////////////////////////////////
789
/**
790
 * Return true if the Surface contains a DEPTH attachment.
791
 *
792
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
793
 */
794
  public boolean hasDepth()
795
    {
796
    return mDepthStencilCreated==CREATED;
797
    }
798

    
799
///////////////////////////////////////////////////////////////////////////////////////////////////
800
/**
801
 * Return true if the Surface contains a STENCIL attachment.
802
 *
803
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
804
 */
805
  public boolean hasStencil()
806
    {
807
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
808
    }
809

    
810
///////////////////////////////////////////////////////////////////////////////////////////////////
811
/**
812
 * Adds a new child to the last position in the list of our Surface's children.
813
 * <p>
814
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
815
 * DistortedMaster (by calling doWork())
816
 *
817
 * @param node The new Node to add.
818
 */
819
  public void attach(DistortedNode node)
820
    {
821
    mJobs.add(new Job(ATTACH,node));
822
    DistortedMaster.newSlave(this);
823
    }
824

    
825
///////////////////////////////////////////////////////////////////////////////////////////////////
826
/**
827
 * Adds a new child to the last position in the list of our Surface's children.
828
 * <p>
829
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
830
 * DistortedMaster (by calling doWork())
831
 *
832
 * @param surface InputSurface to initialize our child Node with.
833
 * @param effects DistortedEffects to initialize our child Node with.
834
 * @param mesh MeshObject to initialize our child Node with.
835
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
836
 */
837
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
838
    {
839
    DistortedNode node = new DistortedNode(surface,effects,mesh);
840
    mJobs.add(new Job(ATTACH,node));
841
    DistortedMaster.newSlave(this);
842
    return node;
843
    }
844

    
845
///////////////////////////////////////////////////////////////////////////////////////////////////
846
/**
847
 * Removes the first occurrence of a specified child from the list of children of our Surface.
848
 * <p>
849
 * A bit questionable method as there can be many different Nodes attached as children, some
850
 * of them having the same Effects but - for instance - different Mesh. Use with care.
851
 * <p>
852
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
853
 * DistortedMaster (by calling doWork())
854
 *
855
 * @param effects DistortedEffects to remove.
856
 */
857
  public void detach(DistortedEffects effects)
858
    {
859
    long id = effects.getID();
860
    DistortedNode node;
861
    boolean detached = false;
862

    
863
    for(int i=0; i<mNumChildren; i++)
864
      {
865
      node = mChildren.get(i);
866

    
867
      if( node.getEffects().getID()==id )
868
        {
869
        detached = true;
870
        mJobs.add(new Job(DETACH,node));
871
        DistortedMaster.newSlave(this);
872
        break;
873
        }
874
      }
875

    
876
    if( !detached )
877
      {
878
      // if we failed to detach any, it still might be the case that
879
      // there's an ATTACH job that we need to cancel.
880
      int num = mJobs.size();
881
      Job job;
882

    
883
      for(int i=0; i<num; i++)
884
        {
885
        job = mJobs.get(i);
886

    
887
        if( job.type==ATTACH && job.node.getEffects()==effects )
888
          {
889
          mJobs.remove(i);
890
          break;
891
          }
892
        }
893
      }
894
    }
895

    
896
///////////////////////////////////////////////////////////////////////////////////////////////////
897
/**
898
 * Removes the first occurrence of a specified child from the list of children of our Surface.
899
 * <p>
900
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
901
 * DistortedMaster (by calling doWork())
902
 *
903
 * @param node The Node to remove.
904
 */
905
  public void detach(DistortedNode node)
906
    {
907
    mJobs.add(new Job(DETACH,node));
908
    DistortedMaster.newSlave(this);
909
    }
910

    
911
///////////////////////////////////////////////////////////////////////////////////////////////////
912
/**
913
 * Removes all children Nodes.
914
 * <p>
915
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
916
 * DistortedMaster (by calling doWork())
917
 */
918
  public void detachAll()
919
    {
920
    mJobs.add(new Job(DETALL,null));
921
    DistortedMaster.newSlave(this);
922
    }
923

    
924
///////////////////////////////////////////////////////////////////////////////////////////////////
925
/**
926
 * This is not really part of the public API. Has to be public only because it is a part of the
927
 * DistortedSlave interface, which should really be a class that we extend here instead but
928
 * Java has no multiple inheritance.
929
 *
930
 * @y.exclude
931
 */
932
  public void doWork()
933
    {
934
    int num = mJobs.size();
935
    Job job;
936

    
937
    for(int i=0; i<num; i++)
938
      {
939
      job = mJobs.remove(0);
940

    
941
      switch(job.type)
942
        {
943
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
944
                     job.node.setSurfaceParent(this);
945
                     DistortedMaster.addSorted(mChildren,job.node);
946
                     mNumChildren++;
947
                     break;
948
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
949
                       {
950
                       job.node.setSurfaceParent(null);
951
                       mNumChildren--;
952
                       }
953
                     break;
954
        case DETALL: if( mNumChildren>0 )
955
                       {
956
                       DistortedNode tmp;
957

    
958
                       for(int j=mNumChildren-1; j>=0; j--)
959
                         {
960
                         tmp = mChildren.remove(j);
961
                         tmp.setSurfaceParent(null);
962
                         }
963

    
964
                       mNumChildren = 0;
965
                       }
966
                     break;
967
        case SORT  : mChildren.remove(job.node);
968
                     DistortedMaster.addSorted(mChildren,job.node);
969
                     break;
970
        }
971
      }
972
    }
973
}
(8-8/21)