Project

General

Profile

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

library / src / main / java / org / distorted / library / main / InternalOutputSurface.java @ 209ea1c7

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
  public static final float DEFAULT_FOV = 60.0f;
42
  public static final float DEFAULT_NEAR=  0.1f;
43

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

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

    
60
///////////////////////////////////////////////////////////////////////////////////////////////////
61

    
62
  InternalOutputSurface(int width, int height, int createColor, int numfbos, int numcolors, int depthStencil, int fbo, int type)
63
    {
64
    super(createColor,numfbos,numcolors,type);
65

    
66
    mRenderWayOIT = false;
67
    mCurrFBO      = 0;
68

    
69
    mDepthStencilH = new int[numfbos];
70
    mFBOH          = new int[numfbos];
71

    
72
    mTime = new long[numfbos];
73
    for(int i=0; i<mNumFBOs;i++) mTime[i]=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
    mFBOH[0]         = fbo;
87
    mDepthStencilH[0]= 0;
88

    
89
    mClearR = 0.0f;
90
    mClearG = 0.0f;
91
    mClearB = 0.0f;
92
    mClearA = 0.0f;
93

    
94
    mClearDepth = 1.0f;
95
    mClearStencil = 0;
96
    mClear = GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_COLOR_BUFFER_BIT;
97

    
98
    mMipmap = 1.0f;
99

    
100
    mChildren = new InternalChildrenList(this);
101

    
102
    createProjection();
103
    }
104

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

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

    
117
        float left   = -q/2;
118
        float right  = +q/2;
119
        float bottom = -c/2;
120
        float top    = +c/2;
121
        float near   =  c/a;
122

    
123
        mDistance    = mHeight/a;
124
        float far    = 2*mDistance-near;
125

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

    
138
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
139
        }
140
      }
141
    }
142

    
143
///////////////////////////////////////////////////////////////////////////////////////////////////
144

    
145
  private static void createPostprocessingBuffers(int width, int height, float near)
146
    {
147
    final float CLEAR_R = 1.0f;
148
    final float CLEAR_G = 1.0f;
149
    final float CLEAR_B = 1.0f;
150
    final float CLEAR_A = 0.0f;
151
    final float CLEAR_D = 1.0f;
152
    final int   CLEAR_S = 0;
153

    
154
    mBuffer = new DistortedFramebuffer[EffectQuality.LENGTH];
155
    float mipmap=1.0f;
156

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

    
164
      mipmap *= EffectQuality.MULTIPLIER;
165
      }
166

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

    
169
    InternalRenderState.colorDepthStencilOn();
170
    GLES31.glClearColor(CLEAR_R, CLEAR_G, CLEAR_B, CLEAR_A);
171
    GLES31.glClearDepthf(CLEAR_D);
172
    GLES31.glClearStencil(CLEAR_S);
173

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

    
186
    InternalRenderState.colorDepthStencilRestore();
187

    
188
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, 0);
189
    }
190

    
191
///////////////////////////////////////////////////////////////////////////////////////////////////
192

    
193
  static synchronized void onDestroy()
194
    {
195
    if( mBuffer!=null )
196
      {
197
      for (int j = 0; j < EffectQuality.LENGTH; j++)
198
        {
199
        mBuffer[j] = null;
200
        }
201

    
202
      mBuffer = null;
203
      }
204
    }
205

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

    
215
  private static void clonePostprocessingViewportAndProjection(InternalOutputSurface from)
216
    {
217
    if( mBuffer[0].mWidth != from.mWidth || mBuffer[0].mHeight != from.mHeight ||
218
        mBuffer[0].mFOV   != from.mFOV   || mBuffer[0].mNear   != from.mNear    )
219
      {
220
      InternalOutputSurface surface;
221

    
222
      for(int i=0; i<EffectQuality.LENGTH; i++)
223
        {
224
        surface = mBuffer[i];
225

    
226
        surface.mWidth  = (int)(from.mWidth *surface.mMipmap);
227
        surface.mHeight = (int)(from.mHeight*surface.mMipmap);
228
        surface.mFOV    = from.mFOV;
229
        surface.mNear   = from.mNear;  // Near plane is independent of the mipmap level
230

    
231
        surface.createProjection();
232

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

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

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

    
248
///////////////////////////////////////////////////////////////////////////////////////////////////
249

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

    
259
    GLES31.glDisable(GLES31.GL_STENCIL_TEST);
260
    GLES31.glStencilMask(0x00);
261

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

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

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

    
282
    return 1;
283
    }
284

    
285
///////////////////////////////////////////////////////////////////////////////////////////////////
286

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

    
294
///////////////////////////////////////////////////////////////////////////////////////////////////
295

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

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

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

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

    
317
    return 1;
318
    }
319

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

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

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

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

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

    
346
    return 1;
347
    }
348

    
349
///////////////////////////////////////////////////////////////////////////////////////////////////
350

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

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

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

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

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

    
383
    setCurrFBO(fbo);
384

    
385
    if( mBuffer!=null )
386
      {
387
      for (int i=0; i<EffectQuality.LENGTH; i++) mBuffer[i].setCurrFBO(fbo);
388
      }
389

    
390
    if( oit && numChildren>0 )
391
      {
392
      oitClear(this);
393
      }
394

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

    
401
      if( currBucket==0 )
402
        {
403
        setAsOutput(time);
404

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

    
423
        if( lastBucket!=currBucket )
424
          {
425
          if( lastBucket==0 )
426
            {
427
            clonePostprocessingViewportAndProjection(this);
428
            }
429
          else
430
            {
431
            for(int j=bucketChange; j<i; j++)
432
              {
433
              DistortedNode node = children.getChild(j);
434

    
435
              if( node.getSurface().setAsInput() )
436
                {
437
                buffer.setAsOutput();
438
                numRenders += lastQueue.preprocess( buffer, node, buffer.mDistance, buffer.mMipmap, buffer.mProjectionMatrix );
439
                }
440
              }
441
            numRenders += lastQueue.postprocess(buffer);
442

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

    
455
          buffer= mBuffer[currQueue.getQuality()];
456
          bucketChange= i;
457
          renderDirectly = currQueue.getRender();
458
          }
459

    
460
        if( renderDirectly )
461
          {
462
          setAsOutput(time);
463

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

    
480
        if( i==numChildren-1 )
481
          {
482
          for(int j=bucketChange; j<numChildren; j++)
483
            {
484
            DistortedNode node = children.getChild(j);
485

    
486
            if( node.getSurface().setAsInput() )
487
              {
488
              buffer.setAsOutput();
489
              numRenders += currQueue.preprocess( buffer, node, buffer.mDistance, buffer.mMipmap, buffer.mProjectionMatrix );
490
              }
491
            }
492
          numRenders += currQueue.postprocess(buffer);
493

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

    
507
      lastQueue = currQueue;
508
      lastBucket= currBucket;
509
      } // end main for loop
510

    
511
    if( oit && numChildren>0 )
512
      {
513
      numRenders += oitRender(time, fbo);  // merge the OIT linked list
514
      }
515

    
516
    return numRenders;
517
    }
518

    
519
///////////////////////////////////////////////////////////////////////////////////////////////////
520
/**
521
 * Not part of the public API.
522
 *
523
 * @y.exclude
524
 */
525
  public void adjustIsomorphism() { }
526

    
527
///////////////////////////////////////////////////////////////////////////////////////////////////
528
/**
529
 * Not part of the Public API.
530
 *
531
 * @y.exclude
532
 */
533
  public float getWidthCorrection()
534
    {
535
    return (float)mWidth/mRealWidth;
536
    }
537

    
538
///////////////////////////////////////////////////////////////////////////////////////////////////
539
/**
540
 * Not part of the Public API.
541
 *
542
 * @y.exclude
543
 */
544
  public float getHeightCorrection()
545
    {
546
    return (float)mHeight/mRealHeight;
547
    }
548

    
549
///////////////////////////////////////////////////////////////////////////////////////////////////
550

    
551
  void clearBuffer(int fbo)
552
    {
553
    InternalRenderState.colorDepthStencilOn();
554

    
555
    GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
556
    GLES31.glClearDepthf(mClearDepth);
557
    GLES31.glClearStencil(mClearStencil);
558

    
559
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[fbo]);
560
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mColorH[2*fbo+1], 0);
561
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
562
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mColorH[2*fbo  ], 0);
563
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
564

    
565
    InternalRenderState.colorDepthStencilRestore();
566
    }
567

    
568
///////////////////////////////////////////////////////////////////////////////////////////////////
569

    
570
  void setAsOutput(long time)
571
    {
572
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
573

    
574
    if( mTime[mCurrFBO]!=time )
575
      {
576
      mTime[mCurrFBO] = time;
577
      clear();
578
      }
579
    }
580

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

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

    
613
    int numRenders=0, numChildren = mChildren.getNumChildren();
614
    DistortedNode node;
615
    long oldBucket=0, newBucket;
616

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

    
626
    numRenders += renderChildren(time,numChildren,mChildren,fbo, mRenderWayOIT);
627

    
628
    return numRenders;
629
    }
630

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

    
642
///////////////////////////////////////////////////////////////////////////////////////////////////
643
/**
644
 * Return the Near plane of the Projection included in the Surface.
645
 *
646
 * @return the Near plane.
647
 */
648
  public float getNear()
649
    {
650
    return mNear;
651
    }
652

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

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

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

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

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

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

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

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

    
767
    createProjection();
768
    }
769

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

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

    
797
      createProjection();
798

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

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

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

    
829
///////////////////////////////////////////////////////////////////////////////////////////////////
830
/**
831
 * When rendering this Node, should we use the Order Independent Transparency render mode?
832
 * <p>
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
    mRenderWayOIT = oit;
842
    }
843

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

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

    
868
///////////////////////////////////////////////////////////////////////////////////////////////////
869
/**
870
 * Adds a new child to the last position in the list of our Surface's children.
871
 * <p>
872
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
873
 * InternalMaster (by calling doWork())
874
 *
875
 * @param node The new Node to add.
876
 */
877
  public void attach(DistortedNode node)
878
    {
879
    mChildren.attach(node);
880
    }
881

    
882
///////////////////////////////////////////////////////////////////////////////////////////////////
883
/**
884
 * Adds a new child to the last position in the list of our Surface's children.
885
 * <p>
886
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
887
 * InternalMaster (by calling doWork())
888
 *
889
 * @param surface InputSurface to initialize our child Node with.
890
 * @param effects DistortedEffects to initialize our child Node with.
891
 * @param mesh MeshBase to initialize our child Node with.
892
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
893
 */
894
  public DistortedNode attach(InternalSurface surface, DistortedEffects effects, MeshBase mesh)
895
    {
896
    return mChildren.attach(surface,effects,mesh);
897
    }
898

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

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

    
930
///////////////////////////////////////////////////////////////////////////////////////////////////
931
/**
932
 * Removes all children Nodes.
933
 * <p>
934
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
935
 * InternalMaster (by calling doWork())
936
 */
937
  public void detachAll()
938
    {
939
    mChildren.detachAll();
940
    }
941

    
942
///////////////////////////////////////////////////////////////////////////////////////////////////
943
/**
944
 * Return the width of this Surface.
945
 *
946
 * @return width of the Object, in pixels.
947
 */
948
  public int getWidth()
949
    {
950
    return mWidth;
951
    }
952

    
953
///////////////////////////////////////////////////////////////////////////////////////////////////
954
/**
955
 * Return the height of this Surface.
956
 *
957
 * @return height of the Object, in pixels.
958
 */
959
  public int getHeight()
960
    {
961
    return mHeight;
962
    }
963
}
(12-12/14)