Project

General

Profile

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

library / src / main / java / org / distorted / library / DistortedOutputSurface.java @ 6e7c8721

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
///////////////////////////////////////////////////////////////////////////////////////////////////
71

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

    
76
    mProjectionMatrix = new float[16];
77

    
78
    mWidth = width;
79
    mHeight= height;
80

    
81
    mFOV = 60.0f;
82
    mNear=  0.5f;
83

    
84
    mDepthCreated= createDepth;
85
    mFBOH[0]     = fbo;
86
    mDepthH[0]   = 0;
87

    
88
    mTime = 0;
89

    
90
    mClearR = 0.0f;
91
    mClearG = 0.0f;
92
    mClearB = 0.0f;
93
    mClearA = 0.0f;
94

    
95
    mClearDepth = 1.0f;
96

    
97
    createProjection();
98
    }
99

    
100
///////////////////////////////////////////////////////////////////////////////////////////////////
101

    
102
  private void createProjection()
103
    {
104
    if( mWidth>0 && mHeight>1 )
105
      {
106
      if( mFOV>0.0f )  // perspective projection
107
        {
108
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
109
        float q = mWidth*mNear;
110
        float c = mHeight*mNear;
111

    
112
        float left   = -q/2;
113
        float right  = +q/2;
114
        float bottom = -c/2;
115
        float top    = +c/2;
116
        float near   =  c/a;
117

    
118
        mDistance    = mHeight/a;
119
        float far    = 2*mDistance-near;
120

    
121
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
122
        }
123
      else             // parallel projection
124
        {
125
        float left   = -mWidth /2.0f;
126
        float right  = +mWidth /2.0f;
127
        float bottom = -mHeight/2.0f;
128
        float top    = +mHeight/2.0f;
129
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
130
        mDistance    = mWidth+mHeight;
131
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
132

    
133
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
134
        }
135
      }
136
    }
137

    
138
///////////////////////////////////////////////////////////////////////////////////////////////////
139
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
140
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
141
// to a whole buffer and merge it.
142

    
143
  int renderChildren(long time, int num, ArrayList<DistortedNode> children)
144
    {
145
    int numRenders = 0;
146
    DistortedNode child;
147
    DistortedEffectsPostprocess lastP=null, currP;
148
    long lastB=0, currB;
149

    
150
//sNew = "";
151

    
152
    for(int i=0; i<num; i++)
153
      {
154
      child = children.get(i);
155
      currP = child.getEffectsPostprocess();
156
      currB = currP==null ? 0 : currP.getBucket();
157

    
158
//sNew += currB;
159

    
160
      if( lastB!=currB && lastB!=0 )
161
        {
162
        numRenders += lastP.postprocess(time,this);
163
        }
164

    
165
      if( currB==0 )
166
        {
167
        numRenders += child.draw(time,this);
168
        }
169
      else
170
        {
171
        if( mBuffer1==null )
172
          {
173
          mBuffer1 = new DistortedFramebuffer(mDepthCreated!=DONT_CREATE, DistortedSurface.TYPE_SYST, mWidth, mHeight);
174
          mBuffer2 = new DistortedFramebuffer(false                     , DistortedSurface.TYPE_SYST, mWidth, mHeight);
175
          DistortedSurface.toDo();  // create immediately
176
          }
177

    
178
        numRenders += child.draw(time,mBuffer1);
179
        if( i==num-1 )
180
          {
181
          numRenders += currP.postprocess(time,this);
182
          }
183
        }
184

    
185
      lastP = currP;
186
      lastB = currB;
187
      }
188
/*
189
if( !sNew.equals(sOld) )
190
  {
191
  sOld = sNew;
192
  android.util.Log.e("surface", "Surface"+getID()+": "+sOld);
193
  }
194
*/
195
    return numRenders;
196
    }
197

    
198
///////////////////////////////////////////////////////////////////////////////////////////////////
199

    
200
  void newJob(int t, DistortedNode n, DistortedEffectsPostprocess d)
201
    {
202
    mJobs.add(new Job(t,n,d));
203
    }
204

    
205
///////////////////////////////////////////////////////////////////////////////////////////////////
206
// PUBLIC API
207
///////////////////////////////////////////////////////////////////////////////////////////////////
208
/**
209
 * Draws all the attached children to this OutputSurface.
210
 * <p>
211
 * Must be called from a thread holding OpenGL Context.
212
 *
213
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
214
 * @return Number of objects rendered.
215
 */
216
  public int render(long time)
217
    {
218
    // change tree topology (attach and detach children)
219
/*
220
    boolean changed =
221
*/
222
    DistortedMaster.toDo();
223
/*
224
    // debugging only
225
    if( changed )
226
      {
227
      for(int i=0; i<mNumChildren; i++)
228
        {
229
        mChildren.get(i).debug(0);
230
        }
231

    
232
      DistortedNode.debugMap();
233
      }
234
*/
235
    // create and delete all underlying OpenGL resources
236
    // Watch out: FIRST change topology, only then deal
237
    // with OpenGL resources. That's because changing Tree
238
    // can result in additional Framebuffers that would need
239
    // to be created immediately, before the calls to drawRecursive()
240
    toDo();
241
/*
242
    // debugging only
243
    if( changed )
244
      {
245
      DistortedSurface.debugLists();
246
      }
247
*/
248
    // mark OpenGL state as unknown
249
    DistortedRenderState.reset();
250

    
251
    int numRenders=0;
252

    
253
    for(int i=0; i<mNumChildren; i++)
254
      {
255
      numRenders += mChildren.get(i).renderRecursive(time);
256
      }
257

    
258
    setAsOutput(time);
259
    numRenders += renderChildren(time,mNumChildren,mChildren);
260

    
261
    return numRenders;
262
    }
263

    
264
///////////////////////////////////////////////////////////////////////////////////////////////////
265
/**
266
 * Bind this Surface as a Framebuffer we can render to.
267
 *
268
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
269
 *             out if this is the first time during present frame that this FBO is being set as output.
270
 *             If so, the library, in addition to binding the Surface for output, also clears the
271
 *             Surface's color and depth attachments.
272
 */
273
  public void setAsOutput(long time)
274
    {
275
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
276

    
277
    if( mTime!=time )
278
      {
279
      mTime = time;
280
      DistortedRenderState.colorDepthOn();
281
      GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
282
      GLES30.glClearDepthf(mClearDepth);
283
      GLES30.glClear( GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT);
284
      }
285
    }
286

    
287
///////////////////////////////////////////////////////////////////////////////////////////////////
288
/**
289
 * Set the (R,G,B,A) values of GLES30.glClearColor() to set up color with which to clear
290
 * this Surface before each render.
291
 *
292
 * @param r the Red component. Default: 0.0f
293
 * @param g the Green component. Default: 0.0f
294
 * @param b the Blue component. Default: 0.0f
295
 * @param a the Alpha component. Default: 0.0f
296
 */
297
  public void glClearColor(float r, float g, float b, float a)
298
    {
299
    mClearR = r;
300
    mClearG = g;
301
    mClearB = b;
302
    mClearA = a;
303
    }
304

    
305
///////////////////////////////////////////////////////////////////////////////////////////////////
306
/**
307
 * Set the Depth value of GLES30.glClearDepthf() to set up depth with which to clear
308
 * the Depth buffer of Surface before each render.
309
 *
310
 * @param d the Depth. Default: 1.0f
311
 */
312
  public void glClearDepthf(float d)
313
    {
314
    mClearDepth = d;
315
    }
316

    
317
///////////////////////////////////////////////////////////////////////////////////////////////////
318
/**
319
 * Create new Projection matrix.
320
 *
321
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
322
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
323
 * @param near Distance between the screen plane and the near plane.
324
 *             Valid vaules: 0<near<1. When near==0, the Near Plane is exactly at the tip of the
325
 *             pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
326
 */
327
  public void setProjection(float fov, float near)
328
    {
329
    if( fov < 180.0f && fov >=0.0f )
330
      {
331
      mFOV = fov;
332
      }
333

    
334
    if( near<   1.0f && near> 0.0f )
335
      {
336
      mNear= near;
337
      }
338
    else if( near<=0.0f )
339
      {
340
      mNear = 0.01f;
341
      }
342
    else if( near>=1.0f )
343
      {
344
      mNear=0.99f;
345
      }
346

    
347
    createProjection();
348
    }
349

    
350
///////////////////////////////////////////////////////////////////////////////////////////////////
351
/**
352
 * Resize the underlying Framebuffer.
353
 * <p>
354
 * This method can be safely called mid-render as it doesn't interfere with rendering.
355
 *
356
 * @param width The new width.
357
 * @param height The new height.
358
 */
359
  public void resize(int width, int height)
360
    {
361
    if( mWidth!=width || mHeight!=height )
362
      {
363
      mWidth = width;
364
      mHeight= height;
365

    
366
      createProjection();
367

    
368
      if( mColorCreated==CREATED )
369
        {
370
        markForCreation();
371
        recreate();
372
        }
373
      }
374
    }
375

    
376
///////////////////////////////////////////////////////////////////////////////////////////////////
377
/**
378
 * Create a new DEPTH buffer and attach it or (param=false) detach an existing DEPTH attachment and recreate it.
379
 *
380
 * @param enable <bold>true</bold> if we want to attach a new DEPTH buffer to the FBO.<br>
381
 *               <bold>false</bold> if we want to detach the DEPTH attachment.
382
 */
383
  public void enableDepth(boolean enable)
384
    {
385
    if( enable && mDepthCreated==DONT_CREATE )
386
      {
387
      mDepthCreated = NOT_CREATED_YET;
388
      markForCreation();
389
      }
390
    if( !enable && mDepthCreated!=DONT_CREATE )
391
      {
392
      mDepthCreated = DONT_CREATE;
393
      markForCreation();
394
      }
395
    }
396

    
397
///////////////////////////////////////////////////////////////////////////////////////////////////
398
/**
399
 * Return true if the Surface contains a DEPTH attachment.
400
 *
401
 * @return <bold>true</bold> if the FBO contains a DEPTH attachment.
402
 */
403
  public boolean hasDepth()
404
    {
405
    return mDepthCreated==CREATED;
406
    }
407

    
408
///////////////////////////////////////////////////////////////////////////////////////////////////
409
/**
410
 * Adds a new child to the last position in the list of our Surface's children.
411
 * <p>
412
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
413
 * DistortedMaster (by calling doWork())
414
 *
415
 * @param node The new Node to add.
416
 */
417
  public void attach(DistortedNode node)
418
    {
419
    mJobs.add(new Job(ATTACH,node,null));
420
    DistortedMaster.newSlave(this);
421
    }
422

    
423
///////////////////////////////////////////////////////////////////////////////////////////////////
424
/**
425
 * Adds a new child to the last position in the list of our Surface's children.
426
 * <p>
427
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
428
 * DistortedMaster (by calling doWork())
429
 *
430
 * @param surface InputSurface to initialize our child Node with.
431
 * @param effects DistortedEffects to initialize our child Node with.
432
 * @param mesh MeshObject to initialize our child Node with.
433
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
434
 */
435
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
436
    {
437
    DistortedNode node = new DistortedNode(surface,effects,mesh);
438
    mJobs.add(new Job(ATTACH,node,null));
439
    DistortedMaster.newSlave(this);
440
    return node;
441
    }
442

    
443
///////////////////////////////////////////////////////////////////////////////////////////////////
444
/**
445
 * Removes the first occurrence of a specified child from the list of children of our Surface.
446
 * <p>
447
 * A bit questionable method as there can be many different Nodes attached as children, some
448
 * of them having the same Effects but - for instance - different Mesh. Use with care.
449
 * <p>
450
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
451
 * DistortedMaster (by calling doWork())
452
 *
453
 * @param effects DistortedEffects to remove.
454
 */
455
  public void detach(DistortedEffects effects)
456
    {
457
    long id = effects.getID();
458
    DistortedNode node;
459
    boolean detached = false;
460

    
461
    for(int i=0; i<mNumChildren; i++)
462
      {
463
      node = mChildren.get(i);
464

    
465
      if( node.getEffects().getID()==id )
466
        {
467
        detached = true;
468
        mJobs.add(new Job(DETACH,node,null));
469
        DistortedMaster.newSlave(this);
470
        break;
471
        }
472
      }
473

    
474
    if( !detached )
475
      {
476
      // if we failed to detach any, it still might be the case that
477
      // there's an ATTACH job that we need to cancel.
478
      int num = mJobs.size();
479
      Job job;
480

    
481
      for(int i=0; i<num; i++)
482
        {
483
        job = mJobs.get(i);
484

    
485
        if( job.type==ATTACH && job.node.getEffects()==effects )
486
          {
487
          mJobs.remove(i);
488
          break;
489
          }
490
        }
491
      }
492
    }
493

    
494
///////////////////////////////////////////////////////////////////////////////////////////////////
495
/**
496
 * Removes the first occurrence of a specified child from the list of children of our Surface.
497
 * <p>
498
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
499
 * DistortedMaster (by calling doWork())
500
 *
501
 * @param node The Node to remove.
502
 */
503
  public void detach(DistortedNode node)
504
    {
505
    mJobs.add(new Job(DETACH,node,null));
506
    DistortedMaster.newSlave(this);
507
    }
508

    
509
///////////////////////////////////////////////////////////////////////////////////////////////////
510
/**
511
 * Removes all children Nodes.
512
 * <p>
513
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
514
 * DistortedMaster (by calling doWork())
515
 */
516
  public void detachAll()
517
    {
518
    mJobs.add(new Job(DETALL,null,null));
519
    DistortedMaster.newSlave(this);
520
    }
521

    
522
///////////////////////////////////////////////////////////////////////////////////////////////////
523
/**
524
 * This is not really part of the public API. Has to be public only because it is a part of the
525
 * DistortedSlave interface, which should really be a class that we extend here instead but
526
 * Java has no multiple inheritance.
527
 *
528
 * @y.exclude
529
 */
530
  public void doWork()
531
    {
532
    int num = mJobs.size();
533
    Job job;
534

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

    
539
      switch(job.type)
540
        {
541
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
542
                     job.node.setSurfaceParent(this);
543
                     DistortedMaster.addSorted(mChildren,job.node);
544
                     mNumChildren++;
545
                     break;
546
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
547
                       {
548
                       job.node.setSurfaceParent(null);
549
                       mNumChildren--;
550
                       }
551
                     break;
552
        case DETALL: if( mNumChildren>0 )
553
                       {
554
                       DistortedNode tmp;
555

    
556
                       for(int j=mNumChildren-1; j>=0; j--)
557
                         {
558
                         tmp = mChildren.remove(j);
559
                         tmp.setSurfaceParent(null);
560
                         }
561

    
562
                       mNumChildren = 0;
563
                       }
564
                     break;
565
        case SORT  : job.node.setPost(job.dep);
566
                     mChildren.remove(job.node);
567
                     DistortedMaster.addSorted(mChildren,job.node);
568
                     break;
569
        }
570
      }
571
    }
572
}
(8-8/24)