Project

General

Profile

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

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

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
    DistortedEffectsPostprocess dep;
64

    
65
    Job(int t, DistortedNode n, DistortedEffectsPostprocess d)
66
      {
67
      type = t;
68
      node = n;
69
      dep  = d;
70
      }
71
    }
72

    
73
  private ArrayList<Job> mJobs = new ArrayList<>();
74

    
75
  DistortedFramebuffer[] mBuffer;
76

    
77
  private long mTime;
78
  private float mFOV;
79
  float mDistance, mNear;
80
  float[] mProjectionMatrix;
81

    
82
  int mDepthStencilCreated;
83
  int mDepthStencil;
84
  int[] mDepthStencilH = new int[1];
85
  int[] mFBOH          = new int[1];
86

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

    
93
  private int mDebugLevel;
94

    
95
private String sLast="", sCurr="";
96

    
97
///////////////////////////////////////////////////////////////////////////////////////////////////
98

    
99
  abstract void prepareDebug(long time);
100
  abstract void renderDebug(long time);
101

    
102
///////////////////////////////////////////////////////////////////////////////////////////////////
103

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

    
108
    mProjectionMatrix = new float[16];
109

    
110
    mFOV = 60.0f;
111
    mNear=  0.5f;
112

    
113
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
114
    mDepthStencil = depthStencil;
115

    
116
    mFBOH[0]         = fbo;
117
    mDepthStencilH[0]= 0;
118

    
119
    mTime = 0;
120
    mDebugLevel = 0;
121

    
122
    mClearR = 0.0f;
123
    mClearG = 0.0f;
124
    mClearB = 0.0f;
125
    mClearA = 0.0f;
126

    
127
    mClearDepth = 1.0f;
128
    mClearStencil = 0;
129
    mClear = GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT;
130

    
131
    mBuffer = new DistortedFramebuffer[EffectQuality.LENGTH];
132

    
133
    mMipmap = 1.0f;
134

    
135
    createProjection();
136
    }
137

    
138
///////////////////////////////////////////////////////////////////////////////////////////////////
139

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

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

    
156
        mDistance    = mHeight/a;
157
        float far    = 2*mDistance-near;
158

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

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

    
176
///////////////////////////////////////////////////////////////////////////////////////////////////
177

    
178
  private void createBuffers()
179
    {
180
    float mipmap=1.0f;
181

    
182
    for(int j=0; j<EffectQuality.LENGTH; j++)
183
      {
184
      mBuffer[j] = new DistortedFramebuffer(2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
185
      mBuffer[j].mMipmap = mipmap;
186
      mipmap *= EffectQuality.MULTIPLIER;
187
      }
188

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

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

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

    
208
///////////////////////////////////////////////////////////////////////////////////////////////////
209

    
210
  private int blitWithDepth(int quality, long currTime)
211
    {
212
    DistortedFramebuffer buffer = mBuffer[quality];
213

    
214
    GLES30.glViewport(0, 0, mWidth, mHeight);
215
    setAsOutput(currTime);
216
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
217
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mColorH[0]);
218
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
219
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mDepthStencilH[0]);
220

    
221
    GLES30.glDisable(GLES30.GL_STENCIL_TEST);
222
    GLES30.glStencilMask(0x00);
223

    
224
    DistortedEffects.blitDepthPriv(this);
225
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
226
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
227
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
228
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
229

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

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

    
244
    return 1;
245
    }
246

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

    
252
  int renderChildren(long time, int num, ArrayList<DistortedNode> children)
253
    {
254
    int numRenders = 0;
255
    DistortedNode child1, child2;
256
    DistortedEffectsPostprocess lastP=null, currP;
257
    long lastB=0, currB;
258
    int bucketChange=0;
259
    int lastQ=0, currQ;
260

    
261
sCurr = "";
262

    
263
    for(int i=0; i<num; i++)
264
      {
265
      child1 = children.get(i);
266
      currP = child1.getEffectsPostprocess();
267
      currB = currP==null ? 0 : currP.getBucket();
268
      currQ = currP==null ? 0 : currP.getQuality();
269

    
270
sCurr += (" "+currB);
271

    
272
      if( currB==0 ) numRenders += child1.draw(time,this);
273
      else
274
        {
275
        if( mBuffer[0]==null ) createBuffers();
276

    
277
        if( lastB!=currB )
278
          {
279
          if( lastB!=0 )
280
            {
281
            for(int j=bucketChange; j<i; j++)
282
              {
283
              child2 = children.get(j);
284
              numRenders += child2.markStencilAndDepth(time,mBuffer[lastQ],lastP);
285
              }
286

    
287
            numRenders += lastP.postprocess(time, this);
288
            numRenders += blitWithDepth(lastQ,time);
289
            }
290

    
291
          bucketChange = i;
292
          }
293

    
294
        numRenders += child1.draw(time,mBuffer[currQ]);
295

    
296
        if( i==num-1 )
297
          {
298
          for(int j=bucketChange; j<num; j++)
299
            {
300
            child2 = children.get(j);
301
            numRenders += child2.markStencilAndDepth(time,mBuffer[currQ],currP);
302
            }
303

    
304
          numRenders += currP.postprocess(time,this);
305
          numRenders += blitWithDepth(currQ,time);
306
          }
307
        }
308

    
309
      lastQ = currQ;
310
      lastP = currP;
311
      lastB = currB;
312
      }
313

    
314
if( !sLast.equals(sCurr) ) android.util.Log.e("surface", "rendering: "+sCurr);
315
sLast = sCurr;
316

    
317
    return numRenders;
318
    }
319

    
320
///////////////////////////////////////////////////////////////////////////////////////////////////
321

    
322
  void newJob(int t, DistortedNode n, DistortedEffectsPostprocess d)
323
    {
324
    mJobs.add(new Job(t,n,d));
325
    }
326

    
327
///////////////////////////////////////////////////////////////////////////////////////////////////
328

    
329
  void setAsOutput()
330
    {
331
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
332
    }
333

    
334
///////////////////////////////////////////////////////////////////////////////////////////////////
335
// PUBLIC API
336
///////////////////////////////////////////////////////////////////////////////////////////////////
337
/**
338
 * Make the library show various debugging information.
339
 * <p>
340
 * Currently only DEBUG_FPS - show FPS in the upper-left corner of every Screen - is defined.
341
 *
342
 * @param bitmask 0, or a bitmask of DEBUG_** flags to enable (currently only DEBUG_FPS defined)
343
 */
344
  public void setDebug(int bitmask)
345
    {
346
    mDebugLevel = bitmask;
347
    }
348

    
349
///////////////////////////////////////////////////////////////////////////////////////////////////
350

    
351
/**
352
 * Draws all the attached children to this OutputSurface.
353
 * <p>
354
 * Must be called from a thread holding OpenGL Context.
355
 *
356
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
357
 * @return Number of objects rendered.
358
 */
359
  public int render(long time)
360
    {
361
    boolean showDebug = ( mDebugLevel!=0 && this instanceof DistortedScreen );
362

    
363
    if( showDebug ) prepareDebug(time);
364

    
365
    // change tree topology (attach and detach children)
366
/*
367
    boolean changed1 =
368
*/
369
    DistortedMaster.toDo();
370
/*
371
    if( changed1 )
372
      {
373
      for(int i=0; i<mNumChildren; i++)
374
        {
375
        mChildren.get(i).debug(0);
376
        }
377

    
378
      DistortedNode.debugMap();
379
      }
380
*/
381
    // create and delete all underlying OpenGL resources
382
    // Watch out: FIRST change topology, only then deal
383
    // with OpenGL resources. That's because changing Tree
384
    // can result in additional Framebuffers that would need
385
    // to be created immediately, before the calls to drawRecursive()
386
/*
387
    boolean changed2 =
388
*/
389
    toDo();
390
/*
391
    if( changed2 )
392
      {
393
      DistortedObject.debugLists();
394
      }
395
*/
396
    // mark OpenGL state as unknown
397
    DistortedRenderState.reset();
398

    
399
    int numRenders=0;
400

    
401
    for(int i=0; i<mNumChildren; i++)
402
      {
403
      numRenders += mChildren.get(i).renderRecursive(time);
404
      }
405

    
406
    setAsOutput(time);
407
    numRenders += renderChildren(time,mNumChildren,mChildren);
408

    
409
    if( showDebug ) renderDebug(time);
410

    
411
    return numRenders;
412
    }
413

    
414
///////////////////////////////////////////////////////////////////////////////////////////////////
415
/**
416
 * Bind this Surface as a Framebuffer we can render to.
417
 *
418
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
419
 *             out if this is the first time during present frame that this FBO is being set as output.
420
 *             If so, the library, in addition to binding the Surface for output, also clears the
421
 *             Surface's color and depth attachments.
422
 */
423
  public void setAsOutput(long time)
424
    {
425
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
426

    
427
    if( mTime!=time )
428
      {
429
      mTime = time;
430
      DistortedRenderState.colorDepthStencilOn();
431
      GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
432
      GLES30.glClearDepthf(mClearDepth);
433
      GLES30.glClearStencil(mClearStencil);
434
      GLES30.glClear(mClear);
435
      }
436
    }
437

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

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

    
480
///////////////////////////////////////////////////////////////////////////////////////////////////
481
/**
482
 * Uses glClearDepthf() to set up a value with which to clear
483
 * the Depth buffer of our Surface at the beginning of each frame.
484
 *
485
 * @param d the Depth. Default: 1.0f
486
 */
487
  public void glClearDepthf(float d)
488
    {
489
    mClearDepth = d;
490
    }
491

    
492
///////////////////////////////////////////////////////////////////////////////////////////////////
493
/**
494
 * Uses glClearStencil() to set up a value with which to clear the
495
 * Stencil buffer of our Surface at the beginning of each frame.
496
 *
497
 * @param s the Stencil. Default: 0
498
 */
499
  public void glClearStencil(int s)
500
    {
501
    mClearStencil = s;
502
    }
503

    
504
///////////////////////////////////////////////////////////////////////////////////////////////////
505
/**
506
 * Which buffers to Clear at the beginning of each frame?
507
 * <p>
508
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
509
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
510
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
511
 *
512
 * @param mask bitwise OR of BUFFER_BITs to clear.
513
 */
514
  public void glClear(int mask)
515
    {
516
    mClear = mask;
517
    }
518

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

    
536
    if( near<   1.0f && near> 0.0f )
537
      {
538
      mNear= near;
539
      }
540
    else if( near<=0.0f )
541
      {
542
      mNear = 0.01f;
543
      }
544
    else if( near>=1.0f )
545
      {
546
      mNear=0.99f;
547
      }
548

    
549
    createProjection();
550
    }
551

    
552
///////////////////////////////////////////////////////////////////////////////////////////////////
553
/**
554
 * Resize the underlying Framebuffer.
555
 * <p>
556
 * This method can be safely called mid-render as it doesn't interfere with rendering.
557
 *
558
 * @param width The new width.
559
 * @param height The new height.
560
 */
561
  public void resize(int width, int height)
562
    {
563
    if( mWidth!=width || mHeight!=height )
564
      {
565
      mWidth = width;
566
      mHeight= height;
567

    
568
      createProjection();
569

    
570
      if( mColorCreated==CREATED )
571
        {
572
        markForCreation();
573
        recreate();
574
        }
575
      }
576
    }
577

    
578
///////////////////////////////////////////////////////////////////////////////////////////////////
579
/**
580
 * Return true if the Surface contains a DEPTH attachment.
581
 *
582
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
583
 */
584
  public boolean hasDepth()
585
    {
586
    return mDepthStencilCreated==CREATED;
587
    }
588

    
589
///////////////////////////////////////////////////////////////////////////////////////////////////
590
/**
591
 * Return true if the Surface contains a STENCIL attachment.
592
 *
593
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
594
 */
595
  public boolean hasStencil()
596
    {
597
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
598
    }
599

    
600
///////////////////////////////////////////////////////////////////////////////////////////////////
601
/**
602
 * Adds a new child to the last position in the list of our Surface's children.
603
 * <p>
604
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
605
 * DistortedMaster (by calling doWork())
606
 *
607
 * @param node The new Node to add.
608
 */
609
  public void attach(DistortedNode node)
610
    {
611
    mJobs.add(new Job(ATTACH,node,null));
612
    DistortedMaster.newSlave(this);
613
    }
614

    
615
///////////////////////////////////////////////////////////////////////////////////////////////////
616
/**
617
 * Adds a new child to the last position in the list of our Surface's children.
618
 * <p>
619
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
620
 * DistortedMaster (by calling doWork())
621
 *
622
 * @param surface InputSurface to initialize our child Node with.
623
 * @param effects DistortedEffects to initialize our child Node with.
624
 * @param mesh MeshObject to initialize our child Node with.
625
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
626
 */
627
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
628
    {
629
    DistortedNode node = new DistortedNode(surface,effects,mesh);
630
    mJobs.add(new Job(ATTACH,node,null));
631
    DistortedMaster.newSlave(this);
632
    return node;
633
    }
634

    
635
///////////////////////////////////////////////////////////////////////////////////////////////////
636
/**
637
 * Removes the first occurrence of a specified child from the list of children of our Surface.
638
 * <p>
639
 * A bit questionable method as there can be many different Nodes attached as children, some
640
 * of them having the same Effects but - for instance - different Mesh. Use with care.
641
 * <p>
642
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
643
 * DistortedMaster (by calling doWork())
644
 *
645
 * @param effects DistortedEffects to remove.
646
 */
647
  public void detach(DistortedEffects effects)
648
    {
649
    long id = effects.getID();
650
    DistortedNode node;
651
    boolean detached = false;
652

    
653
    for(int i=0; i<mNumChildren; i++)
654
      {
655
      node = mChildren.get(i);
656

    
657
      if( node.getEffects().getID()==id )
658
        {
659
        detached = true;
660
        mJobs.add(new Job(DETACH,node,null));
661
        DistortedMaster.newSlave(this);
662
        break;
663
        }
664
      }
665

    
666
    if( !detached )
667
      {
668
      // if we failed to detach any, it still might be the case that
669
      // there's an ATTACH job that we need to cancel.
670
      int num = mJobs.size();
671
      Job job;
672

    
673
      for(int i=0; i<num; i++)
674
        {
675
        job = mJobs.get(i);
676

    
677
        if( job.type==ATTACH && job.node.getEffects()==effects )
678
          {
679
          mJobs.remove(i);
680
          break;
681
          }
682
        }
683
      }
684
    }
685

    
686
///////////////////////////////////////////////////////////////////////////////////////////////////
687
/**
688
 * Removes the first occurrence of a specified child from the list of children of our Surface.
689
 * <p>
690
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
691
 * DistortedMaster (by calling doWork())
692
 *
693
 * @param node The Node to remove.
694
 */
695
  public void detach(DistortedNode node)
696
    {
697
    mJobs.add(new Job(DETACH,node,null));
698
    DistortedMaster.newSlave(this);
699
    }
700

    
701
///////////////////////////////////////////////////////////////////////////////////////////////////
702
/**
703
 * Removes all children Nodes.
704
 * <p>
705
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
706
 * DistortedMaster (by calling doWork())
707
 */
708
  public void detachAll()
709
    {
710
    mJobs.add(new Job(DETALL,null,null));
711
    DistortedMaster.newSlave(this);
712
    }
713

    
714
///////////////////////////////////////////////////////////////////////////////////////////////////
715
/**
716
 * This is not really part of the public API. Has to be public only because it is a part of the
717
 * DistortedSlave interface, which should really be a class that we extend here instead but
718
 * Java has no multiple inheritance.
719
 *
720
 * @y.exclude
721
 */
722
  public void doWork()
723
    {
724
    int num = mJobs.size();
725
    Job job;
726

    
727
    for(int i=0; i<num; i++)
728
      {
729
      job = mJobs.remove(0);
730

    
731
      switch(job.type)
732
        {
733
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
734
                     job.node.setSurfaceParent(this);
735
                     DistortedMaster.addSorted(mChildren,job.node);
736
                     mNumChildren++;
737
                     break;
738
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
739
                       {
740
                       job.node.setSurfaceParent(null);
741
                       mNumChildren--;
742
                       }
743
                     break;
744
        case DETALL: if( mNumChildren>0 )
745
                       {
746
                       DistortedNode tmp;
747

    
748
                       for(int j=mNumChildren-1; j>=0; j--)
749
                         {
750
                         tmp = mChildren.remove(j);
751
                         tmp.setSurfaceParent(null);
752
                         }
753

    
754
                       mNumChildren = 0;
755
                       }
756
                     break;
757
        case SORT  : job.node.setPost(job.dep);
758
                     mChildren.remove(job.node);
759
                     DistortedMaster.addSorted(mChildren,job.node);
760
                     break;
761
        }
762
      }
763
    }
764
}
(9-9/24)