Project

General

Profile

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

library / src / main / java / org / distorted / library / main / InternalOutputSurface.java @ 66103fb2

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

    
44
  private float mFOV;
45

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

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

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

    
64
///////////////////////////////////////////////////////////////////////////////////////////////////
65

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

    
70
    mRenderWayOIT = false;
71
    mCurrFBO      = 0;
72

    
73
    mDepthStencilH = new int[numfbos];
74
    mFBOH          = new int[numfbos];
75

    
76
    mTime = new long[numfbos];
77
    for(int i=0; i<mNumFBOs;i++) mTime[i]=0;
78

    
79
    mRealWidth = mWidth = width;
80
    mRealHeight= mHeight= height;
81

    
82
    mProjectionMatrix = new float[16];
83

    
84
    mFOV = DEFAULT_FOV;
85
    mNear= DEFAULT_NEAR;
86

    
87
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
88
    mDepthStencil = depthStencil;
89

    
90
    mFBOH[0]         = fbo;
91
    mDepthStencilH[0]= 0;
92

    
93
    mClearR = 0.0f;
94
    mClearG = 0.0f;
95
    mClearB = 0.0f;
96
    mClearA = 0.0f;
97

    
98
    mClearDepth = 1.0f;
99
    mClearStencil = 0;
100
    mClear = GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_COLOR_BUFFER_BIT;
101

    
102
    mMipmap = 1.0f;
103

    
104
    mChildren = new InternalChildrenList(this);
105

    
106
    createProjection();
107
    }
108

    
109
///////////////////////////////////////////////////////////////////////////////////////////////////
110

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

    
121
        float left   = -q/2;
122
        float right  = +q/2;
123
        float bottom = -c/2;
124
        float top    = +c/2;
125
        float near   =  c/a;
126

    
127
        mDistance    = mHeight/a;
128
        float far    = 2*mDistance-near;
129

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

    
142
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
143
        }
144
      }
145
    }
146

    
147
///////////////////////////////////////////////////////////////////////////////////////////////////
148

    
149
  private static void createPostprocessingBuffers(int quality, int width, int height, float near)
150
    {
151
    final float CLEAR_R = 1.0f;
152
    final float CLEAR_G = 1.0f;
153
    final float CLEAR_B = 1.0f;
154
    final float CLEAR_A = 0.0f;
155
    final float CLEAR_D = 1.0f;
156
    final int   CLEAR_S = 0;
157

    
158
    float mipmap=1.0f;
159

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

    
162
    mBuffer[quality] = new DistortedFramebuffer(DistortedLibrary.FBO_QUEUE_SIZE,2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(width*mipmap), (int)(height*mipmap) );
163
    mBuffer[quality].mMipmap = mipmap;
164
    mBuffer[quality].mNear = near;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
165
    mBuffer[quality].glClearColor(CLEAR_R, CLEAR_G, CLEAR_B, CLEAR_A);
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 k = 0; k< DistortedLibrary.FBO_QUEUE_SIZE; k++)
175
      {
176
      GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mBuffer[quality].mFBOH[k]);
177
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[quality].mColorH[2*k+1], 0);
178
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT | GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_STENCIL_BUFFER_BIT);
179
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[quality].mColorH[2*k  ], 0);
180
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
181
      }
182

    
183
    InternalRenderState.colorDepthStencilRestore();
184

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

    
188
///////////////////////////////////////////////////////////////////////////////////////////////////
189

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

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

    
209
  private static void clonePostprocessingViewportAndProjection(InternalOutputSurface surface, InternalOutputSurface from)
210
    {
211
    if( surface.mWidth != from.mWidth || surface.mHeight != from.mHeight ||
212
        surface.mFOV   != from.mFOV   || surface.mNear   != from.mNear    )
213
      {
214
      surface.mWidth  = (int)(from.mWidth *surface.mMipmap);
215
      surface.mHeight = (int)(from.mHeight*surface.mMipmap);
216
      surface.mFOV    = from.mFOV;
217
      surface.mNear   = from.mNear;  // Near plane is independent of the mipmap level
218

    
219
      surface.createProjection();
220

    
221
      int maxw = Math.max(surface.mWidth , surface.mRealWidth );
222
      int maxh = Math.max(surface.mHeight, surface.mRealHeight);
223

    
224
      if (maxw > surface.mRealWidth || maxh > surface.mRealHeight)
225
        {
226
        surface.mRealWidth = maxw;
227
        surface.mRealHeight = maxh;
228

    
229
        surface.recreate();
230
        surface.create();
231
        }
232
      }
233
    }
234

    
235
///////////////////////////////////////////////////////////////////////////////////////////////////
236

    
237
  private int blitWithDepth(long currTime, InternalOutputSurface buffer, int fbo)
238
    {
239
    GLES31.glViewport(0, 0, mWidth, mHeight);
240
    setAsOutput(currTime);
241
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
242
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
243
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
244
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
245

    
246
    GLES31.glDisable(GLES31.GL_STENCIL_TEST);
247
    GLES31.glStencilMask(0x00);
248

    
249
    DistortedLibrary.blitDepthPriv(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
250
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
251
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
252
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
253
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
254

    
255
    // clear buffers
256
    GLES31.glStencilMask(0xff);
257
    GLES31.glDepthMask(true);
258
    GLES31.glColorMask(true,true,true,true);
259
    GLES31.glClearColor(buffer.mClearR,buffer.mClearG,buffer.mClearB,buffer.mClearA);
260
    GLES31.glClearDepthf(buffer.mClearDepth);
261
    GLES31.glClearStencil(buffer.mClearStencil);
262

    
263
    buffer.setAsOutput();
264
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo+1], 0);
265
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
266
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo  ], 0);
267
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
268

    
269
    return 1;
270
    }
271

    
272
///////////////////////////////////////////////////////////////////////////////////////////////////
273

    
274
  private static void oitClear(InternalOutputSurface buffer)
275
    {
276
    int counter = DistortedLibrary.zeroOutAtomic();
277
    DistortedLibrary.oitClear(buffer,counter);
278
    GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT|GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
279
    }
280

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

    
283
  private int oitBuild(long time, InternalOutputSurface buffer, int fbo)
284
    {
285
    GLES31.glViewport(0, 0, mWidth, mHeight);
286
    setAsOutput(time);
287
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
288
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
289
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
290
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
291

    
292
    InternalRenderState.colorDepthStencilOn();
293
    InternalRenderState.enableDepthTest();
294

    
295
    DistortedLibrary.oitBuild(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
296
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
297
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
298
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
299
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
300

    
301
    InternalRenderState.colorDepthStencilRestore();
302
    InternalRenderState.restoreDepthTest();
303

    
304
    return 1;
305
    }
306

    
307
///////////////////////////////////////////////////////////////////////////////////////////////////
308
// two phases: 1. collapse the SSBO 2. blend the ssbo's color
309

    
310
  private int oitRender(long currTime, int fbo)
311
    {
312
    float corrW = getWidthCorrection();
313
    float corrH = getHeightCorrection();
314

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

    
318
    if( mDepthStencilH[fbo] != 0 )
319
      {
320
      GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, 0);
321
      GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
322
      GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, mDepthStencilH[fbo]);
323
      InternalRenderState.switchOffColorDepthStencil();
324
      DistortedLibrary.oitCollapse(this, corrW, corrH);
325
      GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
326
      }
327

    
328
    setAsOutput(currTime);
329
    InternalRenderState.switchColorDepthOnStencilOff();
330
    DistortedLibrary.oitRender(this, corrW, corrH);
331
    InternalRenderState.restoreColorDepthStencil();
332

    
333
    return 1;
334
    }
335

    
336
///////////////////////////////////////////////////////////////////////////////////////////////////
337

    
338
  private void clear()
339
    {
340
    InternalRenderState.colorDepthStencilOn();
341
    GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
342
    GLES31.glClearDepthf(mClearDepth);
343
    GLES31.glClearStencil(mClearStencil);
344
    GLES31.glClear(mClear);
345
    InternalRenderState.colorDepthStencilRestore();
346
    }
347

    
348
///////////////////////////////////////////////////////////////////////////////////////////////////
349

    
350
  void setCurrFBO(int fbo)
351
    {
352
    mCurrFBO = fbo;
353
    }
354

    
355
///////////////////////////////////////////////////////////////////////////////////////////////////
356
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
357
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
358
// to a whole buffer (lastQueue.postprocess) and merge it (this.oitBuild or blitWithDepth - depending
359
// on the type of rendering)
360

    
361
  int renderChildren(long time, int numChildren, InternalChildrenList children, int fbo, boolean oit)
362
    {
363
    int numRenders=0, bucketChange=0;
364
    DistortedNode child;
365
    DistortedFramebuffer buffer=null;
366
    EffectQueuePostprocess lastQueue=null, currQueue;
367
    long lastBucket=0, currBucket;
368
    boolean renderDirectly=false;
369

    
370
    setCurrFBO(fbo);
371

    
372
    if( oit && numChildren>0 )
373
      {
374
      oitClear(this);
375
      }
376

    
377
    for(int i=0; i<numChildren; i++)
378
      {
379
      child = children.getChild(i);
380
      currQueue = (EffectQueuePostprocess)child.getEffects().getQueues()[3];
381
      currBucket= currQueue.getID();
382

    
383
      if( currBucket==0 )
384
        {
385
        setAsOutput(time);
386

    
387
        if( oit )
388
          {
389
          numRenders += child.drawOIT(time, this);
390
          GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
391
          }
392
        else
393
          {
394
          numRenders += child.draw(time, this);
395
          }
396
        }
397
      else
398
        {
399
        int currQuality = currQueue.getQuality();
400

    
401
        if( mBuffer[currQuality]==null ) createPostprocessingBuffers(currQuality, mWidth, mHeight, mNear);
402
        mBuffer[currQuality].setCurrFBO(fbo);
403

    
404
        if( lastBucket!=currBucket )
405
          {
406
          if( lastBucket==0 )
407
            {
408
            clonePostprocessingViewportAndProjection(mBuffer[currQuality],this);
409
            }
410
          else
411
            {
412
            for(int j=bucketChange; j<i; j++)
413
              {
414
              DistortedNode node = children.getChild(j);
415

    
416
              if( node.getSurface().setAsInput() )
417
                {
418
                buffer.setAsOutput();
419
                numRenders += lastQueue.preprocess( buffer, node, buffer.mDistance, buffer.mMipmap, buffer.mProjectionMatrix );
420
                }
421
              }
422
            numRenders += lastQueue.postprocess(buffer);
423

    
424
            if( oit )
425
              {
426
              numRenders += oitBuild(time, buffer, fbo);
427
              GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
428
              }
429
            else
430
              {
431
              numRenders += blitWithDepth(time, buffer, fbo);
432
              }
433
            buffer.clearBuffer(fbo);
434
            }
435

    
436
          buffer= mBuffer[currQuality];
437
          bucketChange= i;
438
          renderDirectly = currQueue.getRender();
439
          }
440

    
441
        if( renderDirectly )
442
          {
443
          setAsOutput(time);
444

    
445
          if( oit )
446
            {
447
            numRenders += child.drawOIT(time, this);
448
            GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
449
            }
450
          else
451
            {
452
            numRenders += child.draw(time, this);
453
            }
454
          }
455
        else
456
          {
457
          buffer.setAsOutput(time);
458
          child.drawNoBlend(time, buffer);
459
          }
460

    
461
        if( i==numChildren-1 )
462
          {
463
          for(int j=bucketChange; j<numChildren; j++)
464
            {
465
            DistortedNode node = children.getChild(j);
466

    
467
            if( node.getSurface().setAsInput() )
468
              {
469
              buffer.setAsOutput();
470
              numRenders += currQueue.preprocess( buffer, node, buffer.mDistance, buffer.mMipmap, buffer.mProjectionMatrix );
471
              }
472
            }
473
          numRenders += currQueue.postprocess(buffer);
474

    
475
          if( oit )
476
            {
477
            numRenders += oitBuild(time, buffer, fbo);
478
            GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
479
            buffer.clearBuffer(fbo);
480
            }
481
          else
482
            {
483
            numRenders += blitWithDepth(time, buffer,fbo);
484
            }
485
          }
486
        } // end else (postprocessed child)
487

    
488
      lastQueue = currQueue;
489
      lastBucket= currBucket;
490
      } // end main for loop
491

    
492
    if( oit && numChildren>0 )
493
      {
494
      numRenders += oitRender(time, fbo);  // merge the OIT linked list
495
      }
496

    
497
    return numRenders;
498
    }
499

    
500
///////////////////////////////////////////////////////////////////////////////////////////////////
501
/**
502
 * Not part of the public API.
503
 *
504
 * @y.exclude
505
 */
506
  public void adjustIsomorphism() { }
507

    
508
///////////////////////////////////////////////////////////////////////////////////////////////////
509
/**
510
 * Not part of the Public API.
511
 *
512
 * @y.exclude
513
 */
514
  public float getWidthCorrection()
515
    {
516
    return (float)mWidth/mRealWidth;
517
    }
518

    
519
///////////////////////////////////////////////////////////////////////////////////////////////////
520
/**
521
 * Not part of the Public API.
522
 *
523
 * @y.exclude
524
 */
525
  public float getHeightCorrection()
526
    {
527
    return (float)mHeight/mRealHeight;
528
    }
529

    
530
///////////////////////////////////////////////////////////////////////////////////////////////////
531

    
532
  void clearBuffer(int fbo)
533
    {
534
    InternalRenderState.colorDepthStencilOn();
535

    
536
    GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
537
    GLES31.glClearDepthf(mClearDepth);
538
    GLES31.glClearStencil(mClearStencil);
539

    
540
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[fbo]);
541
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mColorH[2*fbo+1], 0);
542
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
543
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mColorH[2*fbo  ], 0);
544
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
545

    
546
    InternalRenderState.colorDepthStencilRestore();
547
    }
548

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

    
551
  void setAsOutput(long time)
552
    {
553
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
554

    
555
    if( mTime[mCurrFBO]!=time )
556
      {
557
      mTime[mCurrFBO] = time;
558
      clear();
559
      }
560
    }
561

    
562
///////////////////////////////////////////////////////////////////////////////////////////////////
563
// PUBLIC API
564
///////////////////////////////////////////////////////////////////////////////////////////////////
565
/**
566
 * Draws all the attached children to this OutputSurface's 0th FBO.
567
 * <p>
568
 * Must be called from a thread holding OpenGL Context.
569
 *
570
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
571
 * @return Number of objects rendered.
572
 */
573
  public int render(long time)
574
    {
575
    return render(time,0);
576
    }
577

    
578
///////////////////////////////////////////////////////////////////////////////////////////////////
579
/**
580
 * Draws all the attached children to this OutputSurface.
581
 * <p>
582
 * Must be called from a thread holding OpenGL Context.
583
 *
584
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
585
 * @param fbo The surface can have many FBOs backing it up - render this to FBO number 'fbo'.
586
 * @return Number of objects rendered.
587
 */
588
  public int render(long time, int fbo)
589
    {
590
    InternalMaster.toDo();
591
    toDo();
592
    InternalRenderState.reset();
593

    
594
    int numRenders=0, numChildren = mChildren.getNumChildren();
595
    DistortedNode node;
596
    long oldBucket=0, newBucket;
597

    
598
    for(int i=0; i<numChildren; i++)
599
      {
600
      node = mChildren.getChild(i);
601
      newBucket = node.getBucket();
602
      numRenders += node.renderRecursive(time);
603
      if( newBucket<oldBucket ) mChildren.rearrangeByBuckets(i,newBucket);
604
      else oldBucket=newBucket;
605
      }
606

    
607
    numRenders += renderChildren(time,numChildren,mChildren,fbo, mRenderWayOIT);
608

    
609
    return numRenders;
610
    }
611

    
612
///////////////////////////////////////////////////////////////////////////////////////////////////
613
/**
614
 * Bind this Surface as a Framebuffer we can render to.
615
 * <p>
616
 * This version does not attempt to clear anything.
617
 */
618
  public void setAsOutput()
619
    {
620
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
621
    }
622

    
623
///////////////////////////////////////////////////////////////////////////////////////////////////
624
/**
625
 * Return the Near plane of the Projection included in the Surface.
626
 *
627
 * @return the Near plane.
628
 */
629
  public float getNear()
630
    {
631
    return mNear;
632
    }
633

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

    
658
///////////////////////////////////////////////////////////////////////////////////////////////////
659
/**
660
 * Set the (R,G,B,A) values of GLES31.glClearColor() to set up color with which to clear
661
 * this Surface at the beginning of each frame.
662
 *
663
 * @param r the Red component. Default: 0.0f
664
 * @param g the Green component. Default: 0.0f
665
 * @param b the Blue component. Default: 0.0f
666
 * @param a the Alpha component. Default: 0.0f
667
 */
668
  public void glClearColor(float r, float g, float b, float a)
669
    {
670
    mClearR = r;
671
    mClearG = g;
672
    mClearB = b;
673
    mClearA = a;
674
    }
675

    
676
///////////////////////////////////////////////////////////////////////////////////////////////////
677
/**
678
 * Uses glClearDepthf() to set up a value with which to clear
679
 * the Depth buffer of our Surface at the beginning of each frame.
680
 *
681
 * @param d the Depth. Default: 1.0f
682
 */
683
  public void glClearDepthf(float d)
684
    {
685
    mClearDepth = d;
686
    }
687

    
688
///////////////////////////////////////////////////////////////////////////////////////////////////
689
/**
690
 * Uses glClearStencil() to set up a value with which to clear the
691
 * Stencil buffer of our Surface at the beginning of each frame.
692
 *
693
 * @param s the Stencil. Default: 0
694
 */
695
  public void glClearStencil(int s)
696
    {
697
    mClearStencil = s;
698
    }
699

    
700
///////////////////////////////////////////////////////////////////////////////////////////////////
701
/**
702
 * Which buffers to Clear at the beginning of each frame?
703
 * <p>
704
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
705
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
706
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
707
 *
708
 * @param mask bitwise OR of BUFFER_BITs to clear.
709
 */
710
  public void glClear(int mask)
711
    {
712
    mClear = mask;
713
    }
714

    
715
///////////////////////////////////////////////////////////////////////////////////////////////////
716
/**
717
 * Create new Projection matrix.
718
 *
719
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
720
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
721
 * @param near The Near plane.
722
 */
723
  public void setProjection(float fov, float near)
724
    {
725
    if( fov < 180.0f && fov >=0.0f )
726
      {
727
      mFOV = fov;
728
      }
729

    
730
    if( near<   1.0f && near> 0.0f )
731
      {
732
      mNear= near;
733
      }
734
    else if( near<=0.0f )
735
      {
736
      mNear = 0.01f;
737
      }
738
    else if( near>=1.0f )
739
      {
740
      mNear=0.99f;
741
      }
742

    
743
    for(int j=0; j<EffectQuality.LENGTH; j++)
744
      {
745
      if( mBuffer[j]!=null ) mBuffer[j].mNear = mNear;
746
      }
747

    
748
    createProjection();
749
    }
750

    
751
///////////////////////////////////////////////////////////////////////////////////////////////////
752
/**
753
 * Return the vertical field of view angle.
754
 *
755
 * @return Vertival Field of View Angle, in degrees.
756
 */
757
  public float getFOV()
758
    {
759
    return mFOV;
760
    }
761

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

    
778
      createProjection();
779

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

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

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

    
810
///////////////////////////////////////////////////////////////////////////////////////////////////
811
/**
812
 * When rendering this Node, should we use the Order Independent Transparency render mode?
813
 * <p>
814
 * There are two modes of rendering: the fast 'normal' way, which however renders transparent
815
 * fragments in different ways depending on which fragments get rendered first, or the slower
816
 * 'oit' way, which renders transparent fragments correctly regardless of their order.
817
 *
818
 * @param oit True if we want to render more slowly, but in a way which accounts for transparency.
819
 */
820
  public void setOrderIndependentTransparency(boolean oit)
821
    {
822
    mRenderWayOIT = oit;
823
    }
824

    
825
///////////////////////////////////////////////////////////////////////////////////////////////////
826
/**
827
 * When rendering this Node, should we use the Order Independent Transparency render mode?
828
 * <p>
829
 * There are two modes of rendering: the fast 'normal' way, which however renders transparent
830
 * fragments in different ways depending on which fragments get rendered first, or the slower
831
 * 'oit' way, which renders transparent fragments correctly regardless of their order.
832
 *
833
 * @param oit True if we want to render more slowly, but in a way which accounts for transparency.
834
 * @param initialSize Initial number of transparent fragments we expect, in screenfuls.
835
 *                    I.e '1.0' means 'the scene we are going to render contains dialog_about 1 screen
836
 *                    worth of transparent fragments'. Valid values: 0.0 &lt; initialSize &lt; 10.0
837
 *                    Even if you get this wrong, the library will detect that there are more
838
 *                    transparent fragments than it has space for and readjust its internal buffers,
839
 *                    but only after a few frames during which one will probably see missing objects.
840
 */
841
  public void setOrderIndependentTransparency(boolean oit, float initialSize)
842
    {
843
    mRenderWayOIT = oit;
844

    
845
    if( initialSize>0.0f && initialSize<10.0f )
846
      {
847
      DistortedLibrary.setSSBOSize(initialSize);
848
      }
849
    }
850

    
851
///////////////////////////////////////////////////////////////////////////////////////////////////
852
/**
853
 * Adds a new child to the last position in the list of our Surface's children.
854
 * <p>
855
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
856
 * InternalMaster (by calling doWork())
857
 *
858
 * @param node The new Node to add.
859
 */
860
  public void attach(DistortedNode node)
861
    {
862
    mChildren.attach(node);
863
    }
864

    
865
///////////////////////////////////////////////////////////////////////////////////////////////////
866
/**
867
 * Adds a new child to the last position in the list of our Surface's children.
868
 * <p>
869
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
870
 * InternalMaster (by calling doWork())
871
 *
872
 * @param surface InputSurface to initialize our child Node with.
873
 * @param effects DistortedEffects to initialize our child Node with.
874
 * @param mesh MeshBase to initialize our child Node with.
875
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
876
 */
877
  public DistortedNode attach(InternalSurface surface, DistortedEffects effects, MeshBase mesh)
878
    {
879
    return mChildren.attach(surface,effects,mesh);
880
    }
881

    
882
///////////////////////////////////////////////////////////////////////////////////////////////////
883
/**
884
 * Removes the first occurrence of a specified child from the list of children of our Surface.
885
 * <p>
886
 * A bit questionable method as there can be many different Nodes attached as children, some
887
 * of them having the same Effects but - for instance - different Mesh. Use with care.
888
 * <p>
889
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
890
 * InternalMaster (by calling doWork())
891
 *
892
 * @param effects DistortedEffects to remove.
893
 */
894
  public void detach(DistortedEffects effects)
895
    {
896
    mChildren.detach(effects);
897
    }
898

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

    
913
///////////////////////////////////////////////////////////////////////////////////////////////////
914
/**
915
 * Removes all children Nodes.
916
 * <p>
917
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
918
 * InternalMaster (by calling doWork())
919
 */
920
  public void detachAll()
921
    {
922
    mChildren.detachAll();
923
    }
924

    
925
///////////////////////////////////////////////////////////////////////////////////////////////////
926
/**
927
 * Return the width of this Surface.
928
 *
929
 * @return width of the Object, in pixels.
930
 */
931
  public int getWidth()
932
    {
933
    return mWidth;
934
    }
935

    
936
///////////////////////////////////////////////////////////////////////////////////////////////////
937
/**
938
 * Return the height of this Surface.
939
 *
940
 * @return height of the Object, in pixels.
941
 */
942
  public int getHeight()
943
    {
944
    return mHeight;
945
    }
946
}
(12-12/14)