Project

General

Profile

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

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

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 DistortedAttacheable
29
{
30
  private ArrayList<DistortedNode> mChildren;
31
  private int mNumChildren;   // ==mChildren.length(), but we only create mChildren if the first one gets added
32

    
33
  DistortedFramebuffer mBuffer1, mBuffer2;
34

    
35
  private long mTime;
36
  private float mFOV;
37
  int mWidth,mHeight,mDepth;
38
  float mDistance, mNear;
39
  float[] mProjectionMatrix;
40

    
41
  int mDepthCreated;
42
  int[] mDepthH = new int[1];
43
  int[] mFBOH   = new int[1];
44

    
45
  private float mClearR, mClearG, mClearB, mClearA;
46
  private float mClearDepth;
47

    
48
///////////////////////////////////////////////////////////////////////////////////////////////////
49

    
50
  DistortedOutputSurface(int width, int height, int createColor, int createDepth, int fbo, int type)
51
    {
52
    super(width,height,createColor,type);
53

    
54
    mProjectionMatrix = new float[16];
55

    
56
    mWidth = width;
57
    mHeight= height;
58

    
59
    mFOV = 60.0f;
60
    mNear=  0.5f;
61

    
62
    mDepthCreated= createDepth;
63
    mFBOH[0]     = fbo;
64
    mDepthH[0]   = 0;
65

    
66
    mTime = 0;
67

    
68
    mClearR = 0.0f;
69
    mClearG = 0.0f;
70
    mClearB = 0.0f;
71
    mClearA = 0.0f;
72

    
73
    mClearDepth = 1.0f;
74

    
75
    createProjection();
76
    }
77

    
78
///////////////////////////////////////////////////////////////////////////////////////////////////
79

    
80
  void createProjection()
81
    {
82
    if( mWidth>0 && mHeight>1 )
83
      {
84
      if( mFOV>0.0f )  // perspective projection
85
        {
86
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
87
        float q = mWidth*mNear;
88
        float c = mHeight*mNear;
89

    
90
        float left   = -q/2;
91
        float right  = +q/2;
92
        float bottom = -c/2;
93
        float top    = +c/2;
94
        float near   =  c/a;
95

    
96
        mDistance    = mHeight/a;
97
        float far    = 2*mDistance-near;
98
        mDepth       = (int)((far-near)/2);
99

    
100
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
101
        }
102
      else             // parallel projection
103
        {
104
        float left   = -mWidth /2.0f;
105
        float right  = +mWidth /2.0f;
106
        float bottom = -mHeight/2.0f;
107
        float top    = +mHeight/2.0f;
108
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
109
        mDistance    = mWidth+mHeight;
110
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
111
        mDepth       = (int)((far-near)/2);
112

    
113
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
114
        }
115
      }
116
    }
117

    
118
///////////////////////////////////////////////////////////////////////////////////////////////////
119

    
120
  int renderChildren(long time, int num, ArrayList<DistortedNode> children)
121
    {
122
    int numRenders = 0;
123
    DistortedNode child;
124
    EffectQueuePostprocess lastP=null, currP;
125
    long lastB=0, currB;
126

    
127
    // Render all children, one by one.
128
    // If there are no postprocessing effects, just render to THIS.
129
    // Otherwise, render to a buffer and on each change of Postprocessing Bucket,
130
    // apply the postprocessing to a whole buffer and merge it.
131

    
132
    for(int i=0; i<num; i++)
133
      {
134
      child = children.get(i);
135
      currP = child.getPostprocess();
136
      currB = currP==null ? 0 : currP.getBucket();
137

    
138
      if( lastB!=currB && lastB!=0 )
139
        {
140
        //android.util.Log.e("output", "i="+i+" postprocess and merge");
141
        numRenders += lastP.postprocess(time,this);
142
        }
143

    
144
      if( currB==0 )
145
        {
146
        //android.util.Log.e("output", "i="+i+" draw to this");
147
        numRenders += child.draw(time,this);
148
        }
149
      else
150
        {
151
        if( mBuffer1==null )
152
          {
153
          mBuffer1 = new DistortedFramebuffer(mDepthCreated!=DONT_CREATE, DistortedSurface.TYPE_TREE, mWidth, mHeight);
154
          mBuffer2 = new DistortedFramebuffer(false                     , DistortedSurface.TYPE_TREE, mWidth, mHeight);
155
          }
156

    
157
        //android.util.Log.e("output", "i="+i+" draw to buffer");
158
        numRenders += child.draw(time,mBuffer1);
159
        if( i==num-1 )
160
          {
161
          //android.util.Log.e("output", "i="+i+" postprocess and merge");
162
          numRenders += currP.postprocess(time,this);
163
          }
164
        }
165

    
166
      lastP = currP;
167
      lastB = currB;
168
      }
169

    
170
    return numRenders;
171
    }
172

    
173
///////////////////////////////////////////////////////////////////////////////////////////////////
174
// PUBLIC API
175
///////////////////////////////////////////////////////////////////////////////////////////////////
176
/**
177
 * Draws all the attached children to this OutputSurface.
178
 * <p>
179
 * Must be called from a thread holding OpenGL Context.
180
 *
181
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
182
 * @return Number of objects rendered.
183
 */
184
  public int render(long time)
185
    {
186
    // change tree topology (attach and detach children)
187
/*
188
    boolean changed =
189
*/
190
    DistortedAttachDaemon.toDo();
191
/*
192
    // debugging only
193
    if( changed )
194
      {
195
      for(int i=0; i<mNumChildren; i++)
196
        {
197
        mChildren.get(i).debug(0);
198
        }
199

    
200
      DistortedNode.debugMap();
201
      }
202
*/
203
    // create and delete all underlying OpenGL resources
204
    // Watch out: FIRST change topology, only then deal
205
    // with OpenGL resources. That's because changing Tree
206
    // can result in additional Framebuffers that would need
207
    // to be created immediately, before the calls to drawRecursive()
208
    toDo();
209
/*
210
    // debugging only
211
    if( changed )
212
      {
213
      DistortedSurface.debugLists();
214
      }
215
*/
216
    // mark OpenGL state as unknown
217
    DistortedRenderState.reset();
218

    
219
    int numRenders=0;
220

    
221
    for(int i=0; i<mNumChildren; i++)
222
      {
223
      numRenders += mChildren.get(i).renderRecursive(time);
224
      }
225

    
226
    setAsOutput(time);
227
    numRenders += renderChildren(time,mNumChildren,mChildren);
228

    
229
    return numRenders;
230
    }
231

    
232
///////////////////////////////////////////////////////////////////////////////////////////////////
233
/**
234
 * Bind this Surface as a Framebuffer we can render to.
235
 *
236
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
237
 *             out if this is the first time during present frame that this FBO is being set as output.
238
 *             If so, the library, in addition to binding the Surface for output, also clears the
239
 *             Surface's color and depth attachments.
240
 */
241
  public void setAsOutput(long time)
242
    {
243
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
244

    
245
    if( mTime!=time )
246
      {
247
      mTime = time;
248
      DistortedRenderState.colorDepthOn();
249
      GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
250
      GLES30.glClearDepthf(mClearDepth);
251
      GLES30.glClear( GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT);
252
      }
253
    }
254

    
255
///////////////////////////////////////////////////////////////////////////////////////////////////
256
/**
257
 * Set the (R,G,B,A) values of GLES30.glClearColor() to set up color with which to clear
258
 * this Surface before each render.
259
 *
260
 * @param r the Red component. Default: 0.0f
261
 * @param g the Green component. Default: 0.0f
262
 * @param b the Blue component. Default: 0.0f
263
 * @param a the Alpha component. Default: 0.0f
264
 */
265
  public void glClearColor(float r, float g, float b, float a)
266
    {
267
    mClearR = r;
268
    mClearG = g;
269
    mClearB = b;
270
    mClearA = a;
271
    }
272

    
273
///////////////////////////////////////////////////////////////////////////////////////////////////
274
/**
275
 * Set the Depth value of GLES30.glClearDepthf() to set up depth with which to clear
276
 * the Depth buffer of Surface before each render.
277
 *
278
 * @param d the Depth. Default: 1.0f
279
 */
280
  public void glClearDepthf(float d)
281
    {
282
    mClearDepth = d;
283
    }
284

    
285
///////////////////////////////////////////////////////////////////////////////////////////////////
286
/**
287
 * Create new Projection matrix.
288
 *
289
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
290
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
291
 * @param near Distance between the screen plane and the near plane.
292
 *             Valid vaules: 0<near<1. When near==0, the Near Plane is exactly at the tip of the
293
 *             pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
294
 */
295
  public void setProjection(float fov, float near)
296
    {
297
    if( fov < 180.0f && fov >=0.0f )
298
      {
299
      mFOV = fov;
300
      }
301

    
302
    if( near<   1.0f && near> 0.0f )
303
      {
304
      mNear= near;
305
      }
306
    else if( near<=0.0f )
307
      {
308
      mNear = 0.01f;
309
      }
310
    else if( near>=1.0f )
311
      {
312
      mNear=0.99f;
313
      }
314

    
315
    createProjection();
316
    }
317

    
318
///////////////////////////////////////////////////////////////////////////////////////////////////
319
/**
320
 * Resize the underlying Framebuffer.
321
 * <p>
322
 * This method can be safely called mid-render as it doesn't interfere with rendering.
323
 *
324
 * @param width The new width.
325
 * @param height The new height.
326
 */
327
  public void resize(int width, int height)
328
    {
329
    if( mWidth!=width || mHeight!=height )
330
      {
331
      mWidth = width;
332
      mHeight= height;
333
      mSizeX = width;
334
      mSizeY = height;
335

    
336
      createProjection();
337

    
338
      if( mColorCreated==CREATED )
339
        {
340
        markForCreation();
341
        recreate();
342
        }
343
      }
344
    }
345

    
346
///////////////////////////////////////////////////////////////////////////////////////////////////
347
/**
348
 * Create a new DEPTH buffer and attach it or (param=false) detach an existing DEPTH attachment and recreate it.
349
 *
350
 * @param enable <bold>true</bold> if we want to attach a new DEPTH buffer to the FBO.<br>
351
 *               <bold>false</bold> if we want to detach the DEPTH attachment.
352
 */
353
  public void enableDepth(boolean enable)
354
    {
355
    if( enable && mDepthCreated==DONT_CREATE )
356
      {
357
      mDepthCreated = NOT_CREATED_YET;
358
      markForCreation();
359
      }
360
    if( !enable && mDepthCreated!=DONT_CREATE )
361
      {
362
      mDepthCreated = DONT_CREATE;
363
      markForCreation();
364
      }
365
    }
366

    
367
///////////////////////////////////////////////////////////////////////////////////////////////////
368
/**
369
 * Return true if the Surface contains a DEPTH attachment.
370
 *
371
 * @return <bold>true</bold> if the FBO contains a DEPTH attachment.
372
 */
373
  public boolean hasDepth()
374
    {
375
    return mDepthCreated==CREATED;
376
    }
377

    
378
///////////////////////////////////////////////////////////////////////////////////////////////////
379
/**
380
 * Adds a new child to the last position in the list of our Surface's children.
381
 * <p>
382
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
383
 * DistortedAttachDeamon (by calling attachNow())
384
 *
385
 * @param node The new Node to add.
386
 */
387
  public void attach(DistortedNode node)
388
    {
389
    DistortedAttachDaemon.attach(this,node);
390
    }
391

    
392
///////////////////////////////////////////////////////////////////////////////////////////////////
393
/**
394
 * Adds a new child to the last position in the list of our Surface's children.
395
 * <p>
396
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
397
 * DistortedAttachDeamon (by calling attachNow())
398
 *
399
 * @param surface InputSurface to initialize our child Node with.
400
 * @param effects DistortedEffects to initialize our child Node with.
401
 * @param mesh MeshObject to initialize our child Node with.
402
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
403
 */
404
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
405
    {
406
    DistortedNode node = new DistortedNode(surface,effects,mesh);
407
    DistortedAttachDaemon.attach(this,node);
408
    return node;
409
    }
410

    
411
///////////////////////////////////////////////////////////////////////////////////////////////////
412
/**
413
 * This is not really part of the public API. Has to be public only because it is a part of the
414
 * DistortedAttacheable interface, which should really be a class that we extend here instead but
415
 * Java has no multiple inheritance.
416
 *
417
 * @y.exclude
418
 * @param node new Node to add.
419
 */
420
  public void attachNow(DistortedNode node)
421
    {
422
    if( mChildren==null ) mChildren = new ArrayList<>(2);
423
    mChildren.add(node);
424
    mNumChildren++;
425
    }
426

    
427
///////////////////////////////////////////////////////////////////////////////////////////////////
428
/**
429
 * Removes the first occurrence of a specified child from the list of children of our Surface.
430
 * <p>
431
 * A bit questionable method as there can be many different Nodes attached as children, some
432
 * of them having the same Effects but - for instance - different Mesh. Use with care.
433
 * <p>
434
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
435
 * DistortedAttachDeamon (by calling detachNow())
436
 *
437
 * @param effects DistortedEffects to remove.
438
 */
439
  public void detach(DistortedEffects effects)
440
    {
441
    long id = effects.getID();
442
    DistortedNode node;
443
    boolean detached = false;
444

    
445
    for(int i=0; i<mNumChildren; i++)
446
      {
447
      node = mChildren.get(i);
448

    
449
      if( node.getEffects().getID()==id )
450
        {
451
        detached = true;
452
        DistortedAttachDaemon.detach(this,node);
453
        break;
454
        }
455
      }
456

    
457
    if( !detached )
458
      {
459
      // if we failed to detach any, it still might be the case that
460
      // there's a job in Daemon's queue that we need to cancel.
461
      DistortedAttachDaemon.cancelAttachJobs(this,effects);
462
      }
463
    }
464

    
465
///////////////////////////////////////////////////////////////////////////////////////////////////
466
/**
467
 * Removes the first occurrence of a specified child from the list of children of our Surface.
468
 * <p>
469
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
470
 * DistortedAttachDeamon (by calling detachNow())
471
 *
472
 * @param node The Node to remove.
473
 */
474
  public void detach(DistortedNode node)
475
    {
476
    DistortedAttachDaemon.detach(this,node);
477
    }
478

    
479
///////////////////////////////////////////////////////////////////////////////////////////////////
480
/**
481
 * This is not really part of the public API. Has to be public only because it is a part of the
482
 * DistortedAttacheable interface, which should really be a class that we extend here instead but
483
 * Java has no multiple inheritance.
484
 *
485
 * @y.exclude
486
 * @param node The Node to remove.
487
 */
488
  public void detachNow(DistortedNode node)
489
    {
490
    if( mNumChildren>0 && mChildren.remove(node) )
491
      {
492
      mNumChildren--;
493
      }
494
    }
495

    
496
///////////////////////////////////////////////////////////////////////////////////////////////////
497
/**
498
 * Removes all children Nodes.
499
 * <p>
500
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
501
 * DistortedAttachDeamon (by calling detachAllNow())
502
 */
503
  public void detachAll()
504
    {
505
    DistortedAttachDaemon.detachAll(this);
506
    }
507

    
508
///////////////////////////////////////////////////////////////////////////////////////////////////
509
/**
510
 * This is not really part of the public API. Has to be public only because it is a part of the
511
 * DistortedAttacheable interface, which should really be a class that we extend here instead but
512
 * Java has no multiple inheritance.
513
 *
514
 * @y.exclude
515
 */
516
  public void detachAllNow()
517
    {
518
    if( mNumChildren>0 )
519
      {
520
      mNumChildren = 0;
521
      mChildren.clear();
522
      }
523
    }
524
}
(9-9/24)