Project

General

Profile

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

library / src / main / java / org / distorted / library / main / InternalOutputSurface.java @ f953bee0

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++) numRenders += lastQueue.preprocess( buffer,children.getChild(j), buffer.mDistance, buffer.mMipmap, buffer.mProjectionMatrix );
428
            numRenders += lastQueue.postprocess(buffer);
429

    
430
            if( oit )
431
              {
432
              numRenders += oitBuild(time, buffer, fbo);
433
              GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
434
              }
435
            else
436
              {
437
              numRenders += blitWithDepth(time, buffer, fbo);
438
              }
439
            buffer.clearBuffer(fbo);
440
            }
441

    
442
          buffer= mBuffer[currQueue.getQuality()];
443
          bucketChange= i;
444
          renderDirectly = currQueue.getRender();
445
          }
446

    
447
        if( renderDirectly )
448
          {
449
          setAsOutput(time);
450

    
451
          if( oit )
452
            {
453
            numRenders += child.drawOIT(time, this);
454
            GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
455
            }
456
          else
457
            {
458
            numRenders += child.draw(time, this);
459
            }
460
          }
461
        else
462
          {
463
          buffer.setAsOutput(time);
464
          child.drawNoBlend(time, buffer);
465
          }
466

    
467
        if( i==numChildren-1 )
468
          {
469
          for(int j=bucketChange; j<numChildren; j++) numRenders += currQueue.preprocess( buffer,children.getChild(j), buffer.mDistance, buffer.mMipmap, buffer.mProjectionMatrix );
470
          numRenders += currQueue.postprocess(buffer);
471

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

    
485
      lastQueue = currQueue;
486
      lastBucket= currBucket;
487
      } // end main for loop
488

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

    
494
    return numRenders;
495
    }
496

    
497
///////////////////////////////////////////////////////////////////////////////////////////////////
498
/**
499
 * Not part of the public API.
500
 *
501
 * @y.exclude
502
 */
503
  public void adjustIsomorphism() { }
504

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

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

    
527
///////////////////////////////////////////////////////////////////////////////////////////////////
528

    
529
  void clearBuffer(int fbo)
530
    {
531
    InternalRenderState.colorDepthStencilOn();
532

    
533
    GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
534
    GLES31.glClearDepthf(mClearDepth);
535
    GLES31.glClearStencil(mClearStencil);
536

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

    
543
    InternalRenderState.colorDepthStencilRestore();
544
    }
545

    
546
///////////////////////////////////////////////////////////////////////////////////////////////////
547

    
548
  void setAsOutput(long time)
549
    {
550
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
551

    
552
    if( mTime[mCurrFBO]!=time )
553
      {
554
      mTime[mCurrFBO] = time;
555
      clear();
556
      }
557
    }
558

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

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

    
591
    int numRenders=0, numChildren = mChildren.getNumChildren();
592
    DistortedNode node;
593
    long oldBucket=0, newBucket;
594

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

    
604
    numRenders += renderChildren(time,numChildren,mChildren,fbo, mRenderWayOIT);
605

    
606
    return numRenders;
607
    }
608

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

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

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

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

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

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

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

    
712
///////////////////////////////////////////////////////////////////////////////////////////////////
713
/**
714
 * Create new Projection matrix.
715
 *
716
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
717
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
718
 * @param near Distance between the screen plane and the near plane.
719
 *             Valid vaules: 0<near<1. When near==0 (illegal!), the Near Plane is exactly at the tip of
720
 *             the pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
721
 */
722
  public void setProjection(float fov, float near)
723
    {
724
    if( fov < 180.0f && fov >=0.0f )
725
      {
726
      mFOV = fov;
727
      }
728

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

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

    
747
    createProjection();
748
    }
749

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

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

    
777
      createProjection();
778

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

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

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

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

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

    
844
  if( initialSize>0.0f && initialSize<10.0f )
845
    DistortedLibrary.setSSBOSize(initialSize);
846
  }
847

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

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

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

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

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