Project

General

Profile

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

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

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
  int mWidth,mHeight,mDepth;
59
  float mDistance, mNear;
60
  float[] mProjectionMatrix;
61

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

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

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

    
71
///////////////////////////////////////////////////////////////////////////////////////////////////
72

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

    
77
    mProjectionMatrix = new float[16];
78

    
79
    mWidth = width;
80
    mHeight= height;
81

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

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

    
89
    mTime = 0;
90

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

    
96
    mClearDepth = 1.0f;
97

    
98
    createProjection();
99
    }
100

    
101
///////////////////////////////////////////////////////////////////////////////////////////////////
102

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

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

    
119
        mDistance    = mHeight/a;
120
        float far    = 2*mDistance-near;
121
        mDepth       = (int)((far-near)/2);
122

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

    
136
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
137
        }
138
      }
139
    }
140

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

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

    
153
//sNew = "";
154

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

    
161
//sNew += currB;
162

    
163
      if( lastB!=currB && lastB!=0 )
164
        {
165
        numRenders += lastP.postprocess(time,this);
166
        }
167

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

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

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

    
200
///////////////////////////////////////////////////////////////////////////////////////////////////
201

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

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

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

    
253
    int numRenders=0;
254

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

    
260
    setAsOutput(time);
261
    numRenders += renderChildren(time,mNumChildren,mChildren);
262

    
263
    return numRenders;
264
    }
265

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

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

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

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

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

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

    
349
    createProjection();
350
    }
351

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

    
370
      createProjection();
371

    
372
      if( mColorCreated==CREATED )
373
        {
374
        markForCreation();
375
        recreate();
376
        }
377
      }
378
    }
379

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

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

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

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

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

    
465
    for(int i=0; i<mNumChildren; i++)
466
      {
467
      node = mChildren.get(i);
468

    
469
      if( node.getEffects().getID()==id )
470
        {
471
        detached = true;
472
        mJobs.add(new Job(DETACH,node,null));
473
        DistortedMaster.newSlave(this);
474
        break;
475
        }
476
      }
477

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

    
485
      for(int i=0; i<num; i++)
486
        {
487
        job = mJobs.get(i);
488

    
489
        if( job.type==ATTACH && job.node.getEffects()==effects )
490
          {
491
          mJobs.remove(i);
492
          break;
493
          }
494
        }
495
      }
496
    }
497

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

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

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

    
539
    for(int i=0; i<num; i++)
540
      {
541
      job = mJobs.remove(0);
542

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

    
560
                       for(int j=mNumChildren-1; j>=0; j--)
561
                         {
562
                         tmp = mChildren.remove(j);
563
                         tmp.setSurfaceParent(null);
564
                         }
565

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