Project

General

Profile

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

library / src / main / java / org / distorted / library / DistortedOutputSurface.java @ 5c83f4b4

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;
21

    
22
import android.opengl.GLES30;
23
import android.opengl.Matrix;
24
import java.util.ArrayList;
25

    
26
///////////////////////////////////////////////////////////////////////////////////////////////////
27

    
28
abstract class DistortedOutputSurface extends DistortedSurface implements DistortedSlave
29
{
30
/**
31
 * Do not create DEPTH or STENCIL attachment
32
 */
33
  public static final int NO_DEPTH_NO_STENCIL = 0;
34
/**
35
 * Create DEPTH, but not STENCIL
36
 */
37
  public static final int DEPTH_NO_STENCIL    = 1;
38
/**
39
 * Create both DEPTH and STENCIL
40
 */
41
  public static final int BOTH_DEPTH_STENCIL  = 2;
42

    
43
  private static final int ATTACH = 0;
44
  private static final int DETACH = 1;
45
  private static final int DETALL = 2;
46
  private static final int SORT   = 3;
47

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

    
51
  private class Job
52
    {
53
    int type;
54
    DistortedNode node;
55
    DistortedEffectsPostprocess dep;
56

    
57
    Job(int t, DistortedNode n, DistortedEffectsPostprocess d)
58
      {
59
      type = t;
60
      node = n;
61
      dep  = d;
62
      }
63
    }
64

    
65
  private ArrayList<Job> mJobs = new ArrayList<>();
66

    
67
  DistortedFramebuffer[] mBuffer1, mBuffer2;
68

    
69
  private long mTime;
70
  private float mFOV;
71
  float mDistance, mNear;
72
  float[] mProjectionMatrix;
73

    
74
  int mDepthStencilCreated;
75
  int mDepthStencil;
76
  int[] mDepthStencilH = new int[1];
77
  int[] mFBOH          = new int[1];
78

    
79
  private float mClearR, mClearG, mClearB, mClearA;
80
  private float mClearDepth;
81
  private int mClearStencil;
82
  private int mClear;
83
  float mMipmap;
84

    
85
///////////////////////////////////////////////////////////////////////////////////////////////////
86

    
87
  DistortedOutputSurface(int width, int height, int createColor, int depthStencil, int fbo, int type)
88
    {
89
    super(width,height,createColor,type);
90

    
91
    mProjectionMatrix = new float[16];
92

    
93
    mFOV = 60.0f;
94
    mNear=  0.5f;
95

    
96
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
97
    mDepthStencil = depthStencil;
98

    
99
    mFBOH[0]         = fbo;
100
    mDepthStencilH[0]= 0;
101

    
102
    mTime = 0;
103

    
104
    mClearR = 0.0f;
105
    mClearG = 0.0f;
106
    mClearB = 0.0f;
107
    mClearA = 0.0f;
108

    
109
    mClearDepth = 1.0f;
110
    mClearStencil = 0;
111
    mClear = GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT;
112

    
113
    mBuffer1 = new DistortedFramebuffer[EffectQuality.LENGTH];
114
    mBuffer2 = new DistortedFramebuffer[EffectQuality.LENGTH];
115

    
116
    mMipmap = 1.0f;
117

    
118
    createProjection();
119
    }
120

    
121
///////////////////////////////////////////////////////////////////////////////////////////////////
122

    
123
  private void createProjection()
124
    {
125
    if( mWidth>0 && mHeight>1 )
126
      {
127
      if( mFOV>0.0f )  // perspective projection
128
        {
129
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
130
        float q = mWidth*mNear;
131
        float c = mHeight*mNear;
132

    
133
        float left   = -q/2;
134
        float right  = +q/2;
135
        float bottom = -c/2;
136
        float top    = +c/2;
137
        float near   =  c/a;
138

    
139
        mDistance    = mHeight/a;
140
        float far    = 2*mDistance-near;
141

    
142
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
143
        }
144
      else             // parallel projection
145
        {
146
        float left   = -mWidth/2.0f;
147
        float right  = +mWidth/2.0f;
148
        float bottom = -mHeight/2.0f;
149
        float top    = +mHeight/2.0f;
150
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
151
        mDistance    = mWidth+mHeight;
152
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
153

    
154
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
155
        }
156
      }
157
    }
158

    
159
///////////////////////////////////////////////////////////////////////////////////////////////////
160
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
161
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
162
// to a whole buffer and merge it.
163

    
164
  int renderChildren(long time, int num, ArrayList<DistortedNode> children)
165
    {
166
    int numRenders = 0;
167
    DistortedNode child;
168
    DistortedEffectsPostprocess lastP=null, currP;
169
    long lastB=0, currB;
170

    
171
    for(int i=0; i<num; i++)
172
      {
173
      child = children.get(i);
174
      currP = child.getEffectsPostprocess();
175
      currB = currP==null ? 0 : currP.getBucket();
176

    
177
      if( lastB!=currB && lastB!=0 )
178
        {
179
        numRenders += lastP.postprocess(time,this);
180
        }
181

    
182
      if( currB==0 )
183
        {
184
        numRenders += child.draw(time,this);
185
        }
186
      else
187
        {
188
        if( mBuffer1[0]==null )
189
          {
190
          float mipmap=1.0f;
191

    
192
          for(int j=0; j<EffectQuality.LENGTH; j++)
193
            {
194
            mBuffer1[j] = new DistortedFramebuffer(BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
195
            mBuffer2[j] = new DistortedFramebuffer(BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
196
            mBuffer1[j].mMipmap = mipmap;
197
            mipmap *= EffectQuality.MULTIPLIER;
198
            }
199
          DistortedObject.toDo(); // create the FBOs immediately. This is safe as we must be holding the OpenGL context now.
200
          }
201

    
202
        numRenders += child.markStencilAndDraw(time,this,currP.getQuality(),50);
203

    
204
        if( i==num-1 )
205
          {
206
          numRenders += currP.postprocess(time,this);
207
          }
208
        }
209

    
210
      lastP = currP;
211
      lastB = currB;
212
      }
213

    
214
    return numRenders;
215
    }
216

    
217
///////////////////////////////////////////////////////////////////////////////////////////////////
218

    
219
  void newJob(int t, DistortedNode n, DistortedEffectsPostprocess d)
220
    {
221
    mJobs.add(new Job(t,n,d));
222
    }
223

    
224
///////////////////////////////////////////////////////////////////////////////////////////////////
225
// PUBLIC API
226
///////////////////////////////////////////////////////////////////////////////////////////////////
227
/**
228
 * Draws all the attached children to this OutputSurface.
229
 * <p>
230
 * Must be called from a thread holding OpenGL Context.
231
 *
232
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
233
 * @return Number of objects rendered.
234
 */
235
  public int render(long time)
236
    {
237
    // change tree topology (attach and detach children)
238
/*
239
    boolean changed1 =
240
*/
241
    DistortedMaster.toDo();
242
/*
243
    if( changed1 )
244
      {
245
      for(int i=0; i<mNumChildren; i++)
246
        {
247
        mChildren.get(i).debug(0);
248
        }
249

    
250
      DistortedNode.debugMap();
251
      }
252
*/
253
    // create and delete all underlying OpenGL resources
254
    // Watch out: FIRST change topology, only then deal
255
    // with OpenGL resources. That's because changing Tree
256
    // can result in additional Framebuffers that would need
257
    // to be created immediately, before the calls to drawRecursive()
258
/*
259
    boolean changed2 =
260
*/
261
    toDo();
262
/*
263
    if( changed2 )
264
      {
265
      DistortedObject.debugLists();
266
      }
267
*/
268
    // mark OpenGL state as unknown
269
    DistortedRenderState.reset();
270

    
271
    int numRenders=0;
272

    
273
    for(int i=0; i<mNumChildren; i++)
274
      {
275
      numRenders += mChildren.get(i).renderRecursive(time);
276
      }
277

    
278
    setAsOutput(time);
279
    numRenders += renderChildren(time,mNumChildren,mChildren);
280

    
281
    return numRenders;
282
    }
283

    
284
///////////////////////////////////////////////////////////////////////////////////////////////////
285
/**
286
 * Bind this Surface as a Framebuffer we can render to.
287
 *
288
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
289
 *             out if this is the first time during present frame that this FBO is being set as output.
290
 *             If so, the library, in addition to binding the Surface for output, also clears the
291
 *             Surface's color and depth attachments.
292
 */
293
  public void setAsOutput(long time)
294
    {
295
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
296

    
297
    if( mTime!=time )
298
      {
299
      mTime = time;
300
      DistortedRenderState.colorDepthStencilOn();
301
      GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
302
      GLES30.glClearDepthf(mClearDepth);
303
      GLES30.glClearStencil(mClearStencil);
304
      GLES30.glClear(mClear);
305
      }
306
    }
307

    
308
///////////////////////////////////////////////////////////////////////////////////////////////////
309
/**
310
 * Set mipmap level.
311
 * <p>
312
 * Trick for speeding up your renders - one can create a pyramid of OutputSurface objects, each next
313
 * one some constant FACTOR smaller than the previous (0.5 is the common value), then set the Mipmap
314
 * Level of the i-th object to be FACTOR^i (we start counting from 0). When rendering any scene into
315
 * such prepared OutputSurface, the library will make sure to scale any Effects used so that the end
316
 * scene will end up looking identical no matter which object we render to. Identical, that is, except
317
 * for the loss of quality and gain in speed associated with rendering to a smaller Surface.
318
 * <p>
319
 * Example: if you create two FBOs, one 1000x1000 and another 500x500 in size, and set the second one
320
 * mipmap to 0.5 (the first one's is 1.0 by default), define Effects to be a single move by (100,100),
321
 * and render a skinned Mesh into both FBO, the end result will look proportionally the same, because
322
 * in the second case the move vector (100,100) will be auto-scaled to (50,50).
323
 *
324
 * @param mipmap The mipmap level. Acceptable range: 0&lt;mipmap&lt;infinity, although mipmap&gt;1
325
 *               does not make any sense (that would result in loss of speed and no gain in quality)
326
 */
327
  public void setMipmap(float mipmap)
328
    {
329
    mMipmap = mipmap;
330
    }
331

    
332
///////////////////////////////////////////////////////////////////////////////////////////////////
333
/**
334
 * Set the (R,G,B,A) values of GLES30.glClearColor() to set up color with which to clear
335
 * this Surface at the beginning of each frame.
336
 *
337
 * @param r the Red component. Default: 0.0f
338
 * @param g the Green component. Default: 0.0f
339
 * @param b the Blue component. Default: 0.0f
340
 * @param a the Alpha component. Default: 0.0f
341
 */
342
  public void glClearColor(float r, float g, float b, float a)
343
    {
344
    mClearR = r;
345
    mClearG = g;
346
    mClearB = b;
347
    mClearA = a;
348
    }
349

    
350
///////////////////////////////////////////////////////////////////////////////////////////////////
351
/**
352
 * Uses glClearDepthf() to set up a value with which to clear
353
 * the Depth buffer of our Surface at the beginning of each frame.
354
 *
355
 * @param d the Depth. Default: 1.0f
356
 */
357
  public void glClearDepthf(float d)
358
    {
359
    mClearDepth = d;
360
    }
361

    
362
///////////////////////////////////////////////////////////////////////////////////////////////////
363
/**
364
 * Uses glClearStencil() to set up a value with which to clear the
365
 * Stencil buffer of our Surface at the beginning of each frame.
366
 *
367
 * @param s the Stencil. Default: 0
368
 */
369
  public void glClearStencil(int s)
370
    {
371
    mClearStencil = s;
372
    }
373

    
374
///////////////////////////////////////////////////////////////////////////////////////////////////
375
/**
376
 * Which buffers to Clear at the beginning of each frame?
377
 * <p>
378
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
379
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
380
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
381
 *
382
 * @param mask bitwise OR of BUFFER_BITs to clear.
383
 */
384
  public void glClear(int mask)
385
    {
386
    mClear = mask;
387
    }
388

    
389
///////////////////////////////////////////////////////////////////////////////////////////////////
390
/**
391
 * Create new Projection matrix.
392
 *
393
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
394
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
395
 * @param near Distance between the screen plane and the near plane.
396
 *             Valid vaules: 0<near<1. When near==0, the Near Plane is exactly at the tip of the
397
 *             pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
398
 */
399
  public void setProjection(float fov, float near)
400
    {
401
    if( fov < 180.0f && fov >=0.0f )
402
      {
403
      mFOV = fov;
404
      }
405

    
406
    if( near<   1.0f && near> 0.0f )
407
      {
408
      mNear= near;
409
      }
410
    else if( near<=0.0f )
411
      {
412
      mNear = 0.01f;
413
      }
414
    else if( near>=1.0f )
415
      {
416
      mNear=0.99f;
417
      }
418

    
419
    createProjection();
420
    }
421

    
422
///////////////////////////////////////////////////////////////////////////////////////////////////
423
/**
424
 * Resize the underlying Framebuffer.
425
 * <p>
426
 * This method can be safely called mid-render as it doesn't interfere with rendering.
427
 *
428
 * @param width The new width.
429
 * @param height The new height.
430
 */
431
  public void resize(int width, int height)
432
    {
433
    if( mWidth!=width || mHeight!=height )
434
      {
435
      mWidth = width;
436
      mHeight= height;
437

    
438
      createProjection();
439

    
440
      if( mColorCreated==CREATED )
441
        {
442
        markForCreation();
443
        recreate();
444
        }
445
      }
446
    }
447

    
448
///////////////////////////////////////////////////////////////////////////////////////////////////
449
/**
450
 * Return true if the Surface contains a DEPTH attachment.
451
 *
452
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
453
 */
454
  public boolean hasDepth()
455
    {
456
    return mDepthStencilCreated==CREATED;
457
    }
458

    
459
///////////////////////////////////////////////////////////////////////////////////////////////////
460
/**
461
 * Return true if the Surface contains a STENCIL attachment.
462
 *
463
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
464
 */
465
  public boolean hasStencil()
466
    {
467
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
468
    }
469

    
470
///////////////////////////////////////////////////////////////////////////////////////////////////
471
/**
472
 * Adds a new child to the last position in the list of our Surface's children.
473
 * <p>
474
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
475
 * DistortedMaster (by calling doWork())
476
 *
477
 * @param node The new Node to add.
478
 */
479
  public void attach(DistortedNode node)
480
    {
481
    mJobs.add(new Job(ATTACH,node,null));
482
    DistortedMaster.newSlave(this);
483
    }
484

    
485
///////////////////////////////////////////////////////////////////////////////////////////////////
486
/**
487
 * Adds a new child to the last position in the list of our Surface's children.
488
 * <p>
489
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
490
 * DistortedMaster (by calling doWork())
491
 *
492
 * @param surface InputSurface to initialize our child Node with.
493
 * @param effects DistortedEffects to initialize our child Node with.
494
 * @param mesh MeshObject to initialize our child Node with.
495
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
496
 */
497
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
498
    {
499
    DistortedNode node = new DistortedNode(surface,effects,mesh);
500
    mJobs.add(new Job(ATTACH,node,null));
501
    DistortedMaster.newSlave(this);
502
    return node;
503
    }
504

    
505
///////////////////////////////////////////////////////////////////////////////////////////////////
506
/**
507
 * Removes the first occurrence of a specified child from the list of children of our Surface.
508
 * <p>
509
 * A bit questionable method as there can be many different Nodes attached as children, some
510
 * of them having the same Effects but - for instance - different Mesh. Use with care.
511
 * <p>
512
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
513
 * DistortedMaster (by calling doWork())
514
 *
515
 * @param effects DistortedEffects to remove.
516
 */
517
  public void detach(DistortedEffects effects)
518
    {
519
    long id = effects.getID();
520
    DistortedNode node;
521
    boolean detached = false;
522

    
523
    for(int i=0; i<mNumChildren; i++)
524
      {
525
      node = mChildren.get(i);
526

    
527
      if( node.getEffects().getID()==id )
528
        {
529
        detached = true;
530
        mJobs.add(new Job(DETACH,node,null));
531
        DistortedMaster.newSlave(this);
532
        break;
533
        }
534
      }
535

    
536
    if( !detached )
537
      {
538
      // if we failed to detach any, it still might be the case that
539
      // there's an ATTACH job that we need to cancel.
540
      int num = mJobs.size();
541
      Job job;
542

    
543
      for(int i=0; i<num; i++)
544
        {
545
        job = mJobs.get(i);
546

    
547
        if( job.type==ATTACH && job.node.getEffects()==effects )
548
          {
549
          mJobs.remove(i);
550
          break;
551
          }
552
        }
553
      }
554
    }
555

    
556
///////////////////////////////////////////////////////////////////////////////////////////////////
557
/**
558
 * Removes the first occurrence of a specified child from the list of children of our Surface.
559
 * <p>
560
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
561
 * DistortedMaster (by calling doWork())
562
 *
563
 * @param node The Node to remove.
564
 */
565
  public void detach(DistortedNode node)
566
    {
567
    mJobs.add(new Job(DETACH,node,null));
568
    DistortedMaster.newSlave(this);
569
    }
570

    
571
///////////////////////////////////////////////////////////////////////////////////////////////////
572
/**
573
 * Removes all children Nodes.
574
 * <p>
575
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
576
 * DistortedMaster (by calling doWork())
577
 */
578
  public void detachAll()
579
    {
580
    mJobs.add(new Job(DETALL,null,null));
581
    DistortedMaster.newSlave(this);
582
    }
583

    
584
///////////////////////////////////////////////////////////////////////////////////////////////////
585
/**
586
 * This is not really part of the public API. Has to be public only because it is a part of the
587
 * DistortedSlave interface, which should really be a class that we extend here instead but
588
 * Java has no multiple inheritance.
589
 *
590
 * @y.exclude
591
 */
592
  public void doWork()
593
    {
594
    int num = mJobs.size();
595
    Job job;
596

    
597
    for(int i=0; i<num; i++)
598
      {
599
      job = mJobs.remove(0);
600

    
601
      switch(job.type)
602
        {
603
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
604
                     job.node.setSurfaceParent(this);
605
                     DistortedMaster.addSorted(mChildren,job.node);
606
                     mNumChildren++;
607
                     break;
608
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
609
                       {
610
                       job.node.setSurfaceParent(null);
611
                       mNumChildren--;
612
                       }
613
                     break;
614
        case DETALL: if( mNumChildren>0 )
615
                       {
616
                       DistortedNode tmp;
617

    
618
                       for(int j=mNumChildren-1; j>=0; j--)
619
                         {
620
                         tmp = mChildren.remove(j);
621
                         tmp.setSurfaceParent(null);
622
                         }
623

    
624
                       mNumChildren = 0;
625
                       }
626
                     break;
627
        case SORT  : job.node.setPost(job.dep);
628
                     mChildren.remove(job.node);
629
                     DistortedMaster.addSorted(mChildren,job.node);
630
                     break;
631
        }
632
      }
633
    }
634
}
(9-9/26)