Project

General

Profile

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

library / src / main / java / org / distorted / library / main / InternalOutputSurface.java @ 4bb94a7d

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
import org.distorted.library.effectqueue.EffectQueuePostprocess;
27
import org.distorted.library.mesh.MeshBase;
28

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

    
41
  float mFOV, mDistance, mNear, mMipmap;
42
  float[] mProjectionMatrix;
43
  int mDepthStencilCreated, mDepthStencil;
44
  int[] mDepthStencilH, mFBOH;
45
  int mRealWidth;   // the Surface can be backed up by a texture larger than the viewport we have to it.
46
  int mRealHeight;  // mWidth,mHeight are the sizes of the Viewport, those - sizes of the backing up texture.
47
  int mCurrFBO;     // internal current FBO (see DistortedLibrary.FBO_QUEUE_SIZE)
48

    
49
  private static DistortedFramebuffer[] mBuffer=null; // Global buffers used for postprocessing.
50
  private long[] mTime;
51
  private float mClearR, mClearG, mClearB, mClearA, mClearDepth;
52
  private int mClear, mClearStencil;
53
  private boolean mRenderWayOIT;
54
  private InternalChildrenList mChildren;
55

    
56
///////////////////////////////////////////////////////////////////////////////////////////////////
57

    
58
  InternalOutputSurface(int width, int height, int createColor, int numfbos, int numcolors, int depthStencil, int fbo, int type)
59
    {
60
    super(width,height,createColor,numfbos,numcolors,type);
61

    
62
    mRenderWayOIT = false;
63
    mCurrFBO      = 0;
64

    
65
    mDepthStencilH = new int[numfbos];
66
    mFBOH          = new int[numfbos];
67

    
68
    mTime = new long[numfbos];
69
    for(int i=0; i<mNumFBOs;i++) mTime[i]=0;
70

    
71
    mRealWidth = width;
72
    mRealHeight= height;
73

    
74
    mProjectionMatrix = new float[16];
75

    
76
    mFOV = 60.0f;
77
    mNear=  0.5f;
78

    
79
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
80
    mDepthStencil = depthStencil;
81

    
82
    mFBOH[0]         = fbo;
83
    mDepthStencilH[0]= 0;
84

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

    
90
    mClearDepth = 1.0f;
91
    mClearStencil = 0;
92
    mClear = GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_COLOR_BUFFER_BIT;
93

    
94
    mMipmap = 1.0f;
95

    
96
    mChildren = new InternalChildrenList(this);
97

    
98
    createProjection();
99
    }
100

    
101
///////////////////////////////////////////////////////////////////////////////////////////////////
102

    
103
  private void createProjection()
104
    {
105
    if( mWidth>0 && mHeight>1 )
106
      {
107
      if( mFOV>0.0f )  // perspective projection
108
        {
109
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
110
        float q = mWidth*mNear;
111
        float c = mHeight*mNear;
112

    
113
        float left   = -q/2;
114
        float right  = +q/2;
115
        float bottom = -c/2;
116
        float top    = +c/2;
117
        float near   =  c/a;
118

    
119
        mDistance    = mHeight/a;
120
        float far    = 2*mDistance-near;
121

    
122
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
123
        }
124
      else             // parallel projection
125
        {
126
        float left   = -mWidth/2.0f;
127
        float right  = +mWidth/2.0f;
128
        float bottom = -mHeight/2.0f;
129
        float top    = +mHeight/2.0f;
130
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
131
        mDistance    = mWidth+mHeight;
132
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
133

    
134
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
135
        }
136
      }
137
    }
138

    
139
///////////////////////////////////////////////////////////////////////////////////////////////////
140

    
141
  private static void createPostprocessingBuffers(int width, int height, float near)
142
    {
143
    final float CLEAR_R = 1.0f;
144
    final float CLEAR_G = 1.0f;
145
    final float CLEAR_B = 1.0f;
146
    final float CLEAR_A = 0.0f;
147
    final float CLEAR_D = 1.0f;
148
    final int   CLEAR_S = 0;
149

    
150
    mBuffer = new DistortedFramebuffer[EffectQuality.LENGTH];
151
    float mipmap=1.0f;
152

    
153
    for (int j=0; j<EffectQuality.LENGTH; j++)
154
      {
155
      mBuffer[j] = new DistortedFramebuffer(DistortedLibrary.FBO_QUEUE_SIZE,2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(width*mipmap), (int)(height*mipmap) );
156
      mBuffer[j].mMipmap = mipmap;
157
      mBuffer[j].mNear = near;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
158
      mBuffer[j].glClearColor(CLEAR_R, CLEAR_G, CLEAR_B, CLEAR_A);
159

    
160
      mipmap *= EffectQuality.MULTIPLIER;
161
      }
162

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

    
165
    InternalRenderState.colorDepthStencilOn();
166
    GLES31.glClearColor(CLEAR_R, CLEAR_G, CLEAR_B, CLEAR_A);
167
    GLES31.glClearDepthf(CLEAR_D);
168
    GLES31.glClearStencil(CLEAR_S);
169

    
170
    for (int j=0; j<EffectQuality.LENGTH; j++)
171
      {
172
      for(int k = 0; k< DistortedLibrary.FBO_QUEUE_SIZE; k++)
173
        {
174
        GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mBuffer[j].mFBOH[k]);
175
        GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[2*k+1], 0);
176
        GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT | GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_STENCIL_BUFFER_BIT);
177
        GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[2*k  ], 0);
178
        GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
179
        }
180
      }
181

    
182
    InternalRenderState.colorDepthStencilRestore();
183

    
184
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, 0);
185
    }
186

    
187
///////////////////////////////////////////////////////////////////////////////////////////////////
188

    
189
  static synchronized void onDestroy()
190
    {
191
    if( mBuffer!=null )
192
      {
193
      for (int j = 0; j < EffectQuality.LENGTH; j++)
194
        {
195
        mBuffer[j] = null;
196
        }
197

    
198
      mBuffer = null;
199
      }
200
    }
201

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

    
211
  private static void clonePostprocessingViewportAndProjection(InternalOutputSurface from)
212
    {
213
    if( mBuffer[0].mWidth != from.mWidth || mBuffer[0].mHeight != from.mHeight ||
214
        mBuffer[0].mFOV   != from.mFOV   || mBuffer[0].mNear   != from.mNear    )
215
      {
216
      InternalOutputSurface surface;
217

    
218
      for(int i=0; i<EffectQuality.LENGTH; i++)
219
        {
220
        surface = mBuffer[i];
221

    
222
        surface.mWidth  = (int)(from.mWidth *surface.mMipmap);
223
        surface.mHeight = (int)(from.mHeight*surface.mMipmap);
224
        surface.mFOV    = from.mFOV;
225
        surface.mNear   = from.mNear;  // Near plane is independent of the mipmap level
226

    
227
        surface.createProjection();
228

    
229
        int maxw = surface.mWidth  > surface.mRealWidth  ? surface.mWidth  : surface.mRealWidth;
230
        int maxh = surface.mHeight > surface.mRealHeight ? surface.mHeight : surface.mRealHeight;
231

    
232
        if (maxw > surface.mRealWidth || maxh > surface.mRealHeight)
233
          {
234
          surface.mRealWidth = maxw;
235
          surface.mRealHeight = maxh;
236

    
237
          surface.recreate();
238
          surface.create();
239
          }
240
        }
241
      }
242
    }
243

    
244
///////////////////////////////////////////////////////////////////////////////////////////////////
245

    
246
  private int blitWithDepth(long currTime, InternalOutputSurface buffer, int fbo)
247
    {
248
    GLES31.glViewport(0, 0, mWidth, mHeight);
249
    setAsOutput(currTime);
250
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
251
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
252
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
253
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
254

    
255
    GLES31.glDisable(GLES31.GL_STENCIL_TEST);
256
    GLES31.glStencilMask(0x00);
257

    
258
    DistortedLibrary.blitDepthPriv(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
259
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
260
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
261
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
262
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
263

    
264
    // clear buffers
265
    GLES31.glStencilMask(0xff);
266
    GLES31.glDepthMask(true);
267
    GLES31.glColorMask(true,true,true,true);
268
    GLES31.glClearColor(buffer.mClearR,buffer.mClearG,buffer.mClearB,buffer.mClearA);
269
    GLES31.glClearDepthf(buffer.mClearDepth);
270
    GLES31.glClearStencil(buffer.mClearStencil);
271

    
272
    buffer.setAsOutput();
273
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo+1], 0);
274
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
275
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo  ], 0);
276
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
277

    
278
    return 1;
279
    }
280

    
281
///////////////////////////////////////////////////////////////////////////////////////////////////
282

    
283
  private static void oitClear(InternalOutputSurface buffer)
284
    {
285
    int counter = DistortedLibrary.zeroOutAtomic();
286
    DistortedLibrary.oitClear(buffer,counter);
287
    GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT|GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
288
    }
289

    
290
///////////////////////////////////////////////////////////////////////////////////////////////////
291

    
292
  private int oitBuild(long time, InternalOutputSurface buffer, int fbo)
293
    {
294
    GLES31.glViewport(0, 0, mWidth, mHeight);
295
    setAsOutput(time);
296
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
297
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
298
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
299
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
300

    
301
    InternalRenderState.colorDepthStencilOn();
302
    InternalRenderState.enableDepthTest();
303

    
304
    DistortedLibrary.oitBuild(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
305
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
306
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
307
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
308
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
309

    
310
    InternalRenderState.colorDepthStencilRestore();
311
    InternalRenderState.restoreDepthTest();
312

    
313
    return 1;
314
    }
315

    
316
///////////////////////////////////////////////////////////////////////////////////////////////////
317
// two phases: 1. collapse the SSBO 2. blend the ssbo's color
318

    
319
  private int oitRender(long currTime, int fbo)
320
    {
321
    float corrW = getWidthCorrection();
322
    float corrH = getHeightCorrection();
323

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

    
327
    if( mDepthStencilH[fbo] != 0 )
328
      {
329
      GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, 0);
330
      GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
331
      GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, mDepthStencilH[fbo]);
332
      InternalRenderState.switchOffColorDepthStencil();
333
      DistortedLibrary.oitCollapse(this, corrW, corrH);
334
      GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
335
      }
336

    
337
    setAsOutput(currTime);
338
    InternalRenderState.switchColorDepthOnStencilOff();
339
    DistortedLibrary.oitRender(this, corrW, corrH);
340
    InternalRenderState.restoreColorDepthStencil();
341

    
342
    return 1;
343
    }
344

    
345
///////////////////////////////////////////////////////////////////////////////////////////////////
346

    
347
  private void clear()
348
    {
349
    InternalRenderState.colorDepthStencilOn();
350
    GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
351
    GLES31.glClearDepthf(mClearDepth);
352
    GLES31.glClearStencil(mClearStencil);
353
    GLES31.glClear(mClear);
354
    InternalRenderState.colorDepthStencilRestore();
355
    }
356

    
357
///////////////////////////////////////////////////////////////////////////////////////////////////
358

    
359
  void setCurrFBO(int fbo)
360
    {
361
    mCurrFBO = fbo;
362
    }
363

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

    
370
  int renderChildren(long time, int numChildren, InternalChildrenList children, int fbo, boolean oit)
371
    {
372
    int numRenders=0, bucketChange=0;
373
    DistortedNode child;
374
    DistortedFramebuffer buffer=null;
375
    EffectQueuePostprocess lastQueue=null, currQueue;
376
    long lastBucket=0, currBucket;
377
    boolean renderDirectly=false;
378

    
379
    setCurrFBO(fbo);
380

    
381
    if( mBuffer!=null )
382
      {
383
      for (int i=0; i<EffectQuality.LENGTH; i++) mBuffer[i].setCurrFBO(fbo);
384
      }
385

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

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

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

    
401
        if( oit )
402
          {
403
          numRenders += child.drawOIT(time, this);
404
          GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
405
          }
406
        else
407
          {
408
          numRenders += child.draw(time, this);
409
          }
410
        }
411
      else
412
        {
413
        if( mBuffer==null )
414
          {
415
          createPostprocessingBuffers(mWidth,mHeight,mNear);
416
          for (int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].setCurrFBO(fbo);
417
          }
418

    
419
        if( lastBucket!=currBucket )
420
          {
421
          if( lastBucket==0 )
422
            {
423
            clonePostprocessingViewportAndProjection(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[currQueue.getQuality()];
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
    GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
552
    GLES31.glClearDepthf(mClearDepth);
553
    GLES31.glClearStencil(mClearStencil);
554

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

    
561
    InternalRenderState.colorDepthStencilRestore();
562
    }
563

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

    
566
  void setAsOutput(long time)
567
    {
568
    GLES31.glBindFramebuffer(GLES31.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
    GLES31.glBindFramebuffer(GLES31.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 Distance between the screen plane and the near plane.
737
 *             Valid vaules: 0<near<1. When near==0 (illegal!), the Near Plane is exactly at the tip of
738
 *             the pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
739
 */
740
  public void setProjection(float fov, float near)
741
    {
742
    if( fov < 180.0f && fov >=0.0f )
743
      {
744
      mFOV = fov;
745
      }
746

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

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

    
765
    createProjection();
766
    }
767

    
768
///////////////////////////////////////////////////////////////////////////////////////////////////
769
/**
770
 * Return the vertical field of view angle.
771
 *
772
 * @return Vertival Field of View Angle, in degrees.
773
 */
774
  public float getFOV()
775
    {
776
    return mFOV;
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
 * When rendering this Node, should we use the Order Independent Transparency render mode?
830
 * <p>
831
 * There are two modes of rendering: the fast 'normal' way, which however renders transparent
832
 * fragments in different ways depending on which fragments get rendered first, or the slower
833
 * 'oit' way, which renders transparent fragments correctly regardless of their order.
834
 *
835
 * @param oit True if we want to render more slowly, but in a way which accounts for transparency.
836
 */
837
  public void setOrderIndependentTransparency(boolean oit)
838
    {
839
    mRenderWayOIT = oit;
840
    }
841

    
842
///////////////////////////////////////////////////////////////////////////////////////////////////
843
/**
844
 * When rendering this Node, should we use the Order Independent Transparency render mode?
845
 * <p>
846
 * There are two modes of rendering: the fast 'normal' way, which however renders transparent
847
 * fragments in different ways depending on which fragments get rendered first, or the slower
848
 * 'oit' way, which renders transparent fragments correctly regardless of their order.
849
 *
850
 * @param oit True if we want to render more slowly, but in a way which accounts for transparency.
851
 * @param initialSize Initial number of transparent fragments we expect, in screenfuls.
852
 *                    I.e '1.0' means 'the scene we are going to render contains dialog_about 1 screen
853
 *                    worth of transparent fragments'. Valid values: 0.0 &lt; initialSize &lt; 10.0
854
 *                    Even if you get this wrong, the library will detect that there are more
855
 *                    transparent fragments than it has space for and readjust its internal buffers,
856
 *                    but only after a few frames during which one will probably see missing objects.
857
 */
858
public void setOrderIndependentTransparency(boolean oit, float initialSize)
859
  {
860
  mRenderWayOIT = oit;
861

    
862
  if( initialSize>0.0f && initialSize<10.0f )
863
    DistortedLibrary.setSSBOSize(initialSize);
864
  }
865

    
866
///////////////////////////////////////////////////////////////////////////////////////////////////
867
/**
868
 * Adds a new child to the last position in the list of our Surface's children.
869
 * <p>
870
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
871
 * InternalMaster (by calling doWork())
872
 *
873
 * @param node The new Node to add.
874
 */
875
  public void attach(DistortedNode node)
876
    {
877
    mChildren.attach(node);
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 surface InputSurface to initialize our child Node with.
888
 * @param effects DistortedEffects to initialize our child Node with.
889
 * @param mesh MeshBase to initialize our child Node with.
890
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
891
 */
892
  public DistortedNode attach(InternalSurface surface, DistortedEffects effects, MeshBase mesh)
893
    {
894
    return mChildren.attach(surface,effects,mesh);
895
    }
896

    
897
///////////////////////////////////////////////////////////////////////////////////////////////////
898
/**
899
 * Removes the first occurrence of a specified child from the list of children of our Surface.
900
 * <p>
901
 * A bit questionable method as there can be many different Nodes attached as children, some
902
 * of them having the same Effects but - for instance - different Mesh. Use with care.
903
 * <p>
904
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
905
 * InternalMaster (by calling doWork())
906
 *
907
 * @param effects DistortedEffects to remove.
908
 */
909
  public void detach(DistortedEffects effects)
910
    {
911
    mChildren.detach(effects);
912
    }
913

    
914
///////////////////////////////////////////////////////////////////////////////////////////////////
915
/**
916
 * Removes the first occurrence of a specified child from the list of children of our Surface.
917
 * <p>
918
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
919
 * InternalMaster (by calling doWork())
920
 *
921
 * @param node The Node to remove.
922
 */
923
  public void detach(DistortedNode node)
924
    {
925
    mChildren.detach(node);
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
 * InternalMaster (by calling doWork())
934
 */
935
  public void detachAll()
936
    {
937
    mChildren.detachAll();
938
    }
939
}
(12-12/14)