Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedOutputSurface.java @ 27cd6b98

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

    
27
import java.nio.ByteBuffer;
28
import java.nio.ByteOrder;
29
import java.nio.IntBuffer;
30
import java.util.ArrayList;
31

    
32
///////////////////////////////////////////////////////////////////////////////////////////////////
33
/**
34
 * This is not really part of the public API.
35
 *
36
 * @y.exclude
37
 */
38
public abstract class DistortedOutputSurface extends DistortedSurface implements DistortedMaster.Slave
39
{
40
//////////// DEBUG FLAGS /////////////////////////////////////////////
41
/**
42
 * When rendering a Screen, show FPS in the upper-left corner?
43
 */
44
public static final int DEBUG_FPS = 1;
45
//////////// END DEBUG FLAGS /////////////////////////////////////////
46

    
47
/**
48
 * Do not create DEPTH or STENCIL attachment
49
 */
50
  public static final int NO_DEPTH_NO_STENCIL = 0;
51
/**
52
 * Create DEPTH, but not STENCIL
53
 */
54
  public static final int DEPTH_NO_STENCIL    = 1;
55
/**
56
 * Create both DEPTH and STENCIL
57
 */
58
  public static final int BOTH_DEPTH_STENCIL  = 2;
59

    
60
  private static final int ATTACH = 0;
61
  private static final int DETACH = 1;
62
  private static final int DETALL = 2;
63
  private static final int SORT   = 3;
64

    
65
  private ArrayList<DistortedNode> mChildren;
66
  private int mNumChildren;   // ==mChildren.length(), but we only create mChildren if the first one gets added
67

    
68
  private class Job
69
    {
70
    int type;
71
    DistortedNode node;
72

    
73
    Job(int t, DistortedNode n)
74
      {
75
      type = t;
76
      node = n;
77
      }
78
    }
79

    
80
  private ArrayList<Job> mJobs = new ArrayList<>();
81

    
82
  DistortedOutputSurface[] mBuffer;
83

    
84
  private long mTime;
85
  private float mFOV;
86
  float mDistance, mNear;
87
  float[] mProjectionMatrix;
88

    
89
  int mDepthStencilCreated;
90
  int mDepthStencil;
91
  int[] mDepthStencilH = new int[1];
92
  int[] mFBOH          = new int[1];
93

    
94
  private float mClearR, mClearG, mClearB, mClearA;
95
  private float mClearDepth;
96
  private int mClearStencil;
97
  private int mClear;
98
  float mMipmap;
99

    
100
  private int mDebugLevel;
101

    
102
  ////////////////////////////////////////////////////////////////////////////////
103
  // section dealing with Shader Storage Buffer Object (for counting transparency)
104
  private static final int BUFFERING = 3;
105
  private static int mBufferSize     =10;
106
  private static DistortedObjectCounter mSurfaceCounter = new DistortedObjectCounter();
107
  private static int[] mSSBO = new int[1];
108
  private static IntBuffer mIntBuffer;
109

    
110
  static
111
    {
112
    mSSBO[0]= -1;
113
    }
114

    
115
  private int mSurfaceID;
116
  private int mLastIndex;
117
  // end section
118
  ////////////////////////////////////////////////////////////////////////////////
119

    
120
///////////////////////////////////////////////////////////////////////////////////////////////////
121

    
122
  abstract void prepareDebug(long time);
123
  abstract void renderDebug(long time);
124
  abstract void createSurface();
125
  abstract void deleteSurface();
126
  abstract void recreateSurface();
127

    
128
///////////////////////////////////////////////////////////////////////////////////////////////////
129

    
130
  DistortedOutputSurface(int width, int height, int createColor, int numcolors, int depthStencil, int fbo, int type)
131
    {
132
    super(width,height,createColor,numcolors,type);
133

    
134
    mProjectionMatrix = new float[16];
135

    
136
    mFOV = 60.0f;
137
    mNear=  0.5f;
138

    
139
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
140
    mDepthStencil = depthStencil;
141

    
142
    mFBOH[0]         = fbo;
143
    mDepthStencilH[0]= 0;
144

    
145
    mTime = 0;
146
    mDebugLevel = 0;
147

    
148
    mClearR = 0.0f;
149
    mClearG = 0.0f;
150
    mClearB = 0.0f;
151
    mClearA = 0.0f;
152

    
153
    mClearDepth = 1.0f;
154
    mClearStencil = 0;
155
    mClear = GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_COLOR_BUFFER_BIT;
156

    
157
    mBuffer = new DistortedOutputSurface[1+EffectQuality.LENGTH];
158

    
159
    mMipmap = 1.0f;
160

    
161
    createProjection();
162
    }
163

    
164
///////////////////////////////////////////////////////////////////////////////////////////////////
165
// Must be called from a thread holding OpenGL Context
166

    
167
  void create()
168
    {
169
    if( mSSBO[0]<0 )
170
      {
171
      GLES31.glGenBuffers(1,mSSBO,0);
172

    
173
      // here bind the new SSBO and map it
174
      GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mSSBO[0]);
175
      GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, BUFFERING*mBufferSize*4 , null, GLES31.GL_DYNAMIC_READ);
176
      ByteBuffer buf = (ByteBuffer) GLES31.glMapBufferRange(GLES31.GL_SHADER_STORAGE_BUFFER, 0, BUFFERING*mBufferSize*4, GLES31.GL_MAP_READ_BIT );
177
      mIntBuffer = buf.order(ByteOrder.nativeOrder()).asIntBuffer();
178
      GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER,0, mSSBO[0]);
179
      }
180

    
181
    mSurfaceID = mSurfaceCounter.returnNext();
182

    
183
    if( mSurfaceID>=mBufferSize )
184
      {
185
      // increase the size of mSSBOBuffer, copy over old values, remap.
186
      // TODO (don't need this if there are never more than mBufferSize=10 Surfaces)
187
      }
188

    
189
    createSurface();
190
    }
191

    
192
///////////////////////////////////////////////////////////////////////////////////////////////////
193
// Must be called from a thread holding OpenGL Context
194

    
195
  void delete()
196
    {
197
    mSurfaceCounter.release(mSurfaceID);
198
    deleteSurface();
199
    }
200

    
201
///////////////////////////////////////////////////////////////////////////////////////////////////
202

    
203
  void recreate()
204
    {
205
    mSSBO[0] = -1;
206
    mSurfaceCounter.releaseAll();
207
    recreateSurface();
208
    }
209

    
210
///////////////////////////////////////////////////////////////////////////////////////////////////
211

    
212
  void debugSSBO()
213
    {
214
    android.util.Log.d("SSBO", mIntBuffer.get(0)+" "+mIntBuffer.get(1)+" "
215
        +mIntBuffer.get(2)+" "+mIntBuffer.get(3) );
216
    }
217

    
218
///////////////////////////////////////////////////////////////////////////////////////////////////
219

    
220
  int resetNewCounter()
221
    {
222
    mIntBuffer.put(BUFFERING*mSurfaceID+mLastIndex,0);
223
    return BUFFERING*mSurfaceID + mLastIndex;
224
    }
225

    
226
///////////////////////////////////////////////////////////////////////////////////////////////////
227

    
228
  int returnOldCounter()
229
    {
230
    int ret = mIntBuffer.get(BUFFERING*mSurfaceID+mLastIndex);
231

    
232
    mLastIndex++;
233
    if( mLastIndex>=BUFFERING ) mLastIndex-=BUFFERING;
234

    
235
    return ret;
236
    }
237

    
238
///////////////////////////////////////////////////////////////////////////////////////////////////
239

    
240
  private void createProjection()
241
    {
242
    if( mWidth>0 && mHeight>1 )
243
      {
244
      if( mFOV>0.0f )  // perspective projection
245
        {
246
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
247
        float q = mWidth*mNear;
248
        float c = mHeight*mNear;
249

    
250
        float left   = -q/2;
251
        float right  = +q/2;
252
        float bottom = -c/2;
253
        float top    = +c/2;
254
        float near   =  c/a;
255

    
256
        mDistance    = mHeight/a;
257
        float far    = 2*mDistance-near;
258

    
259
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
260
        }
261
      else             // parallel projection
262
        {
263
        float left   = -mWidth/2.0f;
264
        float right  = +mWidth/2.0f;
265
        float bottom = -mHeight/2.0f;
266
        float top    = +mHeight/2.0f;
267
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
268
        mDistance    = mWidth+mHeight;
269
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
270

    
271
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
272
        }
273
      }
274
    }
275

    
276
///////////////////////////////////////////////////////////////////////////////////////////////////
277

    
278
  private void createBuffers()
279
    {
280
    float mipmap=1.0f;
281

    
282
    for(int j=0; j<EffectQuality.LENGTH; j++)
283
      {
284
      mBuffer[j] = new DistortedFramebuffer(2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
285
      mBuffer[j].mMipmap = mipmap;
286
      mBuffer[j].mNear   = mNear;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
287
      mBuffer[j].glClearColor(1.0f,1.0f,1.0f,0.0f);
288
      mipmap *= EffectQuality.MULTIPLIER;
289
      }
290

    
291
    mBuffer[EffectQuality.LENGTH] = this;
292

    
293
    DistortedObject.toDo(); // create the FBOs immediately. This is safe as we must be holding the OpenGL context now.
294

    
295
    GLES31.glStencilMask(0xff);
296
    GLES31.glDepthMask(true);
297
    GLES31.glColorMask(true,true,true,true);
298
    GLES31.glClearColor(0.0f,0.0f,0.0f,0.0f);
299
    GLES31.glClearDepthf(1.0f);
300
    GLES31.glClearStencil(0);
301

    
302
    for(int j=0; j<EffectQuality.LENGTH; j++)
303
      {
304
      mBuffer[j].setAsOutput();
305
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[1], 0);
306
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
307
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[0], 0);
308
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
309
      }
310
    }
311

    
312
///////////////////////////////////////////////////////////////////////////////////////////////////
313

    
314
  private int blitWithDepth(long currTime, DistortedOutputSurface buffer)
315
    {
316
    GLES31.glViewport(0, 0, mWidth, mHeight);
317
    setAsOutput(currTime);
318
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
319
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[0]);
320
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
321
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[0]);
322

    
323
    GLES31.glDisable(GLES31.GL_STENCIL_TEST);
324
    GLES31.glStencilMask(0x00);
325

    
326
    DistortedEffects.blitDepthPriv(this);
327
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
328
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
329
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
330
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
331

    
332
    // clear buffers
333
    GLES31.glStencilMask(0xff);
334
    GLES31.glDepthMask(true);
335
    GLES31.glColorMask(true,true,true,true);
336
    GLES31.glClearColor(0.0f,0.0f,0.0f,0.0f);
337
    GLES31.glClearDepthf(1.0f);
338
    GLES31.glClearStencil(0);
339

    
340
    buffer.setAsOutput();
341
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[1], 0);
342
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
343
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[0], 0);
344
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
345

    
346
    return 1;
347
    }
348

    
349
///////////////////////////////////////////////////////////////////////////////////////////////////
350
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
351
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
352
// to a whole buffer and merge it.
353

    
354
  int renderChildren(long time, int numChildren, ArrayList<DistortedNode> children)
355
    {
356
    int quality=0, internalQuality = 0, numRenders = 0, bucketChange = 0;
357
    DistortedNode child1, child2;
358
    EffectQueuePostprocess lastQueue=null, currQueue;
359
    long lastBucket=0, currBucket;
360

    
361
    for(int i=0; i<numChildren; i++)
362
      {
363
      child1 = children.get(i);
364
      currQueue = child1.getPostprocessQueue();
365
      currBucket= currQueue.getID();
366

    
367
      if( currBucket==0 ) numRenders += child1.draw(time,this);
368
      else
369
        {
370
        if( mBuffer[0]==null ) createBuffers();
371

    
372
        if( lastBucket!=currBucket )
373
          {
374
          if( lastBucket!=0 )
375
            {
376
            for(int j=bucketChange; j<i; j++)
377
              {
378
              child2 = children.get(j);
379
              numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],lastQueue);
380
              }
381

    
382
            numRenders += lastQueue.postprocess(this);
383
            numRenders += blitWithDepth(time, mBuffer[quality]);
384
            }
385

    
386
          internalQuality = currQueue.getInternalQuality();
387
          quality         = currQueue.getQuality();
388
          bucketChange    = i;
389
          }
390

    
391
        child1.draw(time,mBuffer[quality]);
392
        //numRenders += currQueue.draw(child1,time,mBuffer);
393

    
394
        if( i==numChildren-1 )
395
          {
396
          for(int j=bucketChange; j<numChildren; j++)
397
            {
398
            child2 = children.get(j);
399
            numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],currQueue);
400
            }
401

    
402
          numRenders += currQueue.postprocess(this);
403
          numRenders += blitWithDepth(time, mBuffer[quality]);
404
          }
405
        }
406

    
407
      lastQueue = currQueue;
408
      lastBucket= currBucket;
409
      }
410

    
411
    return numRenders;
412
    }
413

    
414
///////////////////////////////////////////////////////////////////////////////////////////////////
415

    
416
  ArrayList<DistortedNode> getChildren()
417
    {
418
    return mChildren;
419
    }
420

    
421
///////////////////////////////////////////////////////////////////////////////////////////////////
422
// PUBLIC API
423
///////////////////////////////////////////////////////////////////////////////////////////////////
424
/**
425
 * Make the library show various debugging information.
426
 * <p>
427
 * Currently only DEBUG_FPS - show FPS in the upper-left corner of every Screen - is defined.
428
 *
429
 * @param bitmask 0, or a bitmask of DEBUG_** flags to enable (currently only DEBUG_FPS defined)
430
 */
431
  public void setDebug(int bitmask)
432
    {
433
    if( this instanceof DistortedScreen )
434
      mDebugLevel = bitmask;
435
    }
436

    
437
///////////////////////////////////////////////////////////////////////////////////////////////////
438

    
439
/**
440
 * Draws all the attached children to this OutputSurface.
441
 * <p>
442
 * Must be called from a thread holding OpenGL Context.
443
 *
444
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
445
 * @return Number of objects rendered.
446
 */
447
  public int render(long time)
448
    {
449
    if( mDebugLevel!=0 ) prepareDebug(time);
450

    
451
    // change tree topology (attach and detach children)
452
/*
453
    boolean changed1 =
454
*/
455
    DistortedMaster.toDo();
456
/*
457
    if( changed1 )
458
      {
459
      for(int i=0; i<mNumChildren; i++)
460
        {
461
        mChildren.get(i).debug(0);
462
        }
463

    
464
      DistortedNode.debugMap();
465
      }
466
*/
467
    // create and delete all underlying OpenGL resources
468
    // Watch out: FIRST change topology, only then deal
469
    // with OpenGL resources. That's because changing Tree
470
    // can result in additional Framebuffers that would need
471
    // to be created immediately, before the calls to drawRecursive()
472
/*
473
    boolean changed2 =
474
*/
475
    toDo();
476
/*
477
    if( changed2 )
478
      {
479
      DistortedObject.debugLists();
480
      }
481
*/
482
    // mark OpenGL state as unknown
483
    DistortedRenderState.reset();
484

    
485
    int numRenders=0;
486

    
487
    for(int i=0; i<mNumChildren; i++)
488
      {
489
      numRenders += mChildren.get(i).renderRecursive(time);
490
      }
491

    
492
    setAsOutput(time);
493
    numRenders += renderChildren(time,mNumChildren,mChildren);
494

    
495
    if( mDebugLevel != 0 ) renderDebug(time);
496

    
497
    return numRenders;
498
    }
499

    
500
///////////////////////////////////////////////////////////////////////////////////////////////////
501
/**
502
 * Bind this Surface as a Framebuffer we can render to.
503
 *
504
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
505
 *             out if this is the first time during present frame that this FBO is being set as output.
506
 *             If so, the library, in addition to binding the Surface for output, also clears the
507
 *             Surface's color and depth attachments.
508
 */
509
  public void setAsOutput(long time)
510
    {
511
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[0]);
512

    
513
    if( mTime!=time )
514
      {
515
      mTime = time;
516
      DistortedRenderState.colorDepthStencilOn();
517
      GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
518
      GLES31.glClearDepthf(mClearDepth);
519
      GLES31.glClearStencil(mClearStencil);
520
      GLES31.glClear(mClear);
521
      DistortedRenderState.colorDepthStencilRestore();
522
      }
523
    }
524

    
525
///////////////////////////////////////////////////////////////////////////////////////////////////
526
/**
527
 * Bind this Surface as a Framebuffer we can render to.
528
 * <p>
529
 * This version does not attempt to clear anything.
530
 */
531

    
532
  public void setAsOutput()
533
    {
534
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[0]);
535
    }
536

    
537
///////////////////////////////////////////////////////////////////////////////////////////////////
538
/**
539
 * Return the Near plane of the Projection included in the Surface.
540
 *
541
 * @return the Near plane.
542
 */
543
  public float getNear()
544
    {
545
    return mNear;
546
    }
547

    
548
///////////////////////////////////////////////////////////////////////////////////////////////////
549
/**
550
 * Set mipmap level.
551
 * <p>
552
 * Trick for speeding up your renders - one can create a pyramid of OutputSurface objects, each next
553
 * one some constant FACTOR smaller than the previous (0.5 is the common value), then set the Mipmap
554
 * Level of the i-th object to be FACTOR^i (we start counting from 0). When rendering any scene into
555
 * such prepared OutputSurface, the library will make sure to scale any Effects used so that the end
556
 * scene will end up looking identical no matter which object we render to. Identical, that is, except
557
 * for the loss of quality and gain in speed associated with rendering to a smaller Surface.
558
 * <p>
559
 * Example: if you create two FBOs, one 1000x1000 and another 500x500 in size, and set the second one
560
 * mipmap to 0.5 (the first one's is 1.0 by default), define Effects to be a single move by (100,100),
561
 * and render a skinned Mesh into both FBO, the end result will look proportionally the same, because
562
 * in the second case the move vector (100,100) will be auto-scaled to (50,50).
563
 *
564
 * @param mipmap The mipmap level. Acceptable range: 0&lt;mipmap&lt;infinity, although mipmap&gt;1
565
 *               does not make any sense (that would result in loss of speed and no gain in quality)
566
 */
567
  public void setMipmap(float mipmap)
568
    {
569
    mMipmap = mipmap;
570
    }
571

    
572
///////////////////////////////////////////////////////////////////////////////////////////////////
573
/**
574
 * Set the (R,G,B,A) values of GLES31.glClearColor() to set up color with which to clear
575
 * this Surface at the beginning of each frame.
576
 *
577
 * @param r the Red component. Default: 0.0f
578
 * @param g the Green component. Default: 0.0f
579
 * @param b the Blue component. Default: 0.0f
580
 * @param a the Alpha component. Default: 0.0f
581
 */
582
  public void glClearColor(float r, float g, float b, float a)
583
    {
584
    mClearR = r;
585
    mClearG = g;
586
    mClearB = b;
587
    mClearA = a;
588
    }
589

    
590
///////////////////////////////////////////////////////////////////////////////////////////////////
591
/**
592
 * Uses glClearDepthf() to set up a value with which to clear
593
 * the Depth buffer of our Surface at the beginning of each frame.
594
 *
595
 * @param d the Depth. Default: 1.0f
596
 */
597
  public void glClearDepthf(float d)
598
    {
599
    mClearDepth = d;
600
    }
601

    
602
///////////////////////////////////////////////////////////////////////////////////////////////////
603
/**
604
 * Uses glClearStencil() to set up a value with which to clear the
605
 * Stencil buffer of our Surface at the beginning of each frame.
606
 *
607
 * @param s the Stencil. Default: 0
608
 */
609
  public void glClearStencil(int s)
610
    {
611
    mClearStencil = s;
612
    }
613

    
614
///////////////////////////////////////////////////////////////////////////////////////////////////
615
/**
616
 * Which buffers to Clear at the beginning of each frame?
617
 * <p>
618
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
619
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
620
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
621
 *
622
 * @param mask bitwise OR of BUFFER_BITs to clear.
623
 */
624
  public void glClear(int mask)
625
    {
626
    mClear = mask;
627
    }
628

    
629
///////////////////////////////////////////////////////////////////////////////////////////////////
630
/**
631
 * Create new Projection matrix.
632
 *
633
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
634
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
635
 * @param near Distance between the screen plane and the near plane.
636
 *             Valid vaules: 0<near<1. When near==0, the Near Plane is exactly at the tip of the
637
 *             pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
638
 */
639
  public void setProjection(float fov, float near)
640
    {
641
    if( fov < 180.0f && fov >=0.0f )
642
      {
643
      mFOV = fov;
644
      }
645

    
646
    if( near<   1.0f && near> 0.0f )
647
      {
648
      mNear= near;
649
      }
650
    else if( near<=0.0f )
651
      {
652
      mNear = 0.01f;
653
      }
654
    else if( near>=1.0f )
655
      {
656
      mNear=0.99f;
657
      }
658

    
659
    if( mBuffer[0]!=null )
660
      {
661
      for(int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].mNear = mNear;
662
      }
663

    
664
    createProjection();
665
    }
666

    
667
///////////////////////////////////////////////////////////////////////////////////////////////////
668
/**
669
 * Resize the underlying Framebuffer.
670
 * <p>
671
 * This method can be safely called mid-render as it doesn't interfere with rendering.
672
 *
673
 * @param width The new width.
674
 * @param height The new height.
675
 */
676
  public void resize(int width, int height)
677
    {
678
    if( mWidth!=width || mHeight!=height )
679
      {
680
      mWidth = width;
681
      mHeight= height;
682

    
683
      createProjection();
684

    
685
      if( mColorCreated==CREATED )
686
        {
687
        markForCreation();
688
        recreate();
689
        }
690
      }
691
    }
692

    
693
///////////////////////////////////////////////////////////////////////////////////////////////////
694
/**
695
 * Return true if the Surface contains a DEPTH attachment.
696
 *
697
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
698
 */
699
  public boolean hasDepth()
700
    {
701
    return mDepthStencilCreated==CREATED;
702
    }
703

    
704
///////////////////////////////////////////////////////////////////////////////////////////////////
705
/**
706
 * Return true if the Surface contains a STENCIL attachment.
707
 *
708
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
709
 */
710
  public boolean hasStencil()
711
    {
712
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
713
    }
714

    
715
///////////////////////////////////////////////////////////////////////////////////////////////////
716
/**
717
 * Adds a new child to the last position in the list of our Surface's children.
718
 * <p>
719
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
720
 * DistortedMaster (by calling doWork())
721
 *
722
 * @param node The new Node to add.
723
 */
724
  public void attach(DistortedNode node)
725
    {
726
    mJobs.add(new Job(ATTACH,node));
727
    DistortedMaster.newSlave(this);
728
    }
729

    
730
///////////////////////////////////////////////////////////////////////////////////////////////////
731
/**
732
 * Adds a new child to the last position in the list of our Surface's children.
733
 * <p>
734
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
735
 * DistortedMaster (by calling doWork())
736
 *
737
 * @param surface InputSurface to initialize our child Node with.
738
 * @param effects DistortedEffects to initialize our child Node with.
739
 * @param mesh MeshObject to initialize our child Node with.
740
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
741
 */
742
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
743
    {
744
    DistortedNode node = new DistortedNode(surface,effects,mesh);
745
    mJobs.add(new Job(ATTACH,node));
746
    DistortedMaster.newSlave(this);
747
    return node;
748
    }
749

    
750
///////////////////////////////////////////////////////////////////////////////////////////////////
751
/**
752
 * Removes the first occurrence of a specified child from the list of children of our Surface.
753
 * <p>
754
 * A bit questionable method as there can be many different Nodes attached as children, some
755
 * of them having the same Effects but - for instance - different Mesh. Use with care.
756
 * <p>
757
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
758
 * DistortedMaster (by calling doWork())
759
 *
760
 * @param effects DistortedEffects to remove.
761
 */
762
  public void detach(DistortedEffects effects)
763
    {
764
    long id = effects.getID();
765
    DistortedNode node;
766
    boolean detached = false;
767

    
768
    for(int i=0; i<mNumChildren; i++)
769
      {
770
      node = mChildren.get(i);
771

    
772
      if( node.getEffects().getID()==id )
773
        {
774
        detached = true;
775
        mJobs.add(new Job(DETACH,node));
776
        DistortedMaster.newSlave(this);
777
        break;
778
        }
779
      }
780

    
781
    if( !detached )
782
      {
783
      // if we failed to detach any, it still might be the case that
784
      // there's an ATTACH job that we need to cancel.
785
      int num = mJobs.size();
786
      Job job;
787

    
788
      for(int i=0; i<num; i++)
789
        {
790
        job = mJobs.get(i);
791

    
792
        if( job.type==ATTACH && job.node.getEffects()==effects )
793
          {
794
          mJobs.remove(i);
795
          break;
796
          }
797
        }
798
      }
799
    }
800

    
801
///////////////////////////////////////////////////////////////////////////////////////////////////
802
/**
803
 * Removes the first occurrence of a specified child from the list of children of our Surface.
804
 * <p>
805
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
806
 * DistortedMaster (by calling doWork())
807
 *
808
 * @param node The Node to remove.
809
 */
810
  public void detach(DistortedNode node)
811
    {
812
    mJobs.add(new Job(DETACH,node));
813
    DistortedMaster.newSlave(this);
814
    }
815

    
816
///////////////////////////////////////////////////////////////////////////////////////////////////
817
/**
818
 * Removes all children Nodes.
819
 * <p>
820
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
821
 * DistortedMaster (by calling doWork())
822
 */
823
  public void detachAll()
824
    {
825
    mJobs.add(new Job(DETALL,null));
826
    DistortedMaster.newSlave(this);
827
    }
828

    
829
///////////////////////////////////////////////////////////////////////////////////////////////////
830
/**
831
 * This is not really part of the public API. Has to be public only because it is a part of the
832
 * DistortedSlave interface, which should really be a class that we extend here instead but
833
 * Java has no multiple inheritance.
834
 *
835
 * @y.exclude
836
 */
837
  public void doWork()
838
    {
839
    int num = mJobs.size();
840
    Job job;
841

    
842
    for(int i=0; i<num; i++)
843
      {
844
      job = mJobs.remove(0);
845

    
846
      switch(job.type)
847
        {
848
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
849
                     job.node.setSurfaceParent(this);
850
                     DistortedMaster.addSorted(mChildren,job.node);
851
                     mNumChildren++;
852
                     break;
853
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
854
                       {
855
                       job.node.setSurfaceParent(null);
856
                       mNumChildren--;
857
                       }
858
                     break;
859
        case DETALL: if( mNumChildren>0 )
860
                       {
861
                       DistortedNode tmp;
862

    
863
                       for(int j=mNumChildren-1; j>=0; j--)
864
                         {
865
                         tmp = mChildren.remove(j);
866
                         tmp.setSurfaceParent(null);
867
                         }
868

    
869
                       mNumChildren = 0;
870
                       }
871
                     break;
872
        case SORT  : mChildren.remove(job.node);
873
                     DistortedMaster.addSorted(mChildren,job.node);
874
                     break;
875
        }
876
      }
877
    }
878
}
(9-9/22)