Project

General

Profile

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

library / src / main / java / org / distorted / library / DistortedEffects.java @ 604b2899

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.content.res.Resources;
23
import android.opengl.GLES30;
24
import android.opengl.Matrix;
25

    
26
import org.distorted.library.message.EffectListener;
27
import org.distorted.library.program.DistortedProgram;
28
import org.distorted.library.program.FragmentCompilationException;
29
import org.distorted.library.program.FragmentUniformsException;
30
import org.distorted.library.program.LinkingException;
31
import org.distorted.library.program.VertexCompilationException;
32
import org.distorted.library.program.VertexUniformsException;
33
import org.distorted.library.type.Data1D;
34
import org.distorted.library.type.Data2D;
35
import org.distorted.library.type.Data3D;
36
import org.distorted.library.type.Data4D;
37
import org.distorted.library.type.Data5D;
38
import org.distorted.library.type.Static3D;
39

    
40
import java.io.InputStream;
41
import java.nio.Buffer;
42
import java.nio.ByteBuffer;
43
import java.nio.ByteOrder;
44
import java.nio.FloatBuffer;
45

    
46
///////////////////////////////////////////////////////////////////////////////////////////////////
47
/**
48
 * Class containing Matrix,Vertex and Fragment effect queues. Postprocessing queue is held in a separate
49
 * class.
50
 * <p>
51
 * The queues hold actual effects to be applied to a given (DistortedTexture,MeshObject) combo.
52
 */
53
public class DistortedEffects
54
  {
55
  /// MAIN PROGRAM ///
56
  private static DistortedProgram mMainProgram;
57
  private static int mMainTextureH;
58
  private static boolean[] mEffectEnabled = new boolean[EffectNames.size()];
59

    
60
  static
61
    {
62
    int len = EffectNames.size();
63

    
64
    for(int i=0; i<len; i++)
65
      {
66
      mEffectEnabled[i] = false;
67
      }
68
    }
69

    
70
  /// BLIT PROGRAM ///
71
  private static DistortedProgram mBlitProgram;
72
  private static int mBlitTextureH;
73
  private static int mBlitDepthH;
74
  private static final FloatBuffer mQuadPositions;
75

    
76
  static
77
    {
78
    float[] positionData= { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
79
    mQuadPositions = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()).asFloatBuffer();
80
    mQuadPositions.put(positionData).position(0);
81
    }
82

    
83
  /// DEBUG ONLY /////
84
  private static DistortedProgram mDebugProgram;
85

    
86
  private static int mDebugObjDH;
87
  private static int mDebugMVPMatrixH;
88
  /// END DEBUG //////
89

    
90
  private static float[] mMVPMatrix = new float[16];
91
  private static float[] mTmpMatrix = new float[16];
92

    
93
  private static long mNextID =0;
94
  private long mID;
95

    
96
  private EffectQueueMatrix      mM;
97
  private EffectQueueFragment    mF;
98
  private EffectQueueVertex      mV;
99

    
100
  private boolean matrixCloned, vertexCloned, fragmentCloned;
101

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

    
104
  static void createProgram(Resources resources)
105
  throws FragmentCompilationException,VertexCompilationException,VertexUniformsException,FragmentUniformsException,LinkingException
106
    {
107
    // MAIN PROGRAM ////////////////////////////////////
108
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
109
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
110

    
111
    String mainVertHeader= Distorted.GLSL_VERSION;
112
    String mainFragHeader= Distorted.GLSL_VERSION;
113

    
114
    EffectNames name;
115
    EffectTypes type;
116
    boolean foundF = false;
117
    boolean foundV = false;
118

    
119
    for(int i=0; i<mEffectEnabled.length; i++)
120
      {
121
      if( mEffectEnabled[i] )
122
        {
123
        name = EffectNames.getName(i);
124
        type = EffectNames.getType(i);
125

    
126
        if( type == EffectTypes.VERTEX )
127
          {
128
          mainVertHeader += ("#define "+name.name()+" "+name.ordinal()+"\n");
129
          foundV = true;
130
          }
131
        else if( type == EffectTypes.FRAGMENT )
132
          {
133
          mainFragHeader += ("#define "+name.name()+" "+name.ordinal()+"\n");
134
          foundF = true;
135
          }
136
        }
137
      }
138

    
139
    mainVertHeader += ("#define NUM_VERTEX "   + ( foundV ? getMaxVertex()   : 0 ) + "\n");
140
    mainFragHeader += ("#define NUM_FRAGMENT " + ( foundF ? getMaxFragment() : 0 ) + "\n");
141

    
142
    //android.util.Log.e("Effects", "vertHeader= "+mainVertHeader);
143
    //android.util.Log.e("Effects", "fragHeader= "+mainFragHeader);
144

    
145
    String[] feedback = { "v_Position", "v_Normal", "v_ndcPosition" };
146

    
147
    mMainProgram = new DistortedProgram(mainVertStream,mainFragStream, mainVertHeader, mainFragHeader, Distorted.GLSL, feedback);
148

    
149
    int mainProgramH = mMainProgram.getProgramHandle();
150
    EffectQueueFragment.getUniforms(mainProgramH);
151
    EffectQueueVertex.getUniforms(mainProgramH);
152
    EffectQueueMatrix.getUniforms(mainProgramH);
153
    mMainTextureH= GLES30.glGetUniformLocation( mainProgramH, "u_Texture");
154

    
155
    // BLIT PROGRAM ////////////////////////////////////
156
    final InputStream blitVertStream = resources.openRawResource(R.raw.blit_vertex_shader);
157
    final InputStream blitFragStream = resources.openRawResource(R.raw.blit_fragment_shader);
158

    
159
    String blitVertHeader= (Distorted.GLSL_VERSION + "#define NUM_VERTEX 0\n"  );
160
    String blitFragHeader= (Distorted.GLSL_VERSION + "#define NUM_FRAGMENT 0\n");
161

    
162
    try
163
      {
164
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream,blitVertHeader,blitFragHeader, Distorted.GLSL);
165
      }
166
    catch(Exception e)
167
      {
168
      android.util.Log.e("EFFECTS", "exception trying to compile BLIT program: "+e.getMessage());
169
      throw new RuntimeException(e.getMessage());
170
      }
171

    
172
    int blitProgramH = mBlitProgram.getProgramHandle();
173
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
174
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
175

    
176
    // DEBUG PROGRAM //////////////////////////////////////
177
    final InputStream debugVertexStream   = resources.openRawResource(R.raw.test_vertex_shader);
178
    final InputStream debugFragmentStream = resources.openRawResource(R.raw.test_fragment_shader);
179

    
180
    try
181
      {
182
      mDebugProgram = new DistortedProgram(debugVertexStream,debugFragmentStream, Distorted.GLSL_VERSION, Distorted.GLSL_VERSION, Distorted.GLSL);
183
      }
184
    catch(Exception e)
185
      {
186
      android.util.Log.e("EFFECTS", "exception trying to compile DEBUG program: "+e.getMessage());
187
      throw new RuntimeException(e.getMessage());
188
      }
189

    
190
    int debugProgramH = mDebugProgram.getProgramHandle();
191
    mDebugObjDH      = GLES30.glGetUniformLocation( debugProgramH, "u_objD");
192
    mDebugMVPMatrixH = GLES30.glGetUniformLocation( debugProgramH, "u_MVPMatrix");
193
    }
194

    
195
///////////////////////////////////////////////////////////////////////////////////////////////////
196

    
197
  private void initializeEffectLists(DistortedEffects d, int flags)
198
    {
199
    if( (flags & Distorted.CLONE_MATRIX) != 0 )
200
      {
201
      mM = d.mM;
202
      matrixCloned = true;
203
      }
204
    else
205
      {
206
      mM = new EffectQueueMatrix(mID);
207
      matrixCloned = false;
208
      }
209
    
210
    if( (flags & Distorted.CLONE_VERTEX) != 0 )
211
      {
212
      mV = d.mV;
213
      vertexCloned = true;
214
      }
215
    else
216
      {
217
      mV = new EffectQueueVertex(mID);
218
      vertexCloned = false;
219
      }
220
    
221
    if( (flags & Distorted.CLONE_FRAGMENT) != 0 )
222
      {
223
      mF = d.mF;
224
      fragmentCloned = true;
225
      }
226
    else
227
      {
228
      mF = new EffectQueueFragment(mID);
229
      fragmentCloned = false;
230
      }
231
    }
232

    
233
///////////////////////////////////////////////////////////////////////////////////////////////////
234

    
235
  @SuppressWarnings("unused")
236
  private void displayBoundingRect(float halfW, float halfH, DistortedOutputSurface surface, MeshObject mesh)
237
    {
238
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, mesh.mAttTFO[0]);
239
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
240

    
241
    DistortedRenderState.switchOffDrawing();
242
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, mesh.numVertices);
243
    DistortedRenderState.restoreDrawing();
244

    
245
    int error = GLES30.glGetError();
246

    
247
    if( error != GLES30.GL_NO_ERROR )
248
      {
249
      throw new RuntimeException("DrawArrays: glError 0x" + Integer.toHexString(error));
250
      }
251

    
252
    // mapping the buffer range slows down rendering /////////////////////////
253
    int size = (MeshObject.POS_DATA_SIZE+MeshObject.NOR_DATA_SIZE+MeshObject.NDC_DATA_SIZE)*mesh.numVertices;
254

    
255
    Buffer mappedBuffer =  GLES30.glMapBufferRange(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 4*size, GLES30.GL_MAP_READ_BIT);
256
    FloatBuffer fb = ((ByteBuffer) mappedBuffer).order(ByteOrder.nativeOrder()).asFloatBuffer();
257
    GLES30.glUnmapBuffer(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER);
258
    // end of slowdown //////////////////////////////////////////////////////
259

    
260
    GLES30.glEndTransformFeedback();
261
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
262
/*
263
    String msg = "";
264
    for(int i=0; i<size; i++) msg += (" "+fb.get(i));
265
    android.util.Log.d( "Feedback", msg);
266
*/
267
    float minx = Integer.MAX_VALUE;
268
    float maxx = Integer.MIN_VALUE;
269
    float miny = Integer.MAX_VALUE;
270
    float maxy = Integer.MIN_VALUE;
271
    float ndcX,ndcY;
272

    
273
    for(int i=0; i<mesh.numVertices; i++)
274
      {
275
      ndcX = fb.get(8*i+6);
276
      ndcY = fb.get(8*i+7);
277

    
278
      if( ndcX<minx ) minx = ndcX;
279
      if( ndcX>maxx ) maxx = ndcX;
280
      if( ndcY<miny ) miny = ndcY;
281
      if( ndcY>maxy ) maxy = ndcY;
282
      }
283

    
284
    minx = surface.mWidth *(minx+1)/2;   //
285
    miny = surface.mHeight*(miny+1)/2;   // transform from NDC to
286
    maxx = surface.mWidth *(maxx+1)/2;   // window coordinates
287
    maxy = surface.mHeight*(maxy+1)/2;   //
288

    
289
    mDebugProgram.useProgram();
290

    
291
    Matrix.setIdentityM( mTmpMatrix, 0);
292
    Matrix.translateM  ( mTmpMatrix, 0, minx-surface.mWidth/2, maxy-surface.mHeight/2, -surface.mDistance);
293
    Matrix.scaleM      ( mTmpMatrix, 0, (maxx-minx)/(2*halfW), (maxy-miny)/(2*halfH), 1.0f);
294
    Matrix.translateM  ( mTmpMatrix, 0, halfW,-halfH, 0);
295
    Matrix.multiplyMM  ( mMVPMatrix, 0, surface.mProjectionMatrix, 0, mTmpMatrix, 0);
296

    
297
    GLES30.glUniform2f(mDebugObjDH, 2*halfW, 2*halfH);
298
    GLES30.glUniformMatrix4fv(mDebugMVPMatrixH, 1, false, mMVPMatrix , 0);
299

    
300
    GLES30.glVertexAttribPointer(mDebugProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
301
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
302
    }
303

    
304
///////////////////////////////////////////////////////////////////////////////////////////////////
305

    
306
  void drawPriv(float halfW, float halfH, MeshObject mesh, DistortedOutputSurface surface, long currTime)
307
    {
308
    mM.compute(currTime);
309
    mV.compute(currTime);
310
    mF.compute(currTime);
311

    
312
    float halfZ = halfW*mesh.zFactor;
313

    
314
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
315

    
316
    mMainProgram.useProgram();
317
    surface.setAsOutput(currTime);
318
    GLES30.glUniform1i(mMainTextureH, 0);
319

    
320
    GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, mesh.mAttVBO[0]);
321
    GLES30.glVertexAttribPointer(mMainProgram.mAttribute[0], MeshObject.POS_DATA_SIZE, GLES30.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET0);
322
    GLES30.glVertexAttribPointer(mMainProgram.mAttribute[1], MeshObject.NOR_DATA_SIZE, GLES30.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET1);
323
    GLES30.glVertexAttribPointer(mMainProgram.mAttribute[2], MeshObject.TEX_DATA_SIZE, GLES30.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET2);
324
    GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0 );
325

    
326
    mM.send(surface,halfW,halfH,halfZ);
327
    mV.send(halfW,halfH,halfZ);
328
    mF.send(halfW,halfH);
329

    
330
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.numVertices);
331

    
332
    displayBoundingRect(halfW,halfH,surface,mesh);
333
    }
334

    
335
///////////////////////////////////////////////////////////////////////////////////////////////////
336
   
337
  static void blitPriv(DistortedOutputSurface surface)
338
    {
339
    mBlitProgram.useProgram();
340

    
341
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
342
    GLES30.glUniform1i(mBlitTextureH, 0);
343
    GLES30.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
344
    GLES30.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
345
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
346
    }
347
    
348
///////////////////////////////////////////////////////////////////////////////////////////////////
349
   
350
  private void releasePriv()
351
    {
352
    if( !matrixCloned     ) mM.abortAll(false);
353
    if( !vertexCloned     ) mV.abortAll(false);
354
    if( !fragmentCloned   ) mF.abortAll(false);
355

    
356
    mM = null;
357
    mV = null;
358
    mF = null;
359
    }
360

    
361
///////////////////////////////////////////////////////////////////////////////////////////////////
362

    
363
  static void onDestroy()
364
    {
365
    mNextID = 0;
366

    
367
    int len = EffectNames.size();
368

    
369
    for(int i=0; i<len; i++)
370
      {
371
      mEffectEnabled[i] = false;
372
      }
373
    }
374

    
375
///////////////////////////////////////////////////////////////////////////////////////////////////
376
// PUBLIC API
377
///////////////////////////////////////////////////////////////////////////////////////////////////
378
/**
379
 * Create empty effect queue.
380
 */
381
  public DistortedEffects()
382
    {
383
    mID = ++mNextID;
384
    initializeEffectLists(this,0);
385
    }
386

    
387
///////////////////////////////////////////////////////////////////////////////////////////////////
388
/**
389
 * Copy constructor.
390
 * <p>
391
 * Whatever we do not clone gets created just like in the default constructor.
392
 *
393
 * @param dc    Source object to create our object from
394
 * @param flags A bitmask of values specifying what to copy.
395
 *              For example, CLONE_VERTEX | CLONE_MATRIX.
396
 */
397
  public DistortedEffects(DistortedEffects dc, int flags)
398
    {
399
    mID = ++mNextID;
400
    initializeEffectLists(dc,flags);
401
    }
402

    
403
///////////////////////////////////////////////////////////////////////////////////////////////////
404
/**
405
 * Releases all resources. After this call, the queue should not be used anymore.
406
 */
407
  @SuppressWarnings("unused")
408
  public synchronized void delete()
409
    {
410
    releasePriv();
411
    }
412

    
413
///////////////////////////////////////////////////////////////////////////////////////////////////
414
/**
415
 * Returns unique ID of this instance.
416
 *
417
 * @return ID of the object.
418
 */
419
  public long getID()
420
      {
421
      return mID;
422
      }
423

    
424
///////////////////////////////////////////////////////////////////////////////////////////////////
425
/**
426
 * Adds the calling class to the list of Listeners that get notified each time some event happens 
427
 * to one of the Effects in those queues. Nothing will happen if 'el' is already in the list.
428
 * 
429
 * @param el A class implementing the EffectListener interface that wants to get notifications.
430
 */
431
  @SuppressWarnings("unused")
432
  public void registerForMessages(EffectListener el)
433
    {
434
    mV.registerForMessages(el);
435
    mF.registerForMessages(el);
436
    mM.registerForMessages(el);
437
    }
438

    
439
///////////////////////////////////////////////////////////////////////////////////////////////////
440
/**
441
 * Removes the calling class from the list of Listeners.
442
 * 
443
 * @param el A class implementing the EffectListener interface that no longer wants to get notifications.
444
 */
445
  @SuppressWarnings("unused")
446
  public void deregisterForMessages(EffectListener el)
447
    {
448
    mV.deregisterForMessages(el);
449
    mF.deregisterForMessages(el);
450
    mM.deregisterForMessages(el);
451
    }
452

    
453
///////////////////////////////////////////////////////////////////////////////////////////////////
454
/**
455
 * Aborts all Effects.
456
 * @return Number of effects aborted.
457
 */
458
  public int abortAllEffects()
459
    {
460
    return mM.abortAll(true) + mV.abortAll(true) + mF.abortAll(true);
461
    }
462

    
463
///////////////////////////////////////////////////////////////////////////////////////////////////
464
/**
465
 * Aborts all Effects of a given type, for example all MATRIX Effects.
466
 * 
467
 * @param type one of the constants defined in {@link EffectTypes}
468
 * @return Number of effects aborted.
469
 */
470
  public int abortEffects(EffectTypes type)
471
    {
472
    switch(type)
473
      {
474
      case MATRIX     : return mM.abortAll(true);
475
      case VERTEX     : return mV.abortAll(true);
476
      case FRAGMENT   : return mF.abortAll(true);
477
      default         : return 0;
478
      }
479
    }
480
    
481
///////////////////////////////////////////////////////////////////////////////////////////////////
482
/**
483
 * Aborts a single Effect.
484
 * 
485
 * @param id ID of the Effect we want to abort.
486
 * @return number of Effects aborted. Always either 0 or 1.
487
 */
488
  public int abortEffect(long id)
489
    {
490
    int type = (int)(id&EffectTypes.MASK);
491

    
492
    if( type==EffectTypes.MATRIX.type      ) return mM.removeByID(id>>EffectTypes.LENGTH);
493
    if( type==EffectTypes.VERTEX.type      ) return mV.removeByID(id>>EffectTypes.LENGTH);
494
    if( type==EffectTypes.FRAGMENT.type    ) return mF.removeByID(id>>EffectTypes.LENGTH);
495

    
496
    return 0;
497
    }
498

    
499
///////////////////////////////////////////////////////////////////////////////////////////////////
500
/**
501
 * Abort all Effects of a given name, for example all rotations.
502
 * 
503
 * @param name one of the constants defined in {@link EffectNames}
504
 * @return number of Effects aborted.
505
 */
506
  public int abortEffects(EffectNames name)
507
    {
508
    switch(name.getType())
509
      {
510
      case MATRIX     : return mM.removeByType(name);
511
      case VERTEX     : return mV.removeByType(name);
512
      case FRAGMENT   : return mF.removeByType(name);
513
      default         : return 0;
514
      }
515
    }
516
    
517
///////////////////////////////////////////////////////////////////////////////////////////////////
518
/**
519
 * Print some info about a given Effect to Android's standard out. Used for debugging only.
520
 * 
521
 * @param id Effect ID we want to print info about
522
 * @return <code>true</code> if a single Effect of type effectType has been found.
523
 */
524
  @SuppressWarnings("unused")
525
  public boolean printEffect(long id)
526
    {
527
    int type = (int)(id&EffectTypes.MASK);
528

    
529
    if( type==EffectTypes.MATRIX.type  )  return mM.printByID(id>>EffectTypes.LENGTH);
530
    if( type==EffectTypes.VERTEX.type  )  return mV.printByID(id>>EffectTypes.LENGTH);
531
    if( type==EffectTypes.FRAGMENT.type)  return mF.printByID(id>>EffectTypes.LENGTH);
532

    
533
    return false;
534
    }
535

    
536
///////////////////////////////////////////////////////////////////////////////////////////////////
537
/**
538
 * Enables a given Effect.
539
 * <p>
540
 * By default, all effects are disabled. One has to explicitly enable each effect one intends to use.
541
 * This needs to be called BEFORE shaders get compiled, i.e. before the call to Distorted.onCreate().
542
 * The point: by enabling only the effects we need, we can optimize the shaders.
543
 *
544
 * @param name Name of the Effect to enable.
545
 */
546
  public static void enableEffect(EffectNames name)
547
    {
548
    mEffectEnabled[name.ordinal()] = true;
549
    }
550

    
551
///////////////////////////////////////////////////////////////////////////////////////////////////
552
/**
553
 * Returns the maximum number of Matrix effects.
554
 *
555
 * @return The maximum number of Matrix effects
556
 */
557
  @SuppressWarnings("unused")
558
  public static int getMaxMatrix()
559
    {
560
    return EffectQueue.getMax(EffectTypes.MATRIX.ordinal());
561
    }
562

    
563
///////////////////////////////////////////////////////////////////////////////////////////////////
564
/**
565
 * Returns the maximum number of Vertex effects.
566
 *
567
 * @return The maximum number of Vertex effects
568
 */
569
  @SuppressWarnings("unused")
570
  public static int getMaxVertex()
571
    {
572
    return EffectQueue.getMax(EffectTypes.VERTEX.ordinal());
573
    }
574

    
575
///////////////////////////////////////////////////////////////////////////////////////////////////
576
/**
577
 * Returns the maximum number of Fragment effects.
578
 *
579
 * @return The maximum number of Fragment effects
580
 */
581
  @SuppressWarnings("unused")
582
  public static int getMaxFragment()
583
    {
584
    return EffectQueue.getMax(EffectTypes.FRAGMENT.ordinal());
585
    }
586

    
587
///////////////////////////////////////////////////////////////////////////////////////////////////
588
/**
589
 * Sets the maximum number of Matrix effects that can be stored in a single EffectQueue at one time.
590
 * This can fail if:
591
 * <ul>
592
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
593
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
594
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link Distorted#onCreate}. After this
595
 *     time only decreasing the value of 'max' is permitted.
596
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
597
 * </ul>
598
 *
599
 * @param max new maximum number of simultaneous Matrix Effects. Has to be a non-negative number not greater
600
 *            than Byte.MAX_VALUE
601
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
602
 */
603
  @SuppressWarnings("unused")
604
  public static boolean setMaxMatrix(int max)
605
    {
606
    return EffectQueue.setMax(EffectTypes.MATRIX.ordinal(),max);
607
    }
608

    
609
///////////////////////////////////////////////////////////////////////////////////////////////////
610
/**
611
 * Sets the maximum number of Vertex effects that can be stored in a single EffectQueue at one time.
612
 * This can fail if:
613
 * <ul>
614
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
615
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
616
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link Distorted#onCreate}. After this
617
 *     time only decreasing the value of 'max' is permitted.
618
* <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
619
 * </ul>
620
 *
621
 * @param max new maximum number of simultaneous Vertex Effects. Has to be a non-negative number not greater
622
 *            than Byte.MAX_VALUE
623
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
624
 */
625
  @SuppressWarnings("unused")
626
  public static boolean setMaxVertex(int max)
627
    {
628
    return EffectQueue.setMax(EffectTypes.VERTEX.ordinal(),max);
629
    }
630

    
631
///////////////////////////////////////////////////////////////////////////////////////////////////
632
/**
633
 * Sets the maximum number of Fragment effects that can be stored in a single EffectQueue at one time.
634
 * This can fail if:
635
 * <ul>
636
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
637
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
638
 *     before the Fragment Shader gets compiled, i.e. before the call to {@link Distorted#onCreate}. After this
639
 *     time only decreasing the value of 'max' is permitted.
640
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
641
 * </ul>
642
 *
643
 * @param max new maximum number of simultaneous Fragment Effects. Has to be a non-negative number not greater
644
 *            than Byte.MAX_VALUE
645
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
646
 */
647
  @SuppressWarnings("unused")
648
  public static boolean setMaxFragment(int max)
649
    {
650
    return EffectQueue.setMax(EffectTypes.FRAGMENT.ordinal(),max);
651
    }
652

    
653
///////////////////////////////////////////////////////////////////////////////////////////////////   
654
///////////////////////////////////////////////////////////////////////////////////////////////////
655
// Individual effect functions.
656
///////////////////////////////////////////////////////////////////////////////////////////////////
657
// Matrix-based effects
658
///////////////////////////////////////////////////////////////////////////////////////////////////
659
/**
660
 * Moves the Object by a (possibly changing in time) vector.
661
 * 
662
 * @param vector 3-dimensional Data which at any given time will return a Static3D
663
 *               representing the current coordinates of the vector we want to move the Object with.
664
 * @return       ID of the effect added, or -1 if we failed to add one.
665
 */
666
  public long move(Data3D vector)
667
    {   
668
    return mM.add(EffectNames.MOVE,vector);
669
    }
670

    
671
///////////////////////////////////////////////////////////////////////////////////////////////////
672
/**
673
 * Scales the Object by (possibly changing in time) 3D scale factors.
674
 * 
675
 * @param scale 3-dimensional Data which at any given time returns a Static3D
676
 *              representing the current x- , y- and z- scale factors.
677
 * @return      ID of the effect added, or -1 if we failed to add one.
678
 */
679
  public long scale(Data3D scale)
680
    {   
681
    return mM.add(EffectNames.SCALE,scale);
682
    }
683

    
684
///////////////////////////////////////////////////////////////////////////////////////////////////
685
/**
686
 * Scales the Object by one uniform, constant factor in all 3 dimensions. Convenience function.
687
 *
688
 * @param scale The factor to scale all 3 dimensions with.
689
 * @return      ID of the effect added, or -1 if we failed to add one.
690
 */
691
  public long scale(float scale)
692
    {
693
    return mM.add(EffectNames.SCALE, new Static3D(scale,scale,scale));
694
    }
695

    
696
///////////////////////////////////////////////////////////////////////////////////////////////////
697
/**
698
 * Rotates the Object by 'angle' degrees around the center.
699
 * Static axis of rotation is given by the last parameter.
700
 *
701
 * @param angle  Angle that we want to rotate the Object to. Unit: degrees
702
 * @param axis   Axis of rotation
703
 * @param center Coordinates of the Point we are rotating around.
704
 * @return       ID of the effect added, or -1 if we failed to add one.
705
 */
706
  public long rotate(Data1D angle, Static3D axis, Data3D center )
707
    {   
708
    return mM.add(EffectNames.ROTATE, angle, axis, center);
709
    }
710

    
711
///////////////////////////////////////////////////////////////////////////////////////////////////
712
/**
713
 * Rotates the Object by 'angle' degrees around the center.
714
 * Here both angle and axis can dynamically change.
715
 *
716
 * @param angleaxis Combined 4-tuple representing the (angle,axisX,axisY,axisZ).
717
 * @param center    Coordinates of the Point we are rotating around.
718
 * @return          ID of the effect added, or -1 if we failed to add one.
719
 */
720
  public long rotate(Data4D angleaxis, Data3D center)
721
    {
722
    return mM.add(EffectNames.ROTATE, angleaxis, center);
723
    }
724

    
725
///////////////////////////////////////////////////////////////////////////////////////////////////
726
/**
727
 * Rotates the Object by quaternion.
728
 *
729
 * @param quaternion The quaternion describing the rotation.
730
 * @param center     Coordinates of the Point we are rotating around.
731
 * @return           ID of the effect added, or -1 if we failed to add one.
732
 */
733
  public long quaternion(Data4D quaternion, Data3D center )
734
    {
735
    return mM.add(EffectNames.QUATERNION,quaternion,center);
736
    }
737

    
738
///////////////////////////////////////////////////////////////////////////////////////////////////
739
/**
740
 * Shears the Object.
741
 *
742
 * @param shear   The 3-tuple of shear factors. The first controls level
743
 *                of shearing in the X-axis, second - Y-axis and the third -
744
 *                Z-axis. Each is the tangens of the shear angle, i.e 0 -
745
 *                no shear, 1 - shear by 45 degrees (tan(45deg)=1) etc.
746
 * @param center  Center of shearing, i.e. the point which stays unmoved.
747
 * @return        ID of the effect added, or -1 if we failed to add one.
748
 */
749
  public long shear(Data3D shear, Data3D center)
750
    {
751
    return mM.add(EffectNames.SHEAR, shear, center);
752
    }
753

    
754
///////////////////////////////////////////////////////////////////////////////////////////////////
755
// Fragment-based effects  
756
///////////////////////////////////////////////////////////////////////////////////////////////////
757
/**
758
 * Makes a certain sub-region of the Object smoothly change all three of its RGB components.
759
 *        
760
 * @param blend  1-dimensional Data that returns the level of blend a given pixel will be
761
 *               mixed with the next parameter 'color': pixel = (1-level)*pixel + level*color.
762
 *               Valid range: <0,1>
763
 * @param color  Color to mix. (1,0,0) is RED.
764
 * @param region Region this Effect is limited to.
765
 * @param smooth If true, the level of 'blend' will smoothly fade out towards the edges of the region.
766
 * @return       ID of the effect added, or -1 if we failed to add one.
767
 */
768
  public long chroma(Data1D blend, Data3D color, Data4D region, boolean smooth)
769
    {
770
    return mF.add( smooth? EffectNames.SMOOTH_CHROMA:EffectNames.CHROMA, blend, color, region);
771
    }
772

    
773
///////////////////////////////////////////////////////////////////////////////////////////////////
774
/**
775
 * Makes the whole Object smoothly change all three of its RGB components.
776
 *
777
 * @param blend  1-dimensional Data that returns the level of blend a given pixel will be
778
 *               mixed with the next parameter 'color': pixel = (1-level)*pixel + level*color.
779
 *               Valid range: <0,1>
780
 * @param color  Color to mix. (1,0,0) is RED.
781
 * @return       ID of the effect added, or -1 if we failed to add one.
782
 */
783
  public long chroma(Data1D blend, Data3D color)
784
    {
785
    return mF.add(EffectNames.CHROMA, blend, color);
786
    }
787

    
788
///////////////////////////////////////////////////////////////////////////////////////////////////
789
/**
790
 * Makes a certain sub-region of the Object smoothly change its transparency level.
791
 *        
792
 * @param alpha  1-dimensional Data that returns the level of transparency we want to have at any given
793
 *               moment: pixel.a *= alpha.
794
 *               Valid range: <0,1>
795
 * @param region Region this Effect is limited to. 
796
 * @param smooth If true, the level of 'alpha' will smoothly fade out towards the edges of the region.
797
 * @return       ID of the effect added, or -1 if we failed to add one. 
798
 */
799
  public long alpha(Data1D alpha, Data4D region, boolean smooth)
800
    {
801
    return mF.add( smooth? EffectNames.SMOOTH_ALPHA:EffectNames.ALPHA, alpha, region);
802
    }
803

    
804
///////////////////////////////////////////////////////////////////////////////////////////////////
805
/**
806
 * Makes the whole Object smoothly change its transparency level.
807
 *
808
 * @param alpha  1-dimensional Data that returns the level of transparency we want to have at any
809
 *               given moment: pixel.a *= alpha.
810
 *               Valid range: <0,1>
811
 * @return       ID of the effect added, or -1 if we failed to add one.
812
 */
813
  public long alpha(Data1D alpha)
814
    {
815
    return mF.add(EffectNames.ALPHA, alpha);
816
    }
817

    
818
///////////////////////////////////////////////////////////////////////////////////////////////////
819
/**
820
 * Makes a certain sub-region of the Object smoothly change its brightness level.
821
 *        
822
 * @param brightness 1-dimensional Data that returns the level of brightness we want to have
823
 *                   at any given moment. Valid range: <0,infinity)
824
 * @param region     Region this Effect is limited to.
825
 * @param smooth     If true, the level of 'brightness' will smoothly fade out towards the edges of the region.
826
 * @return           ID of the effect added, or -1 if we failed to add one.
827
 */
828
  public long brightness(Data1D brightness, Data4D region, boolean smooth)
829
    {
830
    return mF.add( smooth ? EffectNames.SMOOTH_BRIGHTNESS: EffectNames.BRIGHTNESS, brightness, region);
831
    }
832

    
833
///////////////////////////////////////////////////////////////////////////////////////////////////
834
/**
835
 * Makes the whole Object smoothly change its brightness level.
836
 *
837
 * @param brightness 1-dimensional Data that returns the level of brightness we want to have
838
 *                   at any given moment. Valid range: <0,infinity)
839
 * @return           ID of the effect added, or -1 if we failed to add one.
840
 */
841
  public long brightness(Data1D brightness)
842
    {
843
    return mF.add(EffectNames.BRIGHTNESS, brightness);
844
    }
845

    
846
///////////////////////////////////////////////////////////////////////////////////////////////////
847
/**
848
 * Makes a certain sub-region of the Object smoothly change its contrast level.
849
 *        
850
 * @param contrast 1-dimensional Data that returns the level of contrast we want to have
851
 *                 at any given moment. Valid range: <0,infinity)
852
 * @param region   Region this Effect is limited to.
853
 * @param smooth   If true, the level of 'contrast' will smoothly fade out towards the edges of the region.
854
 * @return         ID of the effect added, or -1 if we failed to add one.
855
 */
856
  public long contrast(Data1D contrast, Data4D region, boolean smooth)
857
    {
858
    return mF.add( smooth ? EffectNames.SMOOTH_CONTRAST:EffectNames.CONTRAST, contrast, region);
859
    }
860

    
861
///////////////////////////////////////////////////////////////////////////////////////////////////
862
/**
863
 * Makes the whole Object smoothly change its contrast level.
864
 *
865
 * @param contrast 1-dimensional Data that returns the level of contrast we want to have
866
 *                 at any given moment. Valid range: <0,infinity)
867
 * @return         ID of the effect added, or -1 if we failed to add one.
868
 */
869
  public long contrast(Data1D contrast)
870
    {
871
    return mF.add(EffectNames.CONTRAST, contrast);
872
    }
873

    
874
///////////////////////////////////////////////////////////////////////////////////////////////////
875
/**
876
 * Makes a certain sub-region of the Object smoothly change its saturation level.
877
 *        
878
 * @param saturation 1-dimensional Data that returns the level of saturation we want to have
879
 *                   at any given moment. Valid range: <0,infinity)
880
 * @param region     Region this Effect is limited to.
881
 * @param smooth     If true, the level of 'saturation' will smoothly fade out towards the edges of the region.
882
 * @return           ID of the effect added, or -1 if we failed to add one.
883
 */
884
  public long saturation(Data1D saturation, Data4D region, boolean smooth)
885
    {
886
    return mF.add( smooth ? EffectNames.SMOOTH_SATURATION:EffectNames.SATURATION, saturation, region);
887
    }
888

    
889
///////////////////////////////////////////////////////////////////////////////////////////////////
890
/**
891
 * Makes the whole Object smoothly change its saturation level.
892
 *
893
 * @param saturation 1-dimensional Data that returns the level of saturation we want to have
894
 *                   at any given moment. Valid range: <0,infinity)
895
 * @return           ID of the effect added, or -1 if we failed to add one.
896
 */
897
  public long saturation(Data1D saturation)
898
    {
899
    return mF.add(EffectNames.SATURATION, saturation);
900
    }
901

    
902
///////////////////////////////////////////////////////////////////////////////////////////////////
903
// Vertex-based effects  
904
///////////////////////////////////////////////////////////////////////////////////////////////////
905
/**
906
 * Distort a (possibly changing in time) part of the Object by a (possibly changing in time) vector of force.
907
 *
908
 * @param vector 3-dimensional Vector which represents the force the Center of the Effect is
909
 *               currently being dragged with.
910
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
911
 * @param region Region that masks the Effect.
912
 * @return       ID of the effect added, or -1 if we failed to add one.
913
 */
914
  public long distort(Data3D vector, Data3D center, Data4D region)
915
    {  
916
    return mV.add(EffectNames.DISTORT, vector, center, region);
917
    }
918

    
919
///////////////////////////////////////////////////////////////////////////////////////////////////
920
/**
921
 * Distort the whole Object by a (possibly changing in time) vector of force.
922
 *
923
 * @param vector 3-dimensional Vector which represents the force the Center of the Effect is
924
 *               currently being dragged with.
925
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
926
 * @return       ID of the effect added, or -1 if we failed to add one.
927
 */
928
  public long distort(Data3D vector, Data3D center)
929
    {
930
    return mV.add(EffectNames.DISTORT, vector, center, null);
931
    }
932

    
933
///////////////////////////////////////////////////////////////////////////////////////////////////
934
/**
935
 * Deform the shape of the whole Object with a (possibly changing in time) vector of force applied to
936
 * a (possibly changing in time) point on the Object.
937
 *
938
 * @param vector Vector of force that deforms the shape of the whole Object.
939
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
940
 * @param region Region that masks the Effect.
941
 * @return       ID of the effect added, or -1 if we failed to add one.
942
 */
943
  public long deform(Data3D vector, Data3D center, Data4D region)
944
    {
945
    return mV.add(EffectNames.DEFORM, vector, center, region);
946
    }
947

    
948
///////////////////////////////////////////////////////////////////////////////////////////////////
949
/**
950
 * Deform the shape of the whole Object with a (possibly changing in time) vector of force applied to
951
 * a (possibly changing in time) point on the Object.
952
 *     
953
 * @param vector Vector of force that deforms the shape of the whole Object.
954
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
955
 * @return       ID of the effect added, or -1 if we failed to add one.
956
 */
957
  public long deform(Data3D vector, Data3D center)
958
    {  
959
    return mV.add(EffectNames.DEFORM, vector, center, null);
960
    }
961

    
962
///////////////////////////////////////////////////////////////////////////////////////////////////  
963
/**
964
 * Pull all points around the center of the Effect towards the center (if degree>=1) or push them
965
 * away from the center (degree<=1)
966
 *
967
 * @param sink   The current degree of the Effect.
968
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
969
 * @param region Region that masks the Effect.
970
 * @return       ID of the effect added, or -1 if we failed to add one.
971
 */
972
  public long sink(Data1D sink, Data3D center, Data4D region)
973
    {
974
    return mV.add(EffectNames.SINK, sink, center, region);
975
    }
976

    
977
///////////////////////////////////////////////////////////////////////////////////////////////////
978
/**
979
 * Pull all points around the center of the Effect towards the center (if degree>=1) or push them
980
 * away from the center (degree<=1)
981
 *
982
 * @param sink   The current degree of the Effect.
983
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
984
 * @return       ID of the effect added, or -1 if we failed to add one.
985
 */
986
  public long sink(Data1D sink, Data3D center)
987
    {
988
    return mV.add(EffectNames.SINK, sink, center);
989
    }
990

    
991
///////////////////////////////////////////////////////////////////////////////////////////////////
992
/**
993
 * Pull all points around the center of the Effect towards a line passing through the center
994
 * (that's if degree>=1) or push them away from the line (degree<=1)
995
 *
996
 * @param pinch  The current degree of the Effect + angle the line forms with X-axis
997
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
998
 * @param region Region that masks the Effect.
999
 * @return       ID of the effect added, or -1 if we failed to add one.
1000
 */
1001
  public long pinch(Data2D pinch, Data3D center, Data4D region)
1002
    {
1003
    return mV.add(EffectNames.PINCH, pinch, center, region);
1004
    }
1005

    
1006
///////////////////////////////////////////////////////////////////////////////////////////////////
1007
/**
1008
 * Pull all points around the center of the Effect towards a line passing through the center
1009
 * (that's if degree>=1) or push them away from the line (degree<=1)
1010
 *
1011
 * @param pinch  The current degree of the Effect + angle the line forms with X-axis
1012
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
1013
 * @return       ID of the effect added, or -1 if we failed to add one.
1014
 */
1015
  public long pinch(Data2D pinch, Data3D center)
1016
    {
1017
    return mV.add(EffectNames.PINCH, pinch, center);
1018
    }
1019

    
1020
///////////////////////////////////////////////////////////////////////////////////////////////////  
1021
/**
1022
 * Rotate part of the Object around the Center of the Effect by a certain angle.
1023
 *
1024
 * @param swirl  The angle of Swirl (in degrees). Positive values swirl clockwise.
1025
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
1026
 * @param region Region that masks the Effect.
1027
 * @return       ID of the effect added, or -1 if we failed to add one.
1028
 */
1029
  public long swirl(Data1D swirl, Data3D center, Data4D region)
1030
    {    
1031
    return mV.add(EffectNames.SWIRL, swirl, center, region);
1032
    }
1033

    
1034
///////////////////////////////////////////////////////////////////////////////////////////////////
1035
/**
1036
 * Rotate the whole Object around the Center of the Effect by a certain angle.
1037
 *
1038
 * @param swirl  The angle of Swirl (in degrees). Positive values swirl clockwise.
1039
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
1040
 * @return       ID of the effect added, or -1 if we failed to add one.
1041
 */
1042
  public long swirl(Data1D swirl, Data3D center)
1043
    {
1044
    return mV.add(EffectNames.SWIRL, swirl, center);
1045
    }
1046

    
1047
///////////////////////////////////////////////////////////////////////////////////////////////////
1048
/**
1049
 * Directional, sinusoidal wave effect.
1050
 *
1051
 * @param wave   A 5-dimensional data structure describing the wave: first member is the amplitude,
1052
 *               second is the wave length, third is the phase (i.e. when phase = PI/2, the sine
1053
 *               wave at the center does not start from sin(0), but from sin(PI/2) ) and the next two
1054
 *               describe the 'direction' of the wave.
1055
 *               <p>
1056
 *               Wave direction is defined to be a 3D vector of length 1. To define such vectors, we
1057
 *               need 2 floats: thus the third member is the angle Alpha (in degrees) which the vector
1058
 *               forms with the XY-plane, and the fourth is the angle Beta (again in degrees) which
1059
 *               the projection of the vector to the XY-plane forms with the Y-axis (counterclockwise).
1060
 *               <p>
1061
 *               <p>
1062
 *               Example1: if Alpha = 90, Beta = 90, (then V=(0,0,1) ) and the wave acts 'vertically'
1063
 *               in the X-direction, i.e. cross-sections of the resulting surface with the XZ-plane
1064
 *               will be sine shapes.
1065
 *               <p>
1066
 *               Example2: if Alpha = 90, Beta = 0, the again V=(0,0,1) and the wave is 'vertical',
1067
 *               but this time it waves in the Y-direction, i.e. cross sections of the surface and the
1068
 *               YZ-plane with be sine shapes.
1069
 *               <p>
1070
 *               Example3: if Alpha = 0 and Beta = 45, then V=(sqrt(2)/2, -sqrt(2)/2, 0) and the wave
1071
 *               is entirely 'horizontal' and moves point (x,y,0) in direction V by whatever is the
1072
 *               value if sin at this point.
1073
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
1074
 * @return       ID of the effect added, or -1 if we failed to add one.
1075
 */
1076
  public long wave(Data5D wave, Data3D center)
1077
    {
1078
    return mV.add(EffectNames.WAVE, wave, center, null);
1079
    }
1080

    
1081
///////////////////////////////////////////////////////////////////////////////////////////////////
1082
/**
1083
 * Directional, sinusoidal wave effect.
1084
 *
1085
 * @param wave   see {@link DistortedEffects#wave(Data5D,Data3D)}
1086
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
1087
 * @param region Region that masks the Effect.
1088
 * @return       ID of the effect added, or -1 if we failed to add one.
1089
 */
1090
  public long wave(Data5D wave, Data3D center, Data4D region)
1091
    {
1092
    return mV.add(EffectNames.WAVE, wave, center, region);
1093
    }
1094
  }
(2-2/26)