Project

General

Profile

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

library / src / main / java / org / distorted / library / DistortedOutputSurface.java @ 42571056

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
  private static final int ATTACH = 0;
31
  private static final int DETACH = 1;
32
  private static final int DETALL = 2;
33
  private static final int SORT   = 3;
34

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

    
38
  private class Job
39
    {
40
    int type;
41
    DistortedNode node;
42
    DistortedEffectsPostprocess dep;
43

    
44
    Job(int t, DistortedNode n, DistortedEffectsPostprocess d)
45
      {
46
      type = t;
47
      node = n;
48
      dep  = d;
49
      }
50
    }
51

    
52
  private ArrayList<Job> mJobs = new ArrayList<>();
53

    
54
  DistortedFramebuffer[] mBuffer1, mBuffer2;
55

    
56
  private long mTime;
57
  private float mFOV;
58
  float mDistance, mNear;
59
  float[] mProjectionMatrix;
60

    
61
  int mDepthCreated;
62
  int[] mDepthH = new int[1];
63
  int[] mFBOH   = new int[1];
64

    
65
  private float mClearR, mClearG, mClearB, mClearA;
66
  private float mClearDepth;
67

    
68
//private String sNew="", sOld="";
69

    
70
  float mMipmap;
71

    
72
///////////////////////////////////////////////////////////////////////////////////////////////////
73

    
74
  DistortedOutputSurface(int width, int height, int createColor, int createDepth, int fbo, int type)
75
    {
76
    super(width,height,createColor,type);
77

    
78
    mProjectionMatrix = new float[16];
79

    
80
    mWidth = width;
81
    mHeight= height;
82

    
83
    mFOV = 60.0f;
84
    mNear=  0.5f;
85

    
86
    mDepthCreated= createDepth;
87
    mFBOH[0]     = fbo;
88
    mDepthH[0]   = 0;
89

    
90
    mTime = 0;
91

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

    
97
    mClearDepth = 1.0f;
98

    
99
    mBuffer1 = new DistortedFramebuffer[EffectQuality.LENGTH];
100
    mBuffer2 = new DistortedFramebuffer[EffectQuality.LENGTH];
101

    
102
    mMipmap = 1.0f;
103

    
104
    createProjection();
105
    }
106

    
107
///////////////////////////////////////////////////////////////////////////////////////////////////
108

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

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

    
125
        mDistance    = mHeight/a;
126
        float far    = 2*mDistance-near;
127

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

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

    
145
///////////////////////////////////////////////////////////////////////////////////////////////////
146
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
147
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
148
// to a whole buffer and merge it.
149

    
150
  int renderChildren(long time, int num, ArrayList<DistortedNode> children)
151
    {
152
    int numRenders = 0;
153
    DistortedNode child;
154
    DistortedEffectsPostprocess lastP=null, currP;
155
    long lastB=0, currB;
156

    
157
//sNew = "";
158

    
159
    for(int i=0; i<num; i++)
160
      {
161
      child = children.get(i);
162
      currP = child.getEffectsPostprocess();
163
      currB = currP==null ? 0 : currP.getBucket();
164

    
165
//sNew += currB;
166

    
167
      if( lastB!=currB && lastB!=0 )
168
        {
169
        numRenders += lastP.postprocess(time,this);
170
        }
171

    
172
      if( currB==0 )
173
        {
174
        numRenders += child.draw(time,this);
175
        }
176
      else
177
        {
178
        if( mBuffer1[0]==null )
179
          {
180
          float mipmap=1.0f;
181

    
182
          for(int j=0; j<EffectQuality.LENGTH; j++)
183
            {
184
            mBuffer1[j] = new DistortedFramebuffer( mDepthCreated!=DONT_CREATE, DistortedSurface.TYPE_SYST,
185
                                                    (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
186
            mBuffer2[j] = new DistortedFramebuffer(false                     , DistortedSurface.TYPE_SYST,
187
                                                    (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
188
            mBuffer1[j].mMipmap = mipmap;
189
            mipmap *= EffectQuality.MULTIPLIER;
190
            }
191
          DistortedSurface.toDo();  // create immediately
192
          }
193

    
194
        numRenders += child.draw(time,mBuffer1[currP.getQuality()]);
195

    
196
        if( i==num-1 )
197
          {
198
          numRenders += currP.postprocess(time,this);
199
          }
200
        }
201

    
202
      lastP = currP;
203
      lastB = currB;
204
      }
205
/*
206
if( !sNew.equals(sOld) )
207
  {
208
  sOld = sNew;
209
  android.util.Log.e("surface", "Surface"+getID()+": "+sOld);
210
  }
211
*/
212
    return numRenders;
213
    }
214

    
215
///////////////////////////////////////////////////////////////////////////////////////////////////
216

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

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

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

    
280
    int numRenders=0;
281

    
282
    for(int i=0; i<mNumChildren; i++)
283
      {
284
      numRenders += mChildren.get(i).renderRecursive(time);
285
      }
286

    
287
    setAsOutput(time);
288
    numRenders += renderChildren(time,mNumChildren,mChildren);
289

    
290
    return numRenders;
291
    }
292

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

    
306
    if( mTime!=time )
307
      {
308
      mTime = time;
309
      DistortedRenderState.colorDepthOn();
310
      GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
311
      GLES30.glClearDepthf(mClearDepth);
312
      GLES30.glClear( GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT);
313
      }
314
    }
315

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

    
340
///////////////////////////////////////////////////////////////////////////////////////////////////
341
/**
342
 * Set the (R,G,B,A) values of GLES30.glClearColor() to set up color with which to clear
343
 * this Surface before each render.
344
 *
345
 * @param r the Red component. Default: 0.0f
346
 * @param g the Green component. Default: 0.0f
347
 * @param b the Blue component. Default: 0.0f
348
 * @param a the Alpha component. Default: 0.0f
349
 */
350
  public void glClearColor(float r, float g, float b, float a)
351
    {
352
    mClearR = r;
353
    mClearG = g;
354
    mClearB = b;
355
    mClearA = a;
356
    }
357

    
358
///////////////////////////////////////////////////////////////////////////////////////////////////
359
/**
360
 * Set the Depth value of GLES30.glClearDepthf() to set up depth with which to clear
361
 * the Depth buffer of Surface before each render.
362
 *
363
 * @param d the Depth. Default: 1.0f
364
 */
365
  public void glClearDepthf(float d)
366
    {
367
    mClearDepth = d;
368
    }
369

    
370
///////////////////////////////////////////////////////////////////////////////////////////////////
371
/**
372
 * Create new Projection matrix.
373
 *
374
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
375
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
376
 * @param near Distance between the screen plane and the near plane.
377
 *             Valid vaules: 0<near<1. When near==0, the Near Plane is exactly at the tip of the
378
 *             pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
379
 */
380
  public void setProjection(float fov, float near)
381
    {
382
    if( fov < 180.0f && fov >=0.0f )
383
      {
384
      mFOV = fov;
385
      }
386

    
387
    if( near<   1.0f && near> 0.0f )
388
      {
389
      mNear= near;
390
      }
391
    else if( near<=0.0f )
392
      {
393
      mNear = 0.01f;
394
      }
395
    else if( near>=1.0f )
396
      {
397
      mNear=0.99f;
398
      }
399

    
400
    createProjection();
401
    }
402

    
403
///////////////////////////////////////////////////////////////////////////////////////////////////
404
/**
405
 * Resize the underlying Framebuffer.
406
 * <p>
407
 * This method can be safely called mid-render as it doesn't interfere with rendering.
408
 *
409
 * @param width The new width.
410
 * @param height The new height.
411
 */
412
  public void resize(int width, int height)
413
    {
414
    if( mWidth!=width || mHeight!=height )
415
      {
416
      mWidth = width;
417
      mHeight= height;
418

    
419
      createProjection();
420

    
421
      if( mColorCreated==CREATED )
422
        {
423
        markForCreation();
424
        recreate();
425
        }
426
      }
427
    }
428

    
429
///////////////////////////////////////////////////////////////////////////////////////////////////
430
/**
431
 * Create a new DEPTH buffer and attach it or (param=false) detach an existing DEPTH attachment and recreate it.
432
 *
433
 * @param enable <bold>true</bold> if we want to attach a new DEPTH buffer to the FBO.<br>
434
 *               <bold>false</bold> if we want to detach the DEPTH attachment.
435
 */
436
  public void enableDepth(boolean enable)
437
    {
438
    if( enable && mDepthCreated==DONT_CREATE )
439
      {
440
      mDepthCreated = NOT_CREATED_YET;
441
      markForCreation();
442
      }
443
    if( !enable && mDepthCreated!=DONT_CREATE )
444
      {
445
      mDepthCreated = DONT_CREATE;
446
      markForCreation();
447
      }
448
    }
449

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

    
461
///////////////////////////////////////////////////////////////////////////////////////////////////
462
/**
463
 * Adds a new child to the last position in the list of our Surface's children.
464
 * <p>
465
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
466
 * DistortedMaster (by calling doWork())
467
 *
468
 * @param node The new Node to add.
469
 */
470
  public void attach(DistortedNode node)
471
    {
472
    mJobs.add(new Job(ATTACH,node,null));
473
    DistortedMaster.newSlave(this);
474
    }
475

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

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

    
514
    for(int i=0; i<mNumChildren; i++)
515
      {
516
      node = mChildren.get(i);
517

    
518
      if( node.getEffects().getID()==id )
519
        {
520
        detached = true;
521
        mJobs.add(new Job(DETACH,node,null));
522
        DistortedMaster.newSlave(this);
523
        break;
524
        }
525
      }
526

    
527
    if( !detached )
528
      {
529
      // if we failed to detach any, it still might be the case that
530
      // there's an ATTACH job that we need to cancel.
531
      int num = mJobs.size();
532
      Job job;
533

    
534
      for(int i=0; i<num; i++)
535
        {
536
        job = mJobs.get(i);
537

    
538
        if( job.type==ATTACH && job.node.getEffects()==effects )
539
          {
540
          mJobs.remove(i);
541
          break;
542
          }
543
        }
544
      }
545
    }
546

    
547
///////////////////////////////////////////////////////////////////////////////////////////////////
548
/**
549
 * Removes the first occurrence of a specified child from the list of children of our Surface.
550
 * <p>
551
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
552
 * DistortedMaster (by calling doWork())
553
 *
554
 * @param node The Node to remove.
555
 */
556
  public void detach(DistortedNode node)
557
    {
558
    mJobs.add(new Job(DETACH,node,null));
559
    DistortedMaster.newSlave(this);
560
    }
561

    
562
///////////////////////////////////////////////////////////////////////////////////////////////////
563
/**
564
 * Removes all children Nodes.
565
 * <p>
566
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
567
 * DistortedMaster (by calling doWork())
568
 */
569
  public void detachAll()
570
    {
571
    mJobs.add(new Job(DETALL,null,null));
572
    DistortedMaster.newSlave(this);
573
    }
574

    
575
///////////////////////////////////////////////////////////////////////////////////////////////////
576
/**
577
 * This is not really part of the public API. Has to be public only because it is a part of the
578
 * DistortedSlave interface, which should really be a class that we extend here instead but
579
 * Java has no multiple inheritance.
580
 *
581
 * @y.exclude
582
 */
583
  public void doWork()
584
    {
585
    int num = mJobs.size();
586
    Job job;
587

    
588
    for(int i=0; i<num; i++)
589
      {
590
      job = mJobs.remove(0);
591

    
592
      switch(job.type)
593
        {
594
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
595
                     job.node.setSurfaceParent(this);
596
                     DistortedMaster.addSorted(mChildren,job.node);
597
                     mNumChildren++;
598
                     break;
599
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
600
                       {
601
                       job.node.setSurfaceParent(null);
602
                       mNumChildren--;
603
                       }
604
                     break;
605
        case DETALL: if( mNumChildren>0 )
606
                       {
607
                       DistortedNode tmp;
608

    
609
                       for(int j=mNumChildren-1; j>=0; j--)
610
                         {
611
                         tmp = mChildren.remove(j);
612
                         tmp.setSurfaceParent(null);
613
                         }
614

    
615
                       mNumChildren = 0;
616
                       }
617
                     break;
618
        case SORT  : job.node.setPost(job.dep);
619
                     mChildren.remove(job.node);
620
                     DistortedMaster.addSorted(mChildren,job.node);
621
                     break;
622
        }
623
      }
624
    }
625
}
(8-8/25)