Project

General

Profile

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

library / src / main / java / org / distorted / library / main / InternalOutputSurface.java @ 5f35f1cb

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.GLES30;
23
import android.opengl.GLES31;
24
import android.opengl.Matrix;
25

    
26
import org.distorted.library.effect.EffectQuality;
27
import org.distorted.library.effectqueue.EffectQueuePostprocess;
28
import org.distorted.library.mesh.MeshBase;
29

    
30
///////////////////////////////////////////////////////////////////////////////////////////////////
31
/**
32
 * This is not really part of the public API.
33
 *
34
 * @y.exclude
35
 */
36
public abstract class InternalOutputSurface extends InternalSurface implements InternalChildrenList.Parent
37
{
38
  public static final int NO_DEPTH_NO_STENCIL = 0;
39
  public static final int DEPTH_NO_STENCIL    = 1;
40
  public static final int BOTH_DEPTH_STENCIL  = 2;
41

    
42
  static final float DEFAULT_FOV = 60.0f;
43
  static final float DEFAULT_NEAR=  0.1f;
44

    
45
  private float mFOV;
46
  private int mTmpFBO;
47

    
48
  private long[] mTime;
49
  private float mClearR, mClearG, mClearB, mClearA, mClearDepth;
50
  private int mClear, mClearStencil;
51
  private boolean mRenderWayOIT;
52
  private InternalChildrenList mChildren;
53

    
54
  // Global buffers used for postprocessing
55
  private static DistortedFramebuffer[] mBuffer= new DistortedFramebuffer[EffectQuality.LENGTH];
56

    
57
  float mDistance, mNear, mMipmap;
58
  float[] mProjectionMatrix;
59
  int mDepthStencilCreated, mDepthStencil;
60
  int[] mDepthStencilH, mFBOH;
61
  int mRealWidth;   // the Surface can be backed up by a texture larger than the viewport we have to it.
62
  int mRealHeight;  // mWidth,mHeight are the sizes of the Viewport, those - sizes of the backing up texture.
63
  int mCurrFBO;     // internal current FBO (see DistortedLibrary.FBO_QUEUE_SIZE)
64
  int mWidth, mHeight;
65

    
66
///////////////////////////////////////////////////////////////////////////////////////////////////
67

    
68
  InternalOutputSurface(int width, int height, int createColor, int numfbos, int numcolors, int depthStencil, int fbo, int type)
69
    {
70
    super(createColor,numfbos,numcolors,type);
71

    
72
    mRenderWayOIT = false;
73
    mCurrFBO      = 0;
74

    
75
    mRealWidth = mWidth = width;
76
    mRealHeight= mHeight= height;
77

    
78
    mProjectionMatrix = new float[16];
79

    
80
    mFOV = DEFAULT_FOV;
81
    mNear= DEFAULT_NEAR;
82

    
83
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
84
    mDepthStencil = depthStencil;
85

    
86
    mClearR = 0.0f;
87
    mClearG = 0.0f;
88
    mClearB = 0.0f;
89
    mClearA = 0.0f;
90

    
91
    mClearDepth = 1.0f;
92
    mClearStencil = 0;
93
    mClear = GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT;
94

    
95
    mMipmap = 1.0f;
96

    
97
    mChildren = new InternalChildrenList(this);
98

    
99
    mTmpFBO = fbo;
100

    
101
    allocateStuffDependantOnNumFBOS();
102
    createProjection();
103
    }
104

    
105
///////////////////////////////////////////////////////////////////////////////////////////////////
106

    
107
  void allocateStuffDependantOnNumFBOS()
108
    {
109
    if( mNumFBOs>0 )
110
      {
111
      mDepthStencilH   = new int[mNumFBOs];
112
      mDepthStencilH[0]= 0;
113

    
114
      mFBOH   = new int[mNumFBOs];
115
      mFBOH[0]= mTmpFBO;
116

    
117
      mTime = new long[mNumFBOs];
118
      for(int i=0; i<mNumFBOs;i++) mTime[i]=0;
119
      }
120
    }
121

    
122
///////////////////////////////////////////////////////////////////////////////////////////////////
123

    
124
  private void createProjection()
125
    {
126
    if( mWidth>0 && mHeight>1 )
127
      {
128
      if( mFOV>0.0f )  // perspective projection
129
        {
130
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
131
        float q = mWidth*mNear;
132
        float c = mHeight*mNear;
133

    
134
        float left   = -q/2;
135
        float right  = +q/2;
136
        float bottom = -c/2;
137
        float top    = +c/2;
138
        float near   =  c/a;
139

    
140
        mDistance    = mHeight/a;
141
        float far    = 2*mDistance-near;
142

    
143
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
144
        }
145
      else             // parallel projection
146
        {
147
        float left   = -mWidth/2.0f;
148
        float right  = +mWidth/2.0f;
149
        float bottom = -mHeight/2.0f;
150
        float top    = +mHeight/2.0f;
151
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
152
        mDistance    = mWidth+mHeight;
153
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
154

    
155
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
156
        }
157
      }
158
    }
159

    
160
///////////////////////////////////////////////////////////////////////////////////////////////////
161

    
162
  private static void createPostprocessingBuffers(int quality, int width, int height, float near)
163
    {
164
    final float CLEAR_R = 1.0f;
165
    final float CLEAR_G = 1.0f;
166
    final float CLEAR_B = 1.0f;
167
    final float CLEAR_A = 0.0f;
168
    final float CLEAR_D = 1.0f;
169
    final int   CLEAR_S = 0;
170

    
171
    final int queueSize = DistortedLibrary.getQueueSize();
172
    float mipmap=1.0f;
173

    
174
    for (int j=0; j<quality; j++) mipmap *= EffectQuality.MULTIPLIER;
175

    
176
    mBuffer[quality] = new DistortedFramebuffer(queueSize,2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(width*mipmap), (int)(height*mipmap) );
177
    mBuffer[quality].mMipmap = mipmap;
178
    mBuffer[quality].mNear = near;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
179
    mBuffer[quality].glClearColor(CLEAR_R, CLEAR_G, CLEAR_B, CLEAR_A);
180

    
181
    InternalObject.toDo(); // create the FBOs immediately. This is safe as we must be holding the OpenGL context now.
182

    
183
    InternalRenderState.colorDepthStencilOn();
184
    GLES30.glClearColor(CLEAR_R, CLEAR_G, CLEAR_B, CLEAR_A);
185
    GLES30.glClearDepthf(CLEAR_D);
186
    GLES30.glClearStencil(CLEAR_S);
187

    
188
    for(int k=0; k<queueSize; k++)
189
      {
190
      GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mBuffer[quality].mFBOH[k]);
191
      GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mBuffer[quality].mColorH[2*k+1], 0);
192
      GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT | GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_STENCIL_BUFFER_BIT);
193
      GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mBuffer[quality].mColorH[2*k  ], 0);
194
      GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
195
      }
196

    
197
    InternalRenderState.colorDepthStencilRestore();
198

    
199
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0);
200
    }
201

    
202
///////////////////////////////////////////////////////////////////////////////////////////////////
203

    
204
  static synchronized void onDestroy()
205
    {
206
    for (int j=0; j<EffectQuality.LENGTH; j++)
207
      if( mBuffer[j]!=null )
208
        {
209
        mBuffer[j].markForDeletion();
210
        mBuffer[j] = null;
211
        }
212
    }
213

    
214
///////////////////////////////////////////////////////////////////////////////////////////////////
215
// The postprocessing buffers mBuffer[] are generally speaking too large (there's just one static
216
// set of them) so before we use them for output, we need to adjust the Viewport as if they were
217
// smaller. That takes care of outputting pixels to them. When we use them as input, we have to
218
// adjust the texture coords - see the get{Width|Height}Correction functions.
219
//
220
// Also, adjust the Buffers so their Projection is the same like the surface we are supposed to be
221
// rendering to.
222

    
223
  private static void clonePostprocessingViewportAndProjection(InternalOutputSurface surface, InternalOutputSurface from)
224
    {
225
    if( surface.mWidth != from.mWidth || surface.mHeight != from.mHeight ||
226
        surface.mFOV   != from.mFOV   || surface.mNear   != from.mNear    )
227
      {
228
      surface.mWidth  = (int)(from.mWidth *surface.mMipmap);
229
      surface.mHeight = (int)(from.mHeight*surface.mMipmap);
230
      surface.mFOV    = from.mFOV;
231
      surface.mNear   = from.mNear;  // Near plane is independent of the mipmap level
232

    
233
      surface.createProjection();
234

    
235
      int maxw = Math.max(surface.mWidth , surface.mRealWidth );
236
      int maxh = Math.max(surface.mHeight, surface.mRealHeight);
237

    
238
      if (maxw > surface.mRealWidth || maxh > surface.mRealHeight)
239
        {
240
        surface.mRealWidth = maxw;
241
        surface.mRealHeight = maxh;
242

    
243
        surface.recreate();
244
        surface.create();
245
        }
246
      }
247
    }
248

    
249
///////////////////////////////////////////////////////////////////////////////////////////////////
250

    
251
  private int blitWithDepth(long currTime, InternalOutputSurface buffer, int fbo)
252
    {
253
    GLES30.glViewport(0, 0, mWidth, mHeight);
254
    setAsOutput(currTime);
255
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
256
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
257
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
258
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
259

    
260
    GLES30.glDisable(GLES30.GL_STENCIL_TEST);
261
    GLES30.glStencilMask(0x00);
262

    
263
    DistortedLibrary.blitDepthPriv(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
264
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
265
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
266
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
267
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
268

    
269
    // clear buffers
270
    GLES30.glStencilMask(0xff);
271
    GLES30.glDepthMask(true);
272
    GLES30.glColorMask(true,true,true,true);
273
    GLES30.glClearColor(buffer.mClearR,buffer.mClearG,buffer.mClearB,buffer.mClearA);
274
    GLES30.glClearDepthf(buffer.mClearDepth);
275
    GLES30.glClearStencil(buffer.mClearStencil);
276

    
277
    buffer.setAsOutput();
278
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[2*fbo+1], 0);
279
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
280
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[2*fbo  ], 0);
281
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
282

    
283
    return 1;
284
    }
285

    
286
///////////////////////////////////////////////////////////////////////////////////////////////////
287

    
288
  private static void oitClear(InternalOutputSurface buffer)
289
    {
290
    int counter = DistortedLibrary.zeroOutAtomic();
291
    DistortedLibrary.oitClear(buffer,counter);
292
    GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT|GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
293
    }
294

    
295
///////////////////////////////////////////////////////////////////////////////////////////////////
296

    
297
  private int oitBuild(long time, InternalOutputSurface buffer, int fbo)
298
    {
299
    GLES30.glViewport(0, 0, mWidth, mHeight);
300
    setAsOutput(time);
301
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
302
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
303
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
304
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
305

    
306
    InternalRenderState.colorDepthStencilOn();
307
    InternalRenderState.enableDepthTest();
308

    
309
    DistortedLibrary.oitBuild(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
310
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
311
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
312
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
313
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
314

    
315
    InternalRenderState.colorDepthStencilRestore();
316
    InternalRenderState.restoreDepthTest();
317

    
318
    return 1;
319
    }
320

    
321
///////////////////////////////////////////////////////////////////////////////////////////////////
322
// two phases: 1. collapse the SSBO 2. blend the ssbo's color
323

    
324
  private int oitRender(long currTime, int fbo)
325
    {
326
    float corrW = getWidthCorrection();
327
    float corrH = getHeightCorrection();
328

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

    
332
    if( mDepthStencilH[fbo] != 0 )
333
      {
334
      GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0);
335
      GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
336
      GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, mDepthStencilH[fbo]);
337
      InternalRenderState.switchOffColorDepthStencil();
338
      DistortedLibrary.oitCollapse(this, corrW, corrH);
339
      GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
340
      }
341

    
342
    setAsOutput(currTime);
343
    InternalRenderState.switchColorDepthOnStencilOff();
344
    DistortedLibrary.oitRender(this, corrW, corrH);
345
    InternalRenderState.restoreColorDepthStencil();
346

    
347
    return 1;
348
    }
349

    
350
///////////////////////////////////////////////////////////////////////////////////////////////////
351

    
352
  private void clear()
353
    {
354
    InternalRenderState.colorDepthStencilOn();
355
    GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
356
    GLES30.glClearDepthf(mClearDepth);
357
    GLES30.glClearStencil(mClearStencil);
358
    GLES30.glClear(mClear);
359
    InternalRenderState.colorDepthStencilRestore();
360
    }
361

    
362
///////////////////////////////////////////////////////////////////////////////////////////////////
363

    
364
  void setCurrFBO(int fbo)
365
    {
366
    mCurrFBO = fbo;
367
    }
368

    
369
///////////////////////////////////////////////////////////////////////////////////////////////////
370
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
371
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
372
// to a whole buffer (lastQueue.postprocess) and merge it (this.oitBuild or blitWithDepth - depending
373
// on the type of rendering)
374

    
375
  int renderChildren(long time, int numChildren, InternalChildrenList children, int fbo, boolean oit)
376
    {
377
    int numRenders=0, bucketChange=0;
378
    DistortedNode child;
379
    DistortedFramebuffer buffer=null;
380
    EffectQueuePostprocess lastQueue=null, currQueue;
381
    long lastBucket=0, currBucket;
382
    boolean renderDirectly=false;
383

    
384
    setCurrFBO(fbo);
385
    if( numChildren==0 ) setAsOutput(time);
386

    
387
    if( oit && numChildren>0 )
388
      {
389
      oitClear(this);
390
      }
391

    
392
    for(int i=0; i<numChildren; i++)
393
      {
394
      child = children.getChild(i);
395
      currQueue = (EffectQueuePostprocess)child.getEffects().getQueues()[3];
396
      currBucket= currQueue.getID();
397

    
398
      if( currBucket==0 )
399
        {
400
        setAsOutput(time);
401

    
402
        if( oit )
403
          {
404
          numRenders += child.drawOIT(time, this);
405
          GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
406
          }
407
        else
408
          {
409
          numRenders += child.draw(time, this);
410
          }
411
        }
412
      else
413
        {
414
        int currQuality = currQueue.getQuality();
415

    
416
        if( mBuffer[currQuality]==null ) createPostprocessingBuffers(currQuality, mWidth, mHeight, mNear);
417
        mBuffer[currQuality].setCurrFBO(fbo);
418

    
419
        if( lastBucket!=currBucket )
420
          {
421
          if( lastBucket==0 )
422
            {
423
            clonePostprocessingViewportAndProjection(mBuffer[currQuality],this);
424
            }
425
          else
426
            {
427
            for(int j=bucketChange; j<i; j++)
428
              {
429
              DistortedNode node = children.getChild(j);
430

    
431
              if( node.getSurface().setAsInput() )
432
                {
433
                buffer.setAsOutput();
434
                numRenders += lastQueue.preprocess( buffer, node, buffer.mDistance, buffer.mMipmap, buffer.mProjectionMatrix );
435
                }
436
              }
437
            numRenders += lastQueue.postprocess(buffer);
438

    
439
            if( oit )
440
              {
441
              numRenders += oitBuild(time, buffer, fbo);
442
              GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
443
              }
444
            else
445
              {
446
              numRenders += blitWithDepth(time, buffer, fbo);
447
              }
448
            buffer.clearBuffer(fbo);
449
            }
450

    
451
          buffer= mBuffer[currQuality];
452
          bucketChange= i;
453
          renderDirectly = currQueue.getRender();
454
          }
455

    
456
        if( renderDirectly )
457
          {
458
          setAsOutput(time);
459

    
460
          if( oit )
461
            {
462
            numRenders += child.drawOIT(time, this);
463
            GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
464
            }
465
          else
466
            {
467
            numRenders += child.draw(time, this);
468
            }
469
          }
470
        else
471
          {
472
          buffer.setAsOutput(time);
473
          child.drawNoBlend(time, buffer);
474
          }
475

    
476
        if( i==numChildren-1 )
477
          {
478
          for(int j=bucketChange; j<numChildren; j++)
479
            {
480
            DistortedNode node = children.getChild(j);
481

    
482
            if( node.getSurface().setAsInput() )
483
              {
484
              buffer.setAsOutput();
485
              numRenders += currQueue.preprocess( buffer, node, buffer.mDistance, buffer.mMipmap, buffer.mProjectionMatrix );
486
              }
487
            }
488
          numRenders += currQueue.postprocess(buffer);
489

    
490
          if( oit )
491
            {
492
            numRenders += oitBuild(time, buffer, fbo);
493
            GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
494
            buffer.clearBuffer(fbo);
495
            }
496
          else
497
            {
498
            numRenders += blitWithDepth(time, buffer,fbo);
499
            }
500
          }
501
        } // end else (postprocessed child)
502

    
503
      lastQueue = currQueue;
504
      lastBucket= currBucket;
505
      } // end main for loop
506

    
507
    if( oit && numChildren>0 )
508
      {
509
      numRenders += oitRender(time, fbo);  // merge the OIT linked list
510
      }
511

    
512
    return numRenders;
513
    }
514

    
515
///////////////////////////////////////////////////////////////////////////////////////////////////
516
/**
517
 * Not part of the public API.
518
 *
519
 * @y.exclude
520
 */
521
  public void adjustIsomorphism() { }
522

    
523
///////////////////////////////////////////////////////////////////////////////////////////////////
524
/**
525
 * Not part of the Public API.
526
 *
527
 * @y.exclude
528
 */
529
  public float getWidthCorrection()
530
    {
531
    return (float)mWidth/mRealWidth;
532
    }
533

    
534
///////////////////////////////////////////////////////////////////////////////////////////////////
535
/**
536
 * Not part of the Public API.
537
 *
538
 * @y.exclude
539
 */
540
  public float getHeightCorrection()
541
    {
542
    return (float)mHeight/mRealHeight;
543
    }
544

    
545
///////////////////////////////////////////////////////////////////////////////////////////////////
546

    
547
  void clearBuffer(int fbo)
548
    {
549
    InternalRenderState.colorDepthStencilOn();
550

    
551
    GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
552
    GLES30.glClearDepthf(mClearDepth);
553
    GLES30.glClearStencil(mClearStencil);
554

    
555
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[fbo]);
556
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mColorH[2*fbo+1], 0);
557
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
558
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mColorH[2*fbo  ], 0);
559
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
560

    
561
    InternalRenderState.colorDepthStencilRestore();
562
    }
563

    
564
///////////////////////////////////////////////////////////////////////////////////////////////////
565

    
566
  void setAsOutput(long time)
567
    {
568
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
569

    
570
    if( mTime[mCurrFBO]!=time )
571
      {
572
      mTime[mCurrFBO] = time;
573
      clear();
574
      }
575
    }
576

    
577
///////////////////////////////////////////////////////////////////////////////////////////////////
578
// PUBLIC API
579
///////////////////////////////////////////////////////////////////////////////////////////////////
580
/**
581
 * Draws all the attached children to this OutputSurface's 0th FBO.
582
 * <p>
583
 * Must be called from a thread holding OpenGL Context.
584
 *
585
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
586
 * @return Number of objects rendered.
587
 */
588
  public int render(long time)
589
    {
590
    return render(time,0);
591
    }
592

    
593
///////////////////////////////////////////////////////////////////////////////////////////////////
594
/**
595
 * Draws all the attached children to this OutputSurface.
596
 * <p>
597
 * Must be called from a thread holding OpenGL Context.
598
 *
599
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
600
 * @param fbo The surface can have many FBOs backing it up - render this to FBO number 'fbo'.
601
 * @return Number of objects rendered.
602
 */
603
  public int render(long time, int fbo)
604
    {
605
    InternalMaster.toDo();
606
    toDo();
607
    InternalRenderState.reset();
608

    
609
    int numRenders=0, numChildren = mChildren.getNumChildren();
610
    DistortedNode node;
611
    long oldBucket=0, newBucket;
612

    
613
    for(int i=0; i<numChildren; i++)
614
      {
615
      node = mChildren.getChild(i);
616
      newBucket = node.getBucket();
617
      numRenders += node.renderRecursive(time);
618
      if( newBucket<oldBucket ) mChildren.rearrangeByBuckets(i,newBucket);
619
      else oldBucket=newBucket;
620
      }
621

    
622
    numRenders += renderChildren(time,numChildren,mChildren,fbo, mRenderWayOIT);
623

    
624
    return numRenders;
625
    }
626

    
627
///////////////////////////////////////////////////////////////////////////////////////////////////
628
/**
629
 * Bind this Surface as a Framebuffer we can render to.
630
 * <p>
631
 * This version does not attempt to clear anything.
632
 */
633
  public void setAsOutput()
634
    {
635
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
636
    }
637

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

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

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

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

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

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

    
730
///////////////////////////////////////////////////////////////////////////////////////////////////
731
/**
732
 * Create new Projection matrix.
733
 *
734
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
735
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
736
 * @param near The Near plane.
737
 */
738
  public void setProjection(float fov, float near)
739
    {
740
    if( fov < 180.0f && fov >=0.0f )
741
      {
742
      mFOV = fov;
743
      }
744

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

    
758
    for(int j=0; j<EffectQuality.LENGTH; j++)
759
      {
760
      if( mBuffer[j]!=null ) mBuffer[j].mNear = mNear;
761
      }
762

    
763
    createProjection();
764
    }
765

    
766
///////////////////////////////////////////////////////////////////////////////////////////////////
767
/**
768
 * Return the vertical field of view angle.
769
 *
770
 * @return Vertival Field of View Angle, in degrees.
771
 */
772
  public float getFOV()
773
    {
774
    return mFOV;
775
    }
776

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

    
793
      createProjection();
794

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

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

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

    
825
///////////////////////////////////////////////////////////////////////////////////////////////////
826
/**
827
 * When rendering this Node, should we use the Order Independent Transparency render mode?
828
 * <p>
829
 * This feature requires OpenGL ES 3.1. If we are running on OpenGL 3.0, this will do nothing.
830
 * Also, if you are running on a buggy driver ( Imagination GE8100/8300 driver build 1.8@4490469 )
831
 * then do nothing.
832
 *
833
 * There are two modes of rendering: the fast 'normal' way, which however renders transparent
834
 * fragments in different ways depending on which fragments get rendered first, or the slower
835
 * 'oit' way, which renders transparent fragments correctly regardless of their order.
836
 *
837
 * @param oit True if we want to render more slowly, but in a way which accounts for transparency.
838
 */
839
  public void setOrderIndependentTransparency(boolean oit)
840
    {
841
    if( DistortedLibrary.getGLSL()>=310 && DistortedLibrary.OITCompilationSuccessful() )
842
      {
843
      mRenderWayOIT = oit;
844
      }
845
    }
846

    
847
///////////////////////////////////////////////////////////////////////////////////////////////////
848
/**
849
 * When rendering this Node, should we use the Order Independent Transparency render mode?
850
 * <p>
851
 * This feature requires OpenGL ES 3.1. If we are running on OpenGL 3.0, this will do nothing.
852
 * Also, if you are running on a buggy driver ( Imagination GE8100/8300 driver build 1.8@4490469 )
853
 * then do nothing.
854
 *
855
 * There are two modes of rendering: the fast 'normal' way, which however renders transparent
856
 * fragments in different ways depending on which fragments get rendered first, or the slower
857
 * 'oit' way, which renders transparent fragments correctly regardless of their order.
858
 *
859
 * @param oit True if we want to render more slowly, but in a way which accounts for transparency.
860
 * @param initialSize Initial number of transparent fragments we expect, in screenfuls.
861
 *                    I.e '1.0' means 'the scene we are going to render contains dialog_about 1 screen
862
 *                    worth of transparent fragments'. Valid values: 0.0 &lt; initialSize &lt; 10.0
863
 *                    Even if you get this wrong, the library will detect that there are more
864
 *                    transparent fragments than it has space for and readjust its internal buffers,
865
 *                    but only after a few frames during which one will probably see missing objects.
866
 */
867
  public void setOrderIndependentTransparency(boolean oit, float initialSize)
868
    {
869
    if( DistortedLibrary.getGLSL()>=310 && DistortedLibrary.OITCompilationSuccessful() )
870
      {
871
      mRenderWayOIT = oit;
872

    
873
      if( initialSize>0.0f && initialSize<10.0f )
874
        {
875
        DistortedLibrary.setSSBOSize(initialSize);
876
        }
877
      }
878
    }
879

    
880
///////////////////////////////////////////////////////////////////////////////////////////////////
881
/**
882
 * Adds a new child to the last position in the list of our Surface's children.
883
 * <p>
884
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
885
 * InternalMaster (by calling doWork())
886
 *
887
 * @param node The new Node to add.
888
 */
889
  public void attach(DistortedNode node)
890
    {
891
    mChildren.attach(node);
892
    }
893

    
894
///////////////////////////////////////////////////////////////////////////////////////////////////
895
/**
896
 * Adds a new child to the last position in the list of our Surface's children.
897
 * <p>
898
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
899
 * InternalMaster (by calling doWork())
900
 *
901
 * @param surface InputSurface to initialize our child Node with.
902
 * @param effects DistortedEffects to initialize our child Node with.
903
 * @param mesh MeshBase to initialize our child Node with.
904
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
905
 */
906
  public DistortedNode attach(InternalSurface surface, DistortedEffects effects, MeshBase mesh)
907
    {
908
    return mChildren.attach(surface,effects,mesh);
909
    }
910

    
911
///////////////////////////////////////////////////////////////////////////////////////////////////
912
/**
913
 * Removes the first occurrence of a specified child from the list of children of our Surface.
914
 * <p>
915
 * A bit questionable method as there can be many different Nodes attached as children, some
916
 * of them having the same Effects but - for instance - different Mesh. Use with care.
917
 * <p>
918
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
919
 * InternalMaster (by calling doWork())
920
 *
921
 * @param effects DistortedEffects to remove.
922
 */
923
  public void detach(DistortedEffects effects)
924
    {
925
    mChildren.detach(effects);
926
    }
927

    
928
///////////////////////////////////////////////////////////////////////////////////////////////////
929
/**
930
 * Removes the first occurrence of a specified child from the list of children of our Surface.
931
 * <p>
932
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
933
 * InternalMaster (by calling doWork())
934
 *
935
 * @param node The Node to remove.
936
 */
937
  public void detach(DistortedNode node)
938
    {
939
    mChildren.detach(node);
940
    }
941

    
942
///////////////////////////////////////////////////////////////////////////////////////////////////
943
/**
944
 * Removes all children Nodes.
945
 * <p>
946
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
947
 * InternalMaster (by calling doWork())
948
 */
949
  public void detachAll()
950
    {
951
    mChildren.detachAll();
952
    }
953

    
954
///////////////////////////////////////////////////////////////////////////////////////////////////
955
/**
956
 * Return the width of this Surface.
957
 *
958
 * @return width of the Object, in pixels.
959
 */
960
  public int getWidth()
961
    {
962
    return mWidth;
963
    }
964

    
965
///////////////////////////////////////////////////////////////////////////////////////////////////
966
/**
967
 * Return the height of this Surface.
968
 *
969
 * @return height of the Object, in pixels.
970
 */
971
  public int getHeight()
972
    {
973
    return mHeight;
974
    }
975
}
(12-12/14)