Project

General

Profile

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

library / src / main / java / org / distorted / library / DistortedNode.java @ 3e95b421

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 java.util.ArrayList;
23
import java.util.HashMap;
24

    
25
import android.opengl.GLES30;
26

    
27
///////////////////////////////////////////////////////////////////////////////////////////////////
28
/**
29
 * Class which represents a Node in a Tree of (InputSurface,Mesh,Effects) triplets.
30
 * <p>
31
 * Having organized such sets into a Tree, we can then render any Node to any OutputSurface.
32
 * That recursively renders the set held in the Node and all its children.
33
 * <p>
34
 * The class takes special care to only render identical sub-trees once. Each Node holds a reference
35
 * to sub-class 'NodeData'. Two identical sub-trees attached at different points of the main tree
36
 * will point to the same NodeData; only the first of this is rendered (mData.numRender!).
37
 */
38
public class DistortedNode implements DistortedAttacheable
39
  {
40
  private static HashMap<ArrayList<Long>,NodeData> mMapNodeID = new HashMap<>();
41
  private static long mNextNodeID =0;
42

    
43
  private DistortedNode mParent;
44
  private MeshObject mMesh;
45
  private DistortedEffects mEffects;
46
  private DistortedInputSurface mSurface;
47
  private DistortedRenderState mState;
48
  private NodeData mData;
49

    
50
  private ArrayList<DistortedNode> mChildren;
51
  private int[] mNumChildren;  // ==mChildren.length(), but we only create mChildren if the first one gets added
52

    
53
  private class NodeData
54
    {
55
    long ID;
56
    int numPointingNodes;
57
    long currTime;
58
    ArrayList<Long> key;
59
    DistortedFramebuffer mFBO;
60

    
61
    NodeData(long id, ArrayList<Long> k)
62
      {
63
      ID              = id;
64
      key             = k;
65
      numPointingNodes= 1;
66
      currTime        =-1;
67
      mFBO            = null;
68
      }
69
    }
70
 
71
///////////////////////////////////////////////////////////////////////////////////////////////////
72

    
73
  static synchronized void onDestroy()
74
    {
75
    mNextNodeID = 0;
76
    mMapNodeID.clear();
77
    }
78

    
79
///////////////////////////////////////////////////////////////////////////////////////////////////
80

    
81
  private ArrayList<Long> generateIDList()
82
    {
83
    ArrayList<Long> ret = new ArrayList<>();
84
     
85
    ret.add( mSurface.getID() );
86

    
87
    if( mNumChildren[0]==0 )
88
      {
89
      ret.add(-mEffects.getID());
90
      }
91

    
92
    DistortedNode node;
93
   
94
    for(int i=0; i<mNumChildren[0]; i++)
95
      {
96
      node = mChildren.get(i);
97
      ret.add(node.mData.ID);
98
      }
99
   
100
    return ret;
101
    }
102

    
103
///////////////////////////////////////////////////////////////////////////////////////////////////
104
// Debug - print all the Node IDs
105

    
106
  @SuppressWarnings("unused")
107
  void debug(int depth)
108
    {
109
    String tmp="";
110
    int i;
111

    
112
    for(i=0; i<depth; i++) tmp +="   ";
113
    tmp += ("NodeID="+mData.ID+" nodes pointing: "+mData.numPointingNodes+" surfaceID="+
114
            mSurface.getID()+" FBO="+(mData.mFBO==null ? "null":mData.mFBO.getID()))+
115
            " parent sID="+(mParent==null ? "null": (mParent.mSurface.getID()));
116

    
117
    android.util.Log.e("NODE", tmp);
118

    
119
    for(i=0; i<mNumChildren[0]; i++)
120
      mChildren.get(i).debug(depth+1);
121
    }
122

    
123
///////////////////////////////////////////////////////////////////////////////////////////////////
124
// Debug - print contents of the HashMap
125

    
126
  @SuppressWarnings("unused")
127
  static void debugMap()
128
    {
129
    NodeData tmp;
130

    
131
    for(ArrayList<Long> key: mMapNodeID.keySet())
132
      {
133
      tmp = mMapNodeID.get(key);
134
      android.util.Log.e("NODE", "NodeID: "+tmp.ID+" <-- "+key);
135
      }
136
    }
137

    
138
///////////////////////////////////////////////////////////////////////////////////////////////////
139
// tree isomorphism algorithm
140

    
141
  private void adjustIsomorphism()
142
    {
143
    ArrayList<Long> newList = generateIDList();
144
    NodeData newData = mMapNodeID.get(newList);
145

    
146
    if( newData!=null )
147
      {
148
      newData.numPointingNodes++;
149
      }
150
    else
151
      {
152
      newData = new NodeData(++mNextNodeID,newList);
153
      mMapNodeID.put(newList,newData);
154
      }
155

    
156
    boolean deleteOldFBO = false;
157
    boolean createNewFBO = false;
158

    
159
    if( --mData.numPointingNodes==0 )
160
      {
161
      mMapNodeID.remove(mData.key);
162
      if( mData.mFBO!=null ) deleteOldFBO=true;
163
      }
164
    if( mNumChildren[0]>0 && newData.mFBO==null )
165
      {
166
      createNewFBO = true;
167
      }
168
    if( mNumChildren[0]==0 && newData.mFBO!=null )
169
      {
170
      newData.mFBO.markForDeletion();
171
      android.util.Log.d("NODE", "ERROR!! this NodeData cannot possibly contain a non-null FBO!! "+newData.mFBO.getID() );
172
      newData.mFBO = null;
173
      }
174

    
175
    if( deleteOldFBO && createNewFBO )
176
      {
177
      newData.mFBO = mData.mFBO;  // just copy over
178
      //android.util.Log.d("NODE", "copying over FBOs "+mData.mFBO.getID() );
179
      }
180
    else if( deleteOldFBO )
181
      {
182
      mData.mFBO.markForDeletion();
183
      //android.util.Log.d("NODE", "deleting old FBO "+mData.mFBO.getID() );
184
      mData.mFBO = null;
185
      }
186
    else if( createNewFBO )
187
      {
188
      newData.mFBO = new DistortedFramebuffer(true, DistortedSurface.TYPE_TREE, mSurface.getWidth(),mSurface.getHeight());
189
      //android.util.Log.d("NODE", "creating new FBO "+newData.mFBO.getID() );
190
      }
191

    
192
    mData = newData;
193

    
194
    if( mParent!=null ) mParent.adjustIsomorphism();
195
    }
196

    
197
///////////////////////////////////////////////////////////////////////////////////////////////////
198
// return the total number of render calls issued
199

    
200
  int draw(long currTime, DistortedOutputSurface surface)
201
    {
202
    DistortedInputSurface input = mNumChildren[0]==0 ? mSurface : mData.mFBO;
203

    
204
    if( input.setAsInput() )
205
      {
206
      mState.apply();
207
      mEffects.drawPriv(mSurface.getWidth()/2.0f, mSurface.getHeight()/2.0f, mMesh, surface, currTime);
208
      return 1;
209
      }
210

    
211
    return 0;
212
    }
213

    
214
///////////////////////////////////////////////////////////////////////////////////////////////////
215

    
216
  DistortedFramebuffer getPostprocessingBuffer()
217
    {
218
    return mEffects.getPostprocessingBuffer();
219
    }
220

    
221
///////////////////////////////////////////////////////////////////////////////////////////////////
222
// return the total number of render calls issued
223

    
224
  int renderRecursive(long currTime)
225
    {
226
    int numRenders = 0;
227

    
228
    if( mNumChildren[0]>0 && mData.currTime!=currTime )
229
      {
230
      mData.currTime = currTime;
231

    
232
      for (int i=0; i<mNumChildren[0]; i++)
233
        {
234
        numRenders += mChildren.get(i).renderRecursive(currTime);
235
        }
236

    
237
      mData.mFBO.setAsOutput();
238

    
239
      DistortedRenderState.colorDepthOn();
240

    
241
      GLES30.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
242
      GLES30.glClear( GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT);
243

    
244
      if( mSurface.setAsInput() )
245
        {
246
        numRenders++;
247
        DistortedEffects.blitPriv(mData.mFBO);
248
        }
249

    
250
      numRenders += mData.mFBO.renderChildren(currTime,mNumChildren[0],mChildren);
251
      }
252

    
253
    return numRenders;
254
    }
255

    
256
///////////////////////////////////////////////////////////////////////////////////////////////////
257
// PUBLIC API
258
///////////////////////////////////////////////////////////////////////////////////////////////////
259
/**
260
 * Constructs new Node.
261
 *     
262
 * @param surface InputSurface to put into the new Node.
263
 * @param effects DistortedEffects to put into the new Node.
264
 * @param mesh MeshObject to put into the new Node.
265
 */
266
  public DistortedNode(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
267
    {
268
    mSurface       = surface;
269
    mEffects       = effects;
270
    mMesh          = mesh;
271
    mState         = new DistortedRenderState();
272
    mChildren      = null;
273
    mNumChildren   = new int[1];
274
    mNumChildren[0]= 0;
275
    mParent        = null;
276

    
277
    ArrayList<Long> list = new ArrayList<>();
278
    list.add(mSurface.getID());
279
    list.add(-mEffects.getID());
280

    
281
    mData = mMapNodeID.get(list);
282
   
283
    if( mData!=null )
284
      {
285
      mData.numPointingNodes++;
286
      }
287
    else
288
      {
289
      mData = new NodeData(++mNextNodeID,list);
290
      mMapNodeID.put(list, mData);
291
      }
292
    }
293

    
294
///////////////////////////////////////////////////////////////////////////////////////////////////  
295
/**
296
 * Copy-constructs new Node from another Node.
297
 *     
298
 * @param node The DistortedNode to copy data from.
299
 * @param flags bit field composed of a subset of the following:
300
 *        {@link Distorted#CLONE_SURFACE},  {@link Distorted#CLONE_MATRIX}, {@link Distorted#CLONE_VERTEX},
301
 *        {@link Distorted#CLONE_FRAGMENT} and {@link Distorted#CLONE_CHILDREN}.
302
 *        For example flags = CLONE_SURFACE | CLONE_CHILDREN.
303
 */
304
  public DistortedNode(DistortedNode node, int flags)
305
    {
306
    mEffects= new DistortedEffects(node.mEffects,flags);
307
    mMesh   = node.mMesh;
308
    mState  = new DistortedRenderState();
309
    mParent = null;
310

    
311
    if( (flags & Distorted.CLONE_SURFACE) != 0 )
312
      {
313
      mSurface = node.mSurface;
314
      }
315
    else
316
      {
317
      int w = node.mSurface.getWidth();
318
      int h = node.mSurface.getHeight();
319

    
320
      if( node.mSurface instanceof DistortedTexture )
321
        {
322
        mSurface = new DistortedTexture(w,h, DistortedSurface.TYPE_TREE);
323
        }
324
      else if( node.mSurface instanceof DistortedFramebuffer )
325
        {
326
        boolean hasDepth = ((DistortedFramebuffer) node.mSurface).hasDepth();
327
        mSurface = new DistortedFramebuffer(hasDepth,DistortedSurface.TYPE_TREE,w,h);
328
        }
329
      }
330
    if( (flags & Distorted.CLONE_CHILDREN) != 0 )
331
      {
332
      if( node.mChildren==null )     // do NOT copy over the NULL!
333
        {
334
        node.mChildren = new ArrayList<>(2);
335
        }
336

    
337
      mChildren = node.mChildren;
338
      mNumChildren = node.mNumChildren;
339
      }
340
    else
341
      {
342
      mChildren = null;
343
      mNumChildren = new int[1];
344
      mNumChildren[0] = 0;
345
      }
346
   
347
    ArrayList<Long> list = generateIDList();
348
   
349
    mData = mMapNodeID.get(list);
350
   
351
    if( mData!=null )
352
      {
353
      mData.numPointingNodes++;
354
      }
355
    else
356
      {
357
      mData = new NodeData(++mNextNodeID,list);
358
      mMapNodeID.put(list, mData);
359
      }
360
    }
361

    
362
///////////////////////////////////////////////////////////////////////////////////////////////////
363
/**
364
 * Adds a new child to the last position in the list of our Node's children.
365
 * <p>
366
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
367
 * DistortedAttachDeamon (by calling attachNow())
368
 *
369
 * @param node The new Node to add.
370
 */
371
  public void attach(DistortedNode node)
372
    {
373
    DistortedAttachDaemon.attach(this,node);
374
    }
375

    
376
///////////////////////////////////////////////////////////////////////////////////////////////////
377
/**
378
 * Adds a new child to the last position in the list of our Node's children.
379
 * <p>
380
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
381
 * DistortedAttachDeamon (by calling attachNow())
382
 *
383
 * @param surface InputSurface to initialize our child Node with.
384
 * @param effects DistortedEffects to initialize our child Node with.
385
 * @param mesh MeshObject to initialize our child Node with.
386
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
387
 */
388
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
389
    {
390
    DistortedNode node = new DistortedNode(surface,effects,mesh);
391
    DistortedAttachDaemon.attach(this,node);
392
    return node;
393
    }
394

    
395
///////////////////////////////////////////////////////////////////////////////////////////////////
396
/**
397
 * This is not really part of the public API. Has to be public only because it is a part of the
398
 * DistortedAttacheable interface, which should really be a class that we extend here instead but
399
 * Java has no multiple inheritance.
400
 *
401
 * @y.exclude
402
 * @param node The new Node to add.
403
 */
404
  public void attachNow(DistortedNode node)
405
    {
406
    if( mChildren==null ) mChildren = new ArrayList<>(2);
407

    
408
    node.mParent = this;
409
    mChildren.add(node);
410
    mNumChildren[0]++;
411
    adjustIsomorphism();
412
    }
413

    
414
///////////////////////////////////////////////////////////////////////////////////////////////////
415
/**
416
 * Removes the first occurrence of a specified child from the list of children of our Node.
417
 * <p>
418
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
419
 * DistortedAttachDeamon (by calling detachNow())
420
 *
421
 * @param node The Node to remove.
422
 */
423
  public void detach(DistortedNode node)
424
    {
425
    DistortedAttachDaemon.detach(this,node);
426
    }
427

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

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

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

    
457
///////////////////////////////////////////////////////////////////////////////////////////////////
458
/**
459
 * This is not really part of the public API. Has to be public only because it is a part of the
460
 * DistortedAttacheable interface, which should really be a class that we extend here instead but
461
 * Java has no multiple inheritance.
462
 *
463
 * @y.exclude
464
 * @param node The Node to remove.
465
 */
466
  public void detachNow(DistortedNode node)
467
    {
468
    if( mNumChildren[0]>0 && mChildren.remove(node) )
469
      {
470
      node.mParent = null;
471
      mNumChildren[0]--;
472
      adjustIsomorphism();
473
      }
474
    }
475

    
476
///////////////////////////////////////////////////////////////////////////////////////////////////
477
/**
478
 * Removes all children Nodes.
479
 * <p>
480
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
481
 * DistortedAttachDeamon (by calling detachAllNow())
482
 */
483
  public void detachAll()
484
    {
485
    DistortedAttachDaemon.detachAll(this);
486
    }
487

    
488
///////////////////////////////////////////////////////////////////////////////////////////////////
489
/**
490
 * This is not really part of the public API. Has to be public only because it is a part of the
491
 * DistortedAttacheable interface, which should really be a class that we extend here instead but
492
 * Java has no multiple inheritance.
493
 *
494
 * @y.exclude
495
 */
496
  public void detachAllNow()
497
    {
498
    if( mNumChildren[0]>0 )
499
      {
500
      DistortedNode tmp;
501

    
502
      for(int i=mNumChildren[0]-1; i>=0; i--)
503
        {
504
        tmp = mChildren.remove(i);
505
        tmp.mParent = null;
506
        }
507

    
508
      mNumChildren[0] = 0;
509
      adjustIsomorphism();
510
      }
511
    }
512

    
513
///////////////////////////////////////////////////////////////////////////////////////////////////
514
/**
515
 * Returns the DistortedEffects object that's in the Node.
516
 * 
517
 * @return The DistortedEffects contained in the Node.
518
 */
519
  public DistortedEffects getEffects()
520
    {
521
    return mEffects;
522
    }
523

    
524
///////////////////////////////////////////////////////////////////////////////////////////////////
525
/**
526
 * Returns the DistortedInputSurface object that's in the Node.
527
 *
528
 * @return The DistortedInputSurface contained in the Node.
529
 */
530
  public DistortedInputSurface getSurface()
531
    {
532
    return mSurface;
533
    }
534

    
535
///////////////////////////////////////////////////////////////////////////////////////////////////
536
/**
537
 * Returns the DistortedFramebuffer object that's in the Node.
538
 *
539
 * @return The DistortedFramebuffer contained in the Node.
540
 */
541
  public DistortedFramebuffer getFramebuffer()
542
    {
543
    return mData.mFBO;
544
    }
545

    
546

    
547
///////////////////////////////////////////////////////////////////////////////////////////////////
548
/**
549
 * When rendering this Node, use ColorMask (r,g,b,a).
550
 *
551
 * @param r Write to the RED color channel when rendering this Node?
552
 * @param g Write to the GREEN color channel when rendering this Node?
553
 * @param b Write to the BLUE color channel when rendering this Node?
554
 * @param a Write to the ALPHA channel when rendering this Node?
555
 */
556
  public void glColorMask(boolean r, boolean g, boolean b, boolean a)
557
    {
558
    mState.glColorMask(r,g,b,a);
559
    }
560

    
561
///////////////////////////////////////////////////////////////////////////////////////////////////
562
/**
563
 * When rendering this Node, switch on writing to Depth buffer?
564
 *
565
 * @param mask Write to the Depth buffer when rendering this Node?
566
 */
567
  public void glDepthMask(boolean mask)
568
    {
569
    mState.glDepthMask(mask);
570
    }
571

    
572
///////////////////////////////////////////////////////////////////////////////////////////////////
573
/**
574
 * When rendering this Node, which bits of the Stencil buffer to write to?
575
 *
576
 * @param mask Marks the bits of the Stencil buffer we will write to when rendering this Node.
577
 */
578
  public void glStencilMask(int mask)
579
    {
580
    mState.glStencilMask(mask);
581
    }
582

    
583
///////////////////////////////////////////////////////////////////////////////////////////////////
584
/**
585
 * When rendering this Node, which Tests to enable?
586
 *
587
 * @param test Valid values: GL_DEPTH_TEST, GL_STENCIL_TEST, GL_BLEND
588
 */
589
  public void glEnable(int test)
590
    {
591
    mState.glEnable(test);
592
    }
593

    
594
///////////////////////////////////////////////////////////////////////////////////////////////////
595
/**
596
 * When rendering this Node, which Tests to enable?
597
 *
598
 * @param test Valid values: GL_DEPTH_TEST, GL_STENCIL_TEST, GL_BLEND
599
 */
600
  public void glDisable(int test)
601
    {
602
    mState.glDisable(test);
603
    }
604

    
605
///////////////////////////////////////////////////////////////////////////////////////////////////
606
/**
607
 * When rendering this Node, use the following StencilFunc.
608
 *
609
 * @param func Valid values: GL_NEVER, GL_ALWAYS, GL_LESS, GL_LEQUAL, GL_EQUAL, GL_GEQUAL, GL_GREATER, GL_NOTEQUAL
610
 * @param ref  Reference valut to compare our stencil with.
611
 * @param mask Mask used when comparing.
612
 */
613
  public void glStencilFunc(int func, int ref, int mask)
614
    {
615
    mState.glStencilFunc(func,ref,mask);
616
    }
617

    
618
///////////////////////////////////////////////////////////////////////////////////////////////////
619
/**
620
 * When rendering this Node, use the following StencilOp.
621
 * <p>
622
 * Valid values of all 3 parameters: GL_KEEP, GL_ZERO, GL_REPLACE, GL_INCR, GL_DECR, GL_INVERT, GL_INCR_WRAP, GL_DECR_WRAP
623
 *
624
 * @param sfail  What to do when Stencil Test fails.
625
 * @param dpfail What to do when Depth Test fails.
626
 * @param dppass What to do when Depth Test passes.
627
 */
628
  public void glStencilOp(int sfail, int dpfail, int dppass)
629
    {
630
    mState.glStencilOp(sfail,dpfail,dppass);
631
    }
632

    
633
///////////////////////////////////////////////////////////////////////////////////////////////////
634
/**
635
 * When rendering this Node, use the following DepthFunc.
636
 *
637
 * @param func Valid values: GL_NEVER, GL_ALWAYS, GL_LESS, GL_LEQUAL, GL_EQUAL, GL_GEQUAL, GL_GREATER, GL_NOTEQUAL
638
 */
639
  public void glDepthFunc(int func)
640
    {
641
    mState.glDepthFunc(func);
642
    }
643

    
644
///////////////////////////////////////////////////////////////////////////////////////////////////
645
/**
646
 * When rendering this Node, use the following Blending mode.
647
 * <p>
648
 * Valid values: GL_ZERO, GL_ONE, GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA,
649
 *               GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR,
650
 *               GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_SRC_ALPHA_SATURATE
651
 *
652
 * @param src Source Blend function
653
 * @param dst Destination Blend function
654
 */
655
  public void glBlendFunc(int src, int dst)
656
    {
657
    mState.glBlendFunc(src,dst);
658
    }
659
  }
(7-7/23)