Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedOutputSurface.java @ 041b6dee

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.main;
21

    
22
import android.opengl.GLES30;
23
import android.opengl.Matrix;
24

    
25
import java.util.ArrayList;
26

    
27
///////////////////////////////////////////////////////////////////////////////////////////////////
28

    
29
abstract class DistortedOutputSurface extends DistortedSurface implements DistortedSlave
30
{
31
//////////// DEBUG FLAGS /////////////////////////////////////////////
32
/**
33
 * When rendering a Screen, show FPS in the upper-left corner?
34
 */
35
public static final int DEBUG_FPS = 1;
36
//////////// END DEBUG FLAGS /////////////////////////////////////////
37

    
38
/**
39
 * Do not create DEPTH or STENCIL attachment
40
 */
41
  public static final int NO_DEPTH_NO_STENCIL = 0;
42
/**
43
 * Create DEPTH, but not STENCIL
44
 */
45
  public static final int DEPTH_NO_STENCIL    = 1;
46
/**
47
 * Create both DEPTH and STENCIL
48
 */
49
  public static final int BOTH_DEPTH_STENCIL  = 2;
50

    
51
  private static final int ATTACH = 0;
52
  private static final int DETACH = 1;
53
  private static final int DETALL = 2;
54
  private static final int SORT   = 3;
55

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

    
59
  private class Job
60
    {
61
    int type;
62
    DistortedNode node;
63

    
64
    Job(int t, DistortedNode n)
65
      {
66
      type = t;
67
      node = n;
68
      }
69
    }
70

    
71
  private ArrayList<Job> mJobs = new ArrayList<>();
72

    
73
  DistortedFramebuffer[] mBuffer;
74

    
75
  private long mTime;
76
  private float mFOV;
77
  float mDistance, mNear;
78
  float[] mProjectionMatrix;
79

    
80
  int mDepthStencilCreated;
81
  int mDepthStencil;
82
  int[] mDepthStencilH = new int[1];
83
  int[] mFBOH          = new int[1];
84

    
85
  private float mClearR, mClearG, mClearB, mClearA;
86
  private float mClearDepth;
87
  private int mClearStencil;
88
  private int mClear;
89
  float mMipmap;
90

    
91
  private int mDebugLevel;
92

    
93
private String sLast="", sCurr="";
94

    
95
///////////////////////////////////////////////////////////////////////////////////////////////////
96

    
97
  abstract void prepareDebug(long time);
98
  abstract void renderDebug(long time);
99

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

    
102
  DistortedOutputSurface(int width, int height, int createColor, int numcolors, int depthStencil, int fbo, int type)
103
    {
104
    super(width,height,createColor,numcolors,type);
105

    
106
    mProjectionMatrix = new float[16];
107

    
108
    mFOV = 60.0f;
109
    mNear=  0.5f;
110

    
111
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
112
    mDepthStencil = depthStencil;
113

    
114
    mFBOH[0]         = fbo;
115
    mDepthStencilH[0]= 0;
116

    
117
    mTime = 0;
118
    mDebugLevel = 0;
119

    
120
    mClearR = 0.0f;
121
    mClearG = 0.0f;
122
    mClearB = 0.0f;
123
    mClearA = 0.0f;
124

    
125
    mClearDepth = 1.0f;
126
    mClearStencil = 0;
127
    mClear = GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT;
128

    
129
    mBuffer = new DistortedFramebuffer[EffectQuality.LENGTH];
130

    
131
    mMipmap = 1.0f;
132

    
133
    createProjection();
134
    }
135

    
136
///////////////////////////////////////////////////////////////////////////////////////////////////
137

    
138
  private void createProjection()
139
    {
140
    if( mWidth>0 && mHeight>1 )
141
      {
142
      if( mFOV>0.0f )  // perspective projection
143
        {
144
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
145
        float q = mWidth*mNear;
146
        float c = mHeight*mNear;
147

    
148
        float left   = -q/2;
149
        float right  = +q/2;
150
        float bottom = -c/2;
151
        float top    = +c/2;
152
        float near   =  c/a;
153

    
154
        mDistance    = mHeight/a;
155
        float far    = 2*mDistance-near;
156

    
157
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
158
        }
159
      else             // parallel projection
160
        {
161
        float left   = -mWidth/2.0f;
162
        float right  = +mWidth/2.0f;
163
        float bottom = -mHeight/2.0f;
164
        float top    = +mHeight/2.0f;
165
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
166
        mDistance    = mWidth+mHeight;
167
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
168

    
169
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
170
        }
171
      }
172
    }
173

    
174
///////////////////////////////////////////////////////////////////////////////////////////////////
175

    
176
  private void createBuffers()
177
    {
178
    float mipmap=1.0f;
179

    
180
    for(int j=0; j<EffectQuality.LENGTH; j++)
181
      {
182
      mBuffer[j] = new DistortedFramebuffer(2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
183
      mBuffer[j].mMipmap = mipmap;
184
      mBuffer[j].mNear   = mNear;  // copy mNear as well (for blitting- see PostprocessEffectBlur.apply() )
185
      mipmap *= EffectQuality.MULTIPLIER;
186
      }
187

    
188
    DistortedObject.toDo(); // create the FBOs immediately. This is safe as we must be holding the OpenGL context now.
189

    
190
    GLES30.glStencilMask(0xff);
191
    GLES30.glDepthMask(true);
192
    GLES30.glColorMask(true,true,true,true);
193
    GLES30.glClearColor(0.0f,0.0f,0.0f,0.0f);
194
    GLES30.glClearDepthf(1.0f);
195
    GLES30.glClearStencil(0);
196

    
197
    for(int j=0; j<EffectQuality.LENGTH; j++)
198
      {
199
      mBuffer[j].setAsOutput();
200
      GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mBuffer[j].mColorH[1], 0);
201
      GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
202
      GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mBuffer[j].mColorH[0], 0);
203
      GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
204
      }
205
    }
206

    
207
///////////////////////////////////////////////////////////////////////////////////////////////////
208

    
209
  private int blitWithDepth(long currTime, DistortedFramebuffer buffer)
210
    {
211
    GLES30.glViewport(0, 0, mWidth, mHeight);
212
    setAsOutput(currTime);
213
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
214
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mColorH[0]);
215
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
216
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mDepthStencilH[0]);
217

    
218
    GLES30.glDisable(GLES30.GL_STENCIL_TEST);
219
    GLES30.glStencilMask(0x00);
220

    
221
    DistortedEffects.blitDepthPriv(this);
222
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
223
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
224
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
225
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
226

    
227
    // clear buffers
228
    GLES30.glStencilMask(0xff);
229
    GLES30.glDepthMask(true);
230
    GLES30.glColorMask(true,true,true,true);
231
    GLES30.glClearColor(0.0f,0.0f,0.0f,0.0f);
232
    GLES30.glClearDepthf(1.0f);
233
    GLES30.glClearStencil(0);
234

    
235
    buffer.setAsOutput();
236
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[1], 0);
237
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
238
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[0], 0);
239
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
240

    
241
    return 1;
242
    }
243

    
244
///////////////////////////////////////////////////////////////////////////////////////////////////
245
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
246
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
247
// to a whole buffer and merge it.
248

    
249
  int renderChildren(long time, int numChildren, ArrayList<DistortedNode> children)
250
    {
251
    int quality=0, numRenders = 0, bucketChange = 0;
252
    DistortedNode child1, child2;
253
    DistortedEffects lastEffects=null, currEffects;
254
    long lastBucket=0, currBucket;
255

    
256
sCurr = "";
257

    
258
    for(int i=0; i<numChildren; i++)
259
      {
260
      child1 = children.get(i);
261
      currEffects = child1.getEffects();
262
      currBucket  = currEffects.getBucket();
263

    
264
sCurr += (" "+currBucket);
265

    
266
      if( currBucket==0 ) numRenders += child1.draw(time,this);
267
      else
268
        {
269
        if( mBuffer[0]==null ) createBuffers();
270

    
271
        if( lastBucket!=currBucket )
272
          {
273
          if( lastBucket!=0 )
274
            {
275
            for(int j=bucketChange; j<i; j++)
276
              {
277
              child2 = children.get(j);
278
              numRenders += child2.markStencilAndDepth(time,mBuffer[quality],lastEffects);
279
              }
280

    
281
            numRenders += lastEffects.postprocess(time, this);
282
            numRenders += blitWithDepth(time, mBuffer[quality]);
283
            }
284

    
285
          quality = currEffects.getQuality();
286
          bucketChange = i;
287
          }
288

    
289
        numRenders += child1.draw(time,mBuffer[quality]);
290

    
291
        if( i==numChildren-1 )
292
          {
293
          for(int j=bucketChange; j<numChildren; j++)
294
            {
295
            child2 = children.get(j);
296
            numRenders += child2.markStencilAndDepth(time,mBuffer[quality],currEffects);
297
            }
298

    
299
          numRenders += currEffects.postprocess(time,this);
300
          numRenders += blitWithDepth(time,mBuffer[quality]);
301
          }
302
        }
303

    
304
      lastEffects = currEffects;
305
      lastBucket  = currBucket;
306
      }
307

    
308
if( !sLast.equals(sCurr) ) android.util.Log.e("surface", "rendering: "+sCurr);
309
sLast = sCurr;
310

    
311
    return numRenders;
312
    }
313

    
314
///////////////////////////////////////////////////////////////////////////////////////////////////
315

    
316
  ArrayList<DistortedNode> getChildren()
317
    {
318
    return mChildren;
319
    }
320

    
321
///////////////////////////////////////////////////////////////////////////////////////////////////
322
// PUBLIC API
323
///////////////////////////////////////////////////////////////////////////////////////////////////
324
/**
325
 * Make the library show various debugging information.
326
 * <p>
327
 * Currently only DEBUG_FPS - show FPS in the upper-left corner of every Screen - is defined.
328
 *
329
 * @param bitmask 0, or a bitmask of DEBUG_** flags to enable (currently only DEBUG_FPS defined)
330
 */
331
  public void setDebug(int bitmask)
332
    {
333
    if( this instanceof DistortedScreen )
334
      mDebugLevel = bitmask;
335
    }
336

    
337
///////////////////////////////////////////////////////////////////////////////////////////////////
338

    
339
/**
340
 * Draws all the attached children to this OutputSurface.
341
 * <p>
342
 * Must be called from a thread holding OpenGL Context.
343
 *
344
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
345
 * @return Number of objects rendered.
346
 */
347
  public int render(long time)
348
    {
349
    if( mDebugLevel!=0 ) prepareDebug(time);
350

    
351
    // change tree topology (attach and detach children)
352
/*
353
    boolean changed1 =
354
*/
355
    DistortedMaster.toDo();
356
/*
357
    if( changed1 )
358
      {
359
      for(int i=0; i<mNumChildren; i++)
360
        {
361
        mChildren.get(i).debug(0);
362
        }
363

    
364
      DistortedNode.debugMap();
365
      }
366
*/
367
    // create and delete all underlying OpenGL resources
368
    // Watch out: FIRST change topology, only then deal
369
    // with OpenGL resources. That's because changing Tree
370
    // can result in additional Framebuffers that would need
371
    // to be created immediately, before the calls to drawRecursive()
372
/*
373
    boolean changed2 =
374
*/
375
    toDo();
376
/*
377
    if( changed2 )
378
      {
379
      DistortedObject.debugLists();
380
      }
381
*/
382
    // mark OpenGL state as unknown
383
    DistortedRenderState.reset();
384

    
385
    int numRenders=0;
386

    
387
    for(int i=0; i<mNumChildren; i++)
388
      {
389
      numRenders += mChildren.get(i).renderRecursive(time);
390
      }
391

    
392
    numRenders += renderChildren(time,mNumChildren,mChildren);
393

    
394
    if( mDebugLevel != 0 ) renderDebug(time);
395

    
396
    return numRenders;
397
    }
398

    
399
///////////////////////////////////////////////////////////////////////////////////////////////////
400
/**
401
 * Bind this Surface as a Framebuffer we can render to.
402
 *
403
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
404
 *             out if this is the first time during present frame that this FBO is being set as output.
405
 *             If so, the library, in addition to binding the Surface for output, also clears the
406
 *             Surface's color and depth attachments.
407
 */
408
  public void setAsOutput(long time)
409
    {
410
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
411

    
412
    if( mTime!=time )
413
      {
414
      mTime = time;
415
      DistortedRenderState.colorDepthStencilOn();
416
      GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
417
      GLES30.glClearDepthf(mClearDepth);
418
      GLES30.glClearStencil(mClearStencil);
419
      GLES30.glClear(mClear);
420
      }
421
    }
422

    
423
///////////////////////////////////////////////////////////////////////////////////////////////////
424
/**
425
 * Bind this Surface as a Framebuffer we can render to.
426
 * <p>
427
 * This version does not attempt to clear anything.
428
 */
429

    
430
  public void setAsOutput()
431
    {
432
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
433
    }
434

    
435
///////////////////////////////////////////////////////////////////////////////////////////////////
436
/**
437
 * Return the Near plane of the Projection included in the Surface.
438
 *
439
 * @return the Near plane.
440
 */
441
  public float getNear()
442
    {
443
    return mNear;
444
    }
445

    
446
///////////////////////////////////////////////////////////////////////////////////////////////////
447
/**
448
 * Set mipmap level.
449
 * <p>
450
 * Trick for speeding up your renders - one can create a pyramid of OutputSurface objects, each next
451
 * one some constant FACTOR smaller than the previous (0.5 is the common value), then set the Mipmap
452
 * Level of the i-th object to be FACTOR^i (we start counting from 0). When rendering any scene into
453
 * such prepared OutputSurface, the library will make sure to scale any Effects used so that the end
454
 * scene will end up looking identical no matter which object we render to. Identical, that is, except
455
 * for the loss of quality and gain in speed associated with rendering to a smaller Surface.
456
 * <p>
457
 * Example: if you create two FBOs, one 1000x1000 and another 500x500 in size, and set the second one
458
 * mipmap to 0.5 (the first one's is 1.0 by default), define Effects to be a single move by (100,100),
459
 * and render a skinned Mesh into both FBO, the end result will look proportionally the same, because
460
 * in the second case the move vector (100,100) will be auto-scaled to (50,50).
461
 *
462
 * @param mipmap The mipmap level. Acceptable range: 0&lt;mipmap&lt;infinity, although mipmap&gt;1
463
 *               does not make any sense (that would result in loss of speed and no gain in quality)
464
 */
465
  public void setMipmap(float mipmap)
466
    {
467
    mMipmap = mipmap;
468
    }
469

    
470
///////////////////////////////////////////////////////////////////////////////////////////////////
471
/**
472
 * Set the (R,G,B,A) values of GLES30.glClearColor() to set up color with which to clear
473
 * this Surface at the beginning of each frame.
474
 *
475
 * @param r the Red component. Default: 0.0f
476
 * @param g the Green component. Default: 0.0f
477
 * @param b the Blue component. Default: 0.0f
478
 * @param a the Alpha component. Default: 0.0f
479
 */
480
  public void glClearColor(float r, float g, float b, float a)
481
    {
482
    mClearR = r;
483
    mClearG = g;
484
    mClearB = b;
485
    mClearA = a;
486
    }
487

    
488
///////////////////////////////////////////////////////////////////////////////////////////////////
489
/**
490
 * Uses glClearDepthf() to set up a value with which to clear
491
 * the Depth buffer of our Surface at the beginning of each frame.
492
 *
493
 * @param d the Depth. Default: 1.0f
494
 */
495
  public void glClearDepthf(float d)
496
    {
497
    mClearDepth = d;
498
    }
499

    
500
///////////////////////////////////////////////////////////////////////////////////////////////////
501
/**
502
 * Uses glClearStencil() to set up a value with which to clear the
503
 * Stencil buffer of our Surface at the beginning of each frame.
504
 *
505
 * @param s the Stencil. Default: 0
506
 */
507
  public void glClearStencil(int s)
508
    {
509
    mClearStencil = s;
510
    }
511

    
512
///////////////////////////////////////////////////////////////////////////////////////////////////
513
/**
514
 * Which buffers to Clear at the beginning of each frame?
515
 * <p>
516
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
517
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
518
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
519
 *
520
 * @param mask bitwise OR of BUFFER_BITs to clear.
521
 */
522
  public void glClear(int mask)
523
    {
524
    mClear = mask;
525
    }
526

    
527
///////////////////////////////////////////////////////////////////////////////////////////////////
528
/**
529
 * Create new Projection matrix.
530
 *
531
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
532
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
533
 * @param near Distance between the screen plane and the near plane.
534
 *             Valid vaules: 0<near<1. When near==0, the Near Plane is exactly at the tip of the
535
 *             pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
536
 */
537
  public void setProjection(float fov, float near)
538
    {
539
    if( fov < 180.0f && fov >=0.0f )
540
      {
541
      mFOV = fov;
542
      }
543

    
544
    if( near<   1.0f && near> 0.0f )
545
      {
546
      mNear= near;
547
      }
548
    else if( near<=0.0f )
549
      {
550
      mNear = 0.01f;
551
      }
552
    else if( near>=1.0f )
553
      {
554
      mNear=0.99f;
555
      }
556

    
557
    if( mBuffer[0]!=null )
558
      {
559
      for(int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].mNear = mNear;
560
      }
561

    
562
    createProjection();
563
    }
564

    
565
///////////////////////////////////////////////////////////////////////////////////////////////////
566
/**
567
 * Resize the underlying Framebuffer.
568
 * <p>
569
 * This method can be safely called mid-render as it doesn't interfere with rendering.
570
 *
571
 * @param width The new width.
572
 * @param height The new height.
573
 */
574
  public void resize(int width, int height)
575
    {
576
    if( mWidth!=width || mHeight!=height )
577
      {
578
      mWidth = width;
579
      mHeight= height;
580

    
581
      createProjection();
582

    
583
      if( mColorCreated==CREATED )
584
        {
585
        markForCreation();
586
        recreate();
587
        }
588
      }
589
    }
590

    
591
///////////////////////////////////////////////////////////////////////////////////////////////////
592
/**
593
 * Return true if the Surface contains a DEPTH attachment.
594
 *
595
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
596
 */
597
  public boolean hasDepth()
598
    {
599
    return mDepthStencilCreated==CREATED;
600
    }
601

    
602
///////////////////////////////////////////////////////////////////////////////////////////////////
603
/**
604
 * Return true if the Surface contains a STENCIL attachment.
605
 *
606
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
607
 */
608
  public boolean hasStencil()
609
    {
610
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
611
    }
612

    
613
///////////////////////////////////////////////////////////////////////////////////////////////////
614
/**
615
 * Adds a new child to the last position in the list of our Surface's children.
616
 * <p>
617
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
618
 * DistortedMaster (by calling doWork())
619
 *
620
 * @param node The new Node to add.
621
 */
622
  public void attach(DistortedNode node)
623
    {
624
    mJobs.add(new Job(ATTACH,node));
625
    DistortedMaster.newSlave(this);
626
    }
627

    
628
///////////////////////////////////////////////////////////////////////////////////////////////////
629
/**
630
 * Adds a new child to the last position in the list of our Surface's children.
631
 * <p>
632
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
633
 * DistortedMaster (by calling doWork())
634
 *
635
 * @param surface InputSurface to initialize our child Node with.
636
 * @param effects DistortedEffects to initialize our child Node with.
637
 * @param mesh MeshObject to initialize our child Node with.
638
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
639
 */
640
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
641
    {
642
    DistortedNode node = new DistortedNode(surface,effects,mesh);
643
    mJobs.add(new Job(ATTACH,node));
644
    DistortedMaster.newSlave(this);
645
    return node;
646
    }
647

    
648
///////////////////////////////////////////////////////////////////////////////////////////////////
649
/**
650
 * Removes the first occurrence of a specified child from the list of children of our Surface.
651
 * <p>
652
 * A bit questionable method as there can be many different Nodes attached as children, some
653
 * of them having the same Effects but - for instance - different Mesh. Use with care.
654
 * <p>
655
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
656
 * DistortedMaster (by calling doWork())
657
 *
658
 * @param effects DistortedEffects to remove.
659
 */
660
  public void detach(DistortedEffects effects)
661
    {
662
    long id = effects.getID();
663
    DistortedNode node;
664
    boolean detached = false;
665

    
666
    for(int i=0; i<mNumChildren; i++)
667
      {
668
      node = mChildren.get(i);
669

    
670
      if( node.getEffects().getID()==id )
671
        {
672
        detached = true;
673
        mJobs.add(new Job(DETACH,node));
674
        DistortedMaster.newSlave(this);
675
        break;
676
        }
677
      }
678

    
679
    if( !detached )
680
      {
681
      // if we failed to detach any, it still might be the case that
682
      // there's an ATTACH job that we need to cancel.
683
      int num = mJobs.size();
684
      Job job;
685

    
686
      for(int i=0; i<num; i++)
687
        {
688
        job = mJobs.get(i);
689

    
690
        if( job.type==ATTACH && job.node.getEffects()==effects )
691
          {
692
          mJobs.remove(i);
693
          break;
694
          }
695
        }
696
      }
697
    }
698

    
699
///////////////////////////////////////////////////////////////////////////////////////////////////
700
/**
701
 * Removes the first occurrence of a specified child from the list of children of our Surface.
702
 * <p>
703
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
704
 * DistortedMaster (by calling doWork())
705
 *
706
 * @param node The Node to remove.
707
 */
708
  public void detach(DistortedNode node)
709
    {
710
    mJobs.add(new Job(DETACH,node));
711
    DistortedMaster.newSlave(this);
712
    }
713

    
714
///////////////////////////////////////////////////////////////////////////////////////////////////
715
/**
716
 * Removes all children Nodes.
717
 * <p>
718
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
719
 * DistortedMaster (by calling doWork())
720
 */
721
  public void detachAll()
722
    {
723
    mJobs.add(new Job(DETALL,null));
724
    DistortedMaster.newSlave(this);
725
    }
726

    
727
///////////////////////////////////////////////////////////////////////////////////////////////////
728
/**
729
 * This is not really part of the public API. Has to be public only because it is a part of the
730
 * DistortedSlave interface, which should really be a class that we extend here instead but
731
 * Java has no multiple inheritance.
732
 *
733
 * @y.exclude
734
 */
735
  public void doWork()
736
    {
737
    int num = mJobs.size();
738
    Job job;
739

    
740
    for(int i=0; i<num; i++)
741
      {
742
      job = mJobs.remove(0);
743

    
744
      switch(job.type)
745
        {
746
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
747
                     job.node.setSurfaceParent(this);
748
                     DistortedMaster.addSorted(mChildren,job.node);
749
                     mNumChildren++;
750
                     break;
751
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
752
                       {
753
                       job.node.setSurfaceParent(null);
754
                       mNumChildren--;
755
                       }
756
                     break;
757
        case DETALL: if( mNumChildren>0 )
758
                       {
759
                       DistortedNode tmp;
760

    
761
                       for(int j=mNumChildren-1; j>=0; j--)
762
                         {
763
                         tmp = mChildren.remove(j);
764
                         tmp.setSurfaceParent(null);
765
                         }
766

    
767
                       mNumChildren = 0;
768
                       }
769
                     break;
770
        case SORT  : mChildren.remove(job.node);
771
                     DistortedMaster.addSorted(mChildren,job.node);
772
                     break;
773
        }
774
      }
775
    }
776
}
(8-8/23)