Project

General

Profile

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

library / src / main / java / org / distorted / library / DistortedOutputSurface.java @ 226144d0

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
    mFOV = 60.0f;
81
    mNear=  0.5f;
82

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

    
87
    mTime = 0;
88

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

    
94
    mClearDepth = 1.0f;
95

    
96
    mBuffer1 = new DistortedFramebuffer[EffectQuality.LENGTH];
97
    mBuffer2 = new DistortedFramebuffer[EffectQuality.LENGTH];
98

    
99
    mMipmap = 1.0f;
100

    
101
    createProjection();
102
    }
103

    
104
///////////////////////////////////////////////////////////////////////////////////////////////////
105

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

    
116
        float left   = -q/2;
117
        float right  = +q/2;
118
        float bottom = -c/2;
119
        float top    = +c/2;
120
        float near   =  c/a;
121

    
122
        mDistance    = mHeight/a;
123
        float far    = 2*mDistance-near;
124

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

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

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

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

    
154
//sNew = "";
155

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

    
162
//sNew += currB;
163

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

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

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

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

    
193
        if( i==num-1 )
194
          {
195
          numRenders += currP.postprocess(time,this);
196
          }
197
        }
198

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

    
212
///////////////////////////////////////////////////////////////////////////////////////////////////
213

    
214
  void newJob(int t, DistortedNode n, DistortedEffectsPostprocess d)
215
    {
216
    mJobs.add(new Job(t,n,d));
217
    }
218

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

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

    
266
    int numRenders=0;
267

    
268
    for(int i=0; i<mNumChildren; i++)
269
      {
270
      numRenders += mChildren.get(i).renderRecursive(time);
271
      }
272

    
273
    setAsOutput(time);
274
    numRenders += renderChildren(time,mNumChildren,mChildren);
275

    
276
    return numRenders;
277
    }
278

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

    
292
    if( mTime!=time )
293
      {
294
      mTime = time;
295
      DistortedRenderState.colorDepthOn();
296
      GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
297
      GLES30.glClearDepthf(mClearDepth);
298
      GLES30.glClear( GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT);
299
      }
300
    }
301

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

    
326
///////////////////////////////////////////////////////////////////////////////////////////////////
327
/**
328
 * Set the (R,G,B,A) values of GLES30.glClearColor() to set up color with which to clear
329
 * this Surface before each render.
330
 *
331
 * @param r the Red component. Default: 0.0f
332
 * @param g the Green component. Default: 0.0f
333
 * @param b the Blue component. Default: 0.0f
334
 * @param a the Alpha component. Default: 0.0f
335
 */
336
  public void glClearColor(float r, float g, float b, float a)
337
    {
338
    mClearR = r;
339
    mClearG = g;
340
    mClearB = b;
341
    mClearA = a;
342
    }
343

    
344
///////////////////////////////////////////////////////////////////////////////////////////////////
345
/**
346
 * Set the Depth value of GLES30.glClearDepthf() to set up depth with which to clear
347
 * the Depth buffer of Surface before each render.
348
 *
349
 * @param d the Depth. Default: 1.0f
350
 */
351
  public void glClearDepthf(float d)
352
    {
353
    mClearDepth = d;
354
    }
355

    
356
///////////////////////////////////////////////////////////////////////////////////////////////////
357
/**
358
 * Create new Projection matrix.
359
 *
360
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
361
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
362
 * @param near Distance between the screen plane and the near plane.
363
 *             Valid vaules: 0<near<1. When near==0, the Near Plane is exactly at the tip of the
364
 *             pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
365
 */
366
  public void setProjection(float fov, float near)
367
    {
368
    if( fov < 180.0f && fov >=0.0f )
369
      {
370
      mFOV = fov;
371
      }
372

    
373
    if( near<   1.0f && near> 0.0f )
374
      {
375
      mNear= near;
376
      }
377
    else if( near<=0.0f )
378
      {
379
      mNear = 0.01f;
380
      }
381
    else if( near>=1.0f )
382
      {
383
      mNear=0.99f;
384
      }
385

    
386
    createProjection();
387
    }
388

    
389
///////////////////////////////////////////////////////////////////////////////////////////////////
390
/**
391
 * Resize the underlying Framebuffer.
392
 * <p>
393
 * This method can be safely called mid-render as it doesn't interfere with rendering.
394
 *
395
 * @param width The new width.
396
 * @param height The new height.
397
 */
398
  public void resize(int width, int height)
399
    {
400
    if( mWidth!=width || mHeight!=height )
401
      {
402
      mWidth = width;
403
      mHeight= height;
404

    
405
      createProjection();
406

    
407
      if( mColorCreated==CREATED )
408
        {
409
        markForCreation();
410
        recreate();
411
        }
412
      }
413
    }
414

    
415
///////////////////////////////////////////////////////////////////////////////////////////////////
416
/**
417
 * Create a new DEPTH buffer and attach it or (param=false) detach an existing DEPTH attachment and recreate it.
418
 *
419
 * @param enable <bold>true</bold> if we want to attach a new DEPTH buffer to the FBO.<br>
420
 *               <bold>false</bold> if we want to detach the DEPTH attachment.
421
 */
422
  public void enableDepth(boolean enable)
423
    {
424
    if( enable && mDepthCreated==DONT_CREATE )
425
      {
426
      mDepthCreated = NOT_CREATED_YET;
427
      markForCreation();
428
      }
429
    if( !enable && mDepthCreated!=DONT_CREATE )
430
      {
431
      mDepthCreated = DONT_CREATE;
432
      markForCreation();
433
      }
434
    }
435

    
436
///////////////////////////////////////////////////////////////////////////////////////////////////
437
/**
438
 * Return true if the Surface contains a DEPTH attachment.
439
 *
440
 * @return <bold>true</bold> if the FBO contains a DEPTH attachment.
441
 */
442
  public boolean hasDepth()
443
    {
444
    return mDepthCreated==CREATED;
445
    }
446

    
447
///////////////////////////////////////////////////////////////////////////////////////////////////
448
/**
449
 * Adds a new child to the last position in the list of our Surface's children.
450
 * <p>
451
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
452
 * DistortedMaster (by calling doWork())
453
 *
454
 * @param node The new Node to add.
455
 */
456
  public void attach(DistortedNode node)
457
    {
458
    mJobs.add(new Job(ATTACH,node,null));
459
    DistortedMaster.newSlave(this);
460
    }
461

    
462
///////////////////////////////////////////////////////////////////////////////////////////////////
463
/**
464
 * Adds a new child to the last position in the list of our Surface's children.
465
 * <p>
466
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
467
 * DistortedMaster (by calling doWork())
468
 *
469
 * @param surface InputSurface to initialize our child Node with.
470
 * @param effects DistortedEffects to initialize our child Node with.
471
 * @param mesh MeshObject to initialize our child Node with.
472
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
473
 */
474
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
475
    {
476
    DistortedNode node = new DistortedNode(surface,effects,mesh);
477
    mJobs.add(new Job(ATTACH,node,null));
478
    DistortedMaster.newSlave(this);
479
    return node;
480
    }
481

    
482
///////////////////////////////////////////////////////////////////////////////////////////////////
483
/**
484
 * Removes the first occurrence of a specified child from the list of children of our Surface.
485
 * <p>
486
 * A bit questionable method as there can be many different Nodes attached as children, some
487
 * of them having the same Effects but - for instance - different Mesh. Use with care.
488
 * <p>
489
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
490
 * DistortedMaster (by calling doWork())
491
 *
492
 * @param effects DistortedEffects to remove.
493
 */
494
  public void detach(DistortedEffects effects)
495
    {
496
    long id = effects.getID();
497
    DistortedNode node;
498
    boolean detached = false;
499

    
500
    for(int i=0; i<mNumChildren; i++)
501
      {
502
      node = mChildren.get(i);
503

    
504
      if( node.getEffects().getID()==id )
505
        {
506
        detached = true;
507
        mJobs.add(new Job(DETACH,node,null));
508
        DistortedMaster.newSlave(this);
509
        break;
510
        }
511
      }
512

    
513
    if( !detached )
514
      {
515
      // if we failed to detach any, it still might be the case that
516
      // there's an ATTACH job that we need to cancel.
517
      int num = mJobs.size();
518
      Job job;
519

    
520
      for(int i=0; i<num; i++)
521
        {
522
        job = mJobs.get(i);
523

    
524
        if( job.type==ATTACH && job.node.getEffects()==effects )
525
          {
526
          mJobs.remove(i);
527
          break;
528
          }
529
        }
530
      }
531
    }
532

    
533
///////////////////////////////////////////////////////////////////////////////////////////////////
534
/**
535
 * Removes the first occurrence of a specified child from the list of children of our Surface.
536
 * <p>
537
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
538
 * DistortedMaster (by calling doWork())
539
 *
540
 * @param node The Node to remove.
541
 */
542
  public void detach(DistortedNode node)
543
    {
544
    mJobs.add(new Job(DETACH,node,null));
545
    DistortedMaster.newSlave(this);
546
    }
547

    
548
///////////////////////////////////////////////////////////////////////////////////////////////////
549
/**
550
 * Removes all children Nodes.
551
 * <p>
552
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
553
 * DistortedMaster (by calling doWork())
554
 */
555
  public void detachAll()
556
    {
557
    mJobs.add(new Job(DETALL,null,null));
558
    DistortedMaster.newSlave(this);
559
    }
560

    
561
///////////////////////////////////////////////////////////////////////////////////////////////////
562
/**
563
 * This is not really part of the public API. Has to be public only because it is a part of the
564
 * DistortedSlave interface, which should really be a class that we extend here instead but
565
 * Java has no multiple inheritance.
566
 *
567
 * @y.exclude
568
 */
569
  public void doWork()
570
    {
571
    int num = mJobs.size();
572
    Job job;
573

    
574
    for(int i=0; i<num; i++)
575
      {
576
      job = mJobs.remove(0);
577

    
578
      switch(job.type)
579
        {
580
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
581
                     job.node.setSurfaceParent(this);
582
                     DistortedMaster.addSorted(mChildren,job.node);
583
                     mNumChildren++;
584
                     break;
585
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
586
                       {
587
                       job.node.setSurfaceParent(null);
588
                       mNumChildren--;
589
                       }
590
                     break;
591
        case DETALL: if( mNumChildren>0 )
592
                       {
593
                       DistortedNode tmp;
594

    
595
                       for(int j=mNumChildren-1; j>=0; j--)
596
                         {
597
                         tmp = mChildren.remove(j);
598
                         tmp.setSurfaceParent(null);
599
                         }
600

    
601
                       mNumChildren = 0;
602
                       }
603
                     break;
604
        case SORT  : job.node.setPost(job.dep);
605
                     mChildren.remove(job.node);
606
                     DistortedMaster.addSorted(mChildren,job.node);
607
                     break;
608
        }
609
      }
610
    }
611
}
(9-9/26)