Project

General

Profile

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

library / src / main / java / org / distorted / library / DistortedOutputSurface.java @ 638b5b5c

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 NUM_MIPMAP = 4;
31
          static final int CUR_MIPMAP = 1;
32

    
33
  private static final int ATTACH = 0;
34
  private static final int DETACH = 1;
35
  private static final int DETALL = 2;
36
  private static final int SORT   = 3;
37

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

    
41
  private class Job
42
    {
43
    int type;
44
    DistortedNode node;
45
    DistortedEffectsPostprocess dep;
46

    
47
    Job(int t, DistortedNode n, DistortedEffectsPostprocess d)
48
      {
49
      type = t;
50
      node = n;
51
      dep  = d;
52
      }
53
    }
54

    
55
  private ArrayList<Job> mJobs = new ArrayList<>();
56

    
57
  DistortedFramebuffer[] mBuffer1, mBuffer2;
58

    
59
  private long mTime;
60
  private float mFOV;
61
  float mDistance, mNear;
62
  float[] mProjectionMatrix;
63

    
64
  int mDepthCreated;
65
  int[] mDepthH = new int[1];
66
  int[] mFBOH   = new int[1];
67

    
68
  private float mClearR, mClearG, mClearB, mClearA;
69
  private float mClearDepth;
70

    
71
//private String sNew="", sOld="";
72

    
73
  float mMipmap;
74

    
75
///////////////////////////////////////////////////////////////////////////////////////////////////
76

    
77
  DistortedOutputSurface(int width, int height, int createColor, int createDepth, int fbo, int type)
78
    {
79
    super(width,height,createColor,type);
80

    
81
    mProjectionMatrix = new float[16];
82

    
83
    mWidth = width;
84
    mHeight= height;
85

    
86
    mFOV = 60.0f;
87
    mNear=  0.5f;
88

    
89
    mDepthCreated= createDepth;
90
    mFBOH[0]     = fbo;
91
    mDepthH[0]   = 0;
92

    
93
    mTime = 0;
94

    
95
    mClearR = 0.0f;
96
    mClearG = 0.0f;
97
    mClearB = 0.0f;
98
    mClearA = 0.0f;
99

    
100
    mClearDepth = 1.0f;
101

    
102
    mBuffer1 = new DistortedFramebuffer[NUM_MIPMAP];
103
    mBuffer2 = new DistortedFramebuffer[NUM_MIPMAP];
104

    
105
    mMipmap = (this instanceof DistortedScreen ? 0.5f : 1.0f);
106

    
107
    createProjection();
108
    }
109

    
110
///////////////////////////////////////////////////////////////////////////////////////////////////
111

    
112
  private void createProjection()
113
    {
114
    if( mWidth>0 && mHeight>1 )
115
      {
116
      float mw = mWidth;//mMipmap*mWidth;
117
      float mh = mHeight;//mMipmap*mHeight;
118

    
119
      if( mFOV>0.0f )  // perspective projection
120
        {
121
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
122
        float q = mw*mNear;
123
        float c = mh*mNear;
124

    
125
        float left   = -q/2;
126
        float right  = +q/2;
127
        float bottom = -c/2;
128
        float top    = +c/2;
129
        float near   =  c/a;
130

    
131
        mDistance    = mh/a;
132
        float far    = 2*mDistance-near;
133

    
134
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
135
        }
136
      else             // parallel projection
137
        {
138
        float left   = -mw/2.0f;
139
        float right  = +mw/2.0f;
140
        float bottom = -mh/2.0f;
141
        float top    = +mh/2.0f;
142
        float near   = mw+mh-mh*(1.0f-mNear);
143
        mDistance    = mw+mh;
144
        float far    = mw+mh+mh*(1.0f-mNear);
145

    
146
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
147
        }
148
      }
149
    }
150

    
151
///////////////////////////////////////////////////////////////////////////////////////////////////
152
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
153
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
154
// to a whole buffer and merge it.
155

    
156
  int renderChildren(long time, int num, ArrayList<DistortedNode> children)
157
    {
158
    int numRenders = 0;
159
    DistortedNode child;
160
    DistortedEffectsPostprocess lastP=null, currP;
161
    long lastB=0, currB;
162

    
163
//sNew = "";
164

    
165
    for(int i=0; i<num; i++)
166
      {
167
      child = children.get(i);
168
      currP = child.getEffectsPostprocess();
169
      currB = currP==null ? 0 : currP.getBucket();
170

    
171
//sNew += currB;
172

    
173
      if( lastB!=currB && lastB!=0 )
174
        {
175
        numRenders += lastP.postprocess(time,this);
176
        }
177

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

    
188
          for(int j=0; j<NUM_MIPMAP; j++)
189
            {
190
            mBuffer1[j] = new DistortedFramebuffer( mDepthCreated!=DONT_CREATE, DistortedSurface.TYPE_SYST,
191
                                                    (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
192
            mBuffer2[j] = new DistortedFramebuffer(false                     , DistortedSurface.TYPE_SYST,
193
                                                    (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
194
            mBuffer1[j].mMipmap = mipmap;
195
            mipmap *= 0.5f;
196
            }
197
          DistortedSurface.toDo();  // create immediately
198
          }
199

    
200
        numRenders += child.draw(time,mBuffer1[CUR_MIPMAP]);
201
        if( i==num-1 )
202
          {
203
          numRenders += currP.postprocess(time,this);
204
          }
205
        }
206

    
207
      lastP = currP;
208
      lastB = currB;
209
      }
210
/*
211
if( !sNew.equals(sOld) )
212
  {
213
  sOld = sNew;
214
  android.util.Log.e("surface", "Surface"+getID()+": "+sOld);
215
  }
216
*/
217
    return numRenders;
218
    }
219

    
220
///////////////////////////////////////////////////////////////////////////////////////////////////
221

    
222
  void newJob(int t, DistortedNode n, DistortedEffectsPostprocess d)
223
    {
224
    mJobs.add(new Job(t,n,d));
225
    }
226

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

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

    
273
    int numRenders=0;
274

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

    
280
    setAsOutput(time);
281
    numRenders += renderChildren(time,mNumChildren,mChildren);
282

    
283
    return numRenders;
284
    }
285

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

    
299
    if( mTime!=time )
300
      {
301
      mTime = time;
302
      DistortedRenderState.colorDepthOn();
303
      GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
304
      GLES30.glClearDepthf(mClearDepth);
305
      GLES30.glClear( GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT);
306
      }
307
    }
308

    
309
///////////////////////////////////////////////////////////////////////////////////////////////////
310
/**
311
 * Set mipmap level.
312
 * <p>
313
 * Trick for speeding up your renders - one can create a pyramid of OutputSurface objects, each next
314
 * one some constant FACTOR smaller than the previous (0.5 is the common value), then set the Mipmap
315
 * Level of the i-th object to be FACTOR^i (we start counting from 0). When rendering any scene into
316
 * such prepared OutputSurface, the library will make sure to scale any Effects used so that the end
317
 * scene will end up looking identical no matter which object we render to. Identical, that is, except
318
 * for the loss of quality and gain in speed associated with rendering to a smaller Surface.
319
 *
320
 * @param mipmap The mipmap level. Acceptable range: 0&lt;mipmap&lt;infinity, although mipmap&gt;1
321
 *               does not make any sense (that would result in loss of speed and no gain in quality)
322
 */
323
  public void setMipmap(float mipmap)
324
    {
325
    mMipmap = mipmap;
326
    createProjection();
327
    }
328

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

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

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

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

    
389
    createProjection();
390
    }
391

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

    
408
      createProjection();
409

    
410
      if( mColorCreated==CREATED )
411
        {
412
        markForCreation();
413
        recreate();
414
        }
415
      }
416
    }
417

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

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

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

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

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

    
503
    for(int i=0; i<mNumChildren; i++)
504
      {
505
      node = mChildren.get(i);
506

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

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

    
523
      for(int i=0; i<num; i++)
524
        {
525
        job = mJobs.get(i);
526

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

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

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

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

    
577
    for(int i=0; i<num; i++)
578
      {
579
      job = mJobs.remove(0);
580

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

    
598
                       for(int j=mNumChildren-1; j>=0; j--)
599
                         {
600
                         tmp = mChildren.remove(j);
601
                         tmp.setSurfaceParent(null);
602
                         }
603

    
604
                       mNumChildren = 0;
605
                       }
606
                     break;
607
        case SORT  : job.node.setPost(job.dep);
608
                     mChildren.remove(job.node);
609
                     DistortedMaster.addSorted(mChildren,job.node);
610
                     break;
611
        }
612
      }
613
    }
614
}
(8-8/24)