Project

General

Profile

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

library / src / main / java / org / distorted / library / DistortedEffects.java @ 226144d0

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.ByteBuffer;
42
import java.nio.ByteOrder;
43
import java.nio.FloatBuffer;
44

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

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

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

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

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

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

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

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

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

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

    
99
  private boolean matrixCloned, vertexCloned, fragmentCloned;
100

    
101
///////////////////////////////////////////////////////////////////////////////////////////////////
102

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

    
109
    String mainVertHeader= Distorted.GLSL_VERSION;
110
    String mainFragHeader= Distorted.GLSL_VERSION;
111

    
112
    EffectNames name;
113
    EffectTypes type;
114
    boolean foundF = false;
115
    boolean foundV = false;
116

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

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

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

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

    
143
    mMainProgram = new DistortedProgram(mainVertStream,mainFragStream, mainVertHeader, mainFragHeader, Distorted.GLSL);
144

    
145
    int mainProgramH = mMainProgram.getProgramHandle();
146
    EffectQueueFragment.getUniforms(mainProgramH);
147
    EffectQueueVertex.getUniforms(mainProgramH);
148
    EffectQueueMatrix.getUniforms(mainProgramH);
149
    mMainTextureH= GLES30.glGetUniformLocation( mainProgramH, "u_Texture");
150

    
151
    // BLIT PROGRAM ////////////////////////////////////
152
    final InputStream blitVertStream = resources.openRawResource(R.raw.blit_vertex_shader);
153
    final InputStream blitFragStream = resources.openRawResource(R.raw.blit_fragment_shader);
154

    
155
    String blitVertHeader= (Distorted.GLSL_VERSION + "#define NUM_VERTEX 0\n"  );
156
    String blitFragHeader= (Distorted.GLSL_VERSION + "#define NUM_FRAGMENT 0\n");
157

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

    
168
    int blitProgramH = mBlitProgram.getProgramHandle();
169
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
170
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
171

    
172
    // DEBUG ONLY //////////////////////////////////////
173
    final InputStream debugVertexStream   = resources.openRawResource(R.raw.test_vertex_shader);
174
    final InputStream debugFragmentStream = resources.openRawResource(R.raw.test_fragment_shader);
175

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

    
186
    int debugProgramH = mDebugProgram.getProgramHandle();
187
    mDebugObjDH = GLES30.glGetUniformLocation( debugProgramH, "u_objD");
188
    mDebugMVPMatrixH = GLES30.glGetUniformLocation( debugProgramH, "u_MVPMatrix");
189
    // END DEBUG  //////////////////////////////////////
190
    }
191

    
192
///////////////////////////////////////////////////////////////////////////////////////////////////
193

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

    
230
///////////////////////////////////////////////////////////////////////////////////////////////////
231
// DEBUG ONLY
232

    
233
  @SuppressWarnings("unused")
234
  private void displayBoundingRect(float halfX, float halfY, float halfZ, DistortedOutputSurface surface, float[] mvp, float[] vertices, long currTime)
235
    {
236
    int len  = vertices.length/3;
237
    int minx = Integer.MAX_VALUE;
238
    int maxx = Integer.MIN_VALUE;
239
    int miny = Integer.MAX_VALUE;
240
    int maxy = Integer.MIN_VALUE;
241
    int wx,wy;
242

    
243
    float x,y,z, X,Y,W, ndcX,ndcY;
244

    
245
    for(int i=0; i<len; i++)
246
      {
247
      x = 2*halfX*vertices[3*i  ];
248
      y = 2*halfY*vertices[3*i+1];
249
      z = 2*halfZ*vertices[3*i+2];
250

    
251
      X = mvp[ 0]*x + mvp[ 4]*y + mvp[ 8]*z + mvp[12];
252
      Y = mvp[ 1]*x + mvp[ 5]*y + mvp[ 9]*z + mvp[13];
253
      W = mvp[ 3]*x + mvp[ 7]*y + mvp[11]*z + mvp[15];
254

    
255
      ndcX = X/W;
256
      ndcY = Y/W;
257

    
258
      wx = (int)(surface.mWidth *(ndcX+1)/2);
259
      wy = (int)(surface.mHeight*(ndcY+1)/2);
260

    
261
      if( wx<minx ) minx = wx;
262
      if( wx>maxx ) maxx = wx;
263
      if( wy<miny ) miny = wy;
264
      if( wy>maxy ) maxy = wy;
265
      }
266

    
267
    mDebugProgram.useProgram();
268
    surface.setAsOutput(currTime);
269

    
270
    Matrix.setIdentityM( mTmpMatrix, 0);
271
    Matrix.translateM  ( mTmpMatrix, 0, minx-surface.mWidth/2, maxy-surface.mHeight/2, -surface.mDistance);
272
    Matrix.scaleM      ( mTmpMatrix, 0, (float)(maxx-minx)/(2*halfX), (float)(maxy-miny)/(2*halfY), 1.0f);
273
    Matrix.translateM  ( mTmpMatrix, 0, halfX,-halfY, 0);
274
    Matrix.multiplyMM  ( mMVPMatrix, 0, surface.mProjectionMatrix, 0, mTmpMatrix, 0);
275

    
276
    GLES30.glUniform2f(mDebugObjDH, 2*halfX, 2*halfY);
277
    GLES30.glUniformMatrix4fv(mDebugMVPMatrixH, 1, false, mMVPMatrix , 0);
278

    
279
    GLES30.glVertexAttribPointer(mDebugProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
280
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
281
    }
282

    
283
///////////////////////////////////////////////////////////////////////////////////////////////////
284

    
285
  void drawPriv(float halfW, float halfH, MeshObject mesh, DistortedOutputSurface surface, long currTime)
286
    {
287
    mM.compute(currTime);
288
    mV.compute(currTime);
289
    mF.compute(currTime);
290

    
291
    float halfZ = halfW*mesh.zFactor;
292

    
293
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
294

    
295
    mMainProgram.useProgram();
296
    GLES30.glUniform1i(mMainTextureH, 0);
297
    surface.setAsOutput(currTime);
298
    mM.send(surface,halfW,halfH,halfZ);
299
    mM.send(surface,halfW,halfH,halfZ);
300
    mV.send(halfW,halfH,halfZ);
301
    mF.send(halfW,halfH);
302

    
303
    GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, mesh.mPosVBO[0]);
304
    GLES30.glVertexAttribPointer(mMainProgram.mAttribute[0], MeshObject.POSITION_DATA_SIZE, GLES30.GL_FLOAT, false, 0, 0);
305
    GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, mesh.mNorVBO[0]);
306
    GLES30.glVertexAttribPointer(mMainProgram.mAttribute[1], MeshObject.NORMAL_DATA_SIZE  , GLES30.GL_FLOAT, false, 0, 0);
307
    GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, mesh.mTexVBO[0]);
308
    GLES30.glVertexAttribPointer(mMainProgram.mAttribute[2], MeshObject.TEX_DATA_SIZE     , GLES30.GL_FLOAT, false, 0, 0);
309
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.dataLength);
310
    GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0 );
311

    
312
    /// DEBUG ONLY //////
313
    // displayBoundingRect(halfInputW, halfInputH, halfZ, df, mM.getMVP(), mesh.getBoundingVertices() );
314
    /// END DEBUG ///////
315
    }
316

    
317
///////////////////////////////////////////////////////////////////////////////////////////////////
318
   
319
  static void blitPriv(DistortedOutputSurface surface)
320
    {
321
    mBlitProgram.useProgram();
322

    
323
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
324
    GLES30.glUniform1i(mBlitTextureH, 0);
325
    GLES30.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
326
    GLES30.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
327
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
328
    }
329
    
330
///////////////////////////////////////////////////////////////////////////////////////////////////
331
   
332
  private void releasePriv()
333
    {
334
    if( !matrixCloned     ) mM.abortAll(false);
335
    if( !vertexCloned     ) mV.abortAll(false);
336
    if( !fragmentCloned   ) mF.abortAll(false);
337

    
338
    mM = null;
339
    mV = null;
340
    mF = null;
341
    }
342

    
343
///////////////////////////////////////////////////////////////////////////////////////////////////
344

    
345
  static void onDestroy()
346
    {
347
    mNextID = 0;
348

    
349
    int len = EffectNames.size();
350

    
351
    for(int i=0; i<len; i++)
352
      {
353
      mEffectEnabled[i] = false;
354
      }
355
    }
356

    
357
///////////////////////////////////////////////////////////////////////////////////////////////////
358
// PUBLIC API
359
///////////////////////////////////////////////////////////////////////////////////////////////////
360
/**
361
 * Create empty effect queue.
362
 */
363
  public DistortedEffects()
364
    {
365
    mID = ++mNextID;
366
    initializeEffectLists(this,0);
367
    }
368

    
369
///////////////////////////////////////////////////////////////////////////////////////////////////
370
/**
371
 * Copy constructor.
372
 * <p>
373
 * Whatever we do not clone gets created just like in the default constructor.
374
 *
375
 * @param dc    Source object to create our object from
376
 * @param flags A bitmask of values specifying what to copy.
377
 *              For example, CLONE_VERTEX | CLONE_MATRIX.
378
 */
379
  public DistortedEffects(DistortedEffects dc, int flags)
380
    {
381
    mID = ++mNextID;
382
    initializeEffectLists(dc,flags);
383
    }
384

    
385
///////////////////////////////////////////////////////////////////////////////////////////////////
386
/**
387
 * Releases all resources. After this call, the queue should not be used anymore.
388
 */
389
  @SuppressWarnings("unused")
390
  public synchronized void delete()
391
    {
392
    releasePriv();
393
    }
394

    
395
///////////////////////////////////////////////////////////////////////////////////////////////////
396
/**
397
 * Returns unique ID of this instance.
398
 *
399
 * @return ID of the object.
400
 */
401
  public long getID()
402
      {
403
      return mID;
404
      }
405

    
406
///////////////////////////////////////////////////////////////////////////////////////////////////
407
/**
408
 * Adds the calling class to the list of Listeners that get notified each time some event happens 
409
 * to one of the Effects in those queues. Nothing will happen if 'el' is already in the list.
410
 * 
411
 * @param el A class implementing the EffectListener interface that wants to get notifications.
412
 */
413
  @SuppressWarnings("unused")
414
  public void registerForMessages(EffectListener el)
415
    {
416
    mV.registerForMessages(el);
417
    mF.registerForMessages(el);
418
    mM.registerForMessages(el);
419
    }
420

    
421
///////////////////////////////////////////////////////////////////////////////////////////////////
422
/**
423
 * Removes the calling class from the list of Listeners.
424
 * 
425
 * @param el A class implementing the EffectListener interface that no longer wants to get notifications.
426
 */
427
  @SuppressWarnings("unused")
428
  public void deregisterForMessages(EffectListener el)
429
    {
430
    mV.deregisterForMessages(el);
431
    mF.deregisterForMessages(el);
432
    mM.deregisterForMessages(el);
433
    }
434

    
435
///////////////////////////////////////////////////////////////////////////////////////////////////
436
/**
437
 * Aborts all Effects.
438
 * @return Number of effects aborted.
439
 */
440
  public int abortAllEffects()
441
    {
442
    return mM.abortAll(true) + mV.abortAll(true) + mF.abortAll(true);
443
    }
444

    
445
///////////////////////////////////////////////////////////////////////////////////////////////////
446
/**
447
 * Aborts all Effects of a given type, for example all MATRIX Effects.
448
 * 
449
 * @param type one of the constants defined in {@link EffectTypes}
450
 * @return Number of effects aborted.
451
 */
452
  public int abortEffects(EffectTypes type)
453
    {
454
    switch(type)
455
      {
456
      case MATRIX     : return mM.abortAll(true);
457
      case VERTEX     : return mV.abortAll(true);
458
      case FRAGMENT   : return mF.abortAll(true);
459
      default         : return 0;
460
      }
461
    }
462
    
463
///////////////////////////////////////////////////////////////////////////////////////////////////
464
/**
465
 * Aborts a single Effect.
466
 * 
467
 * @param id ID of the Effect we want to abort.
468
 * @return number of Effects aborted. Always either 0 or 1.
469
 */
470
  public int abortEffect(long id)
471
    {
472
    int type = (int)(id&EffectTypes.MASK);
473

    
474
    if( type==EffectTypes.MATRIX.type      ) return mM.removeByID(id>>EffectTypes.LENGTH);
475
    if( type==EffectTypes.VERTEX.type      ) return mV.removeByID(id>>EffectTypes.LENGTH);
476
    if( type==EffectTypes.FRAGMENT.type    ) return mF.removeByID(id>>EffectTypes.LENGTH);
477

    
478
    return 0;
479
    }
480

    
481
///////////////////////////////////////////////////////////////////////////////////////////////////
482
/**
483
 * Abort all Effects of a given name, for example all rotations.
484
 * 
485
 * @param name one of the constants defined in {@link EffectNames}
486
 * @return number of Effects aborted.
487
 */
488
  public int abortEffects(EffectNames name)
489
    {
490
    switch(name.getType())
491
      {
492
      case MATRIX     : return mM.removeByType(name);
493
      case VERTEX     : return mV.removeByType(name);
494
      case FRAGMENT   : return mF.removeByType(name);
495
      default         : return 0;
496
      }
497
    }
498
    
499
///////////////////////////////////////////////////////////////////////////////////////////////////
500
/**
501
 * Print some info about a given Effect to Android's standard out. Used for debugging only.
502
 * 
503
 * @param id Effect ID we want to print info about
504
 * @return <code>true</code> if a single Effect of type effectType has been found.
505
 */
506
  @SuppressWarnings("unused")
507
  public boolean printEffect(long id)
508
    {
509
    int type = (int)(id&EffectTypes.MASK);
510

    
511
    if( type==EffectTypes.MATRIX.type  )  return mM.printByID(id>>EffectTypes.LENGTH);
512
    if( type==EffectTypes.VERTEX.type  )  return mV.printByID(id>>EffectTypes.LENGTH);
513
    if( type==EffectTypes.FRAGMENT.type)  return mF.printByID(id>>EffectTypes.LENGTH);
514

    
515
    return false;
516
    }
517

    
518
///////////////////////////////////////////////////////////////////////////////////////////////////
519
/**
520
 * Enables a given Effect.
521
 * <p>
522
 * By default, all effects are disabled. One has to explicitly enable each effect one intends to use.
523
 * This needs to be called BEFORE shaders get compiled, i.e. before the call to Distorted.onCreate().
524
 * The point: by enabling only the effects we need, we can optimize the shaders.
525
 *
526
 * @param name Name of the Effect to enable.
527
 */
528
  public static void enableEffect(EffectNames name)
529
    {
530
    mEffectEnabled[name.ordinal()] = true;
531
    }
532

    
533
///////////////////////////////////////////////////////////////////////////////////////////////////
534
/**
535
 * Returns the maximum number of Matrix effects.
536
 *
537
 * @return The maximum number of Matrix effects
538
 */
539
  @SuppressWarnings("unused")
540
  public static int getMaxMatrix()
541
    {
542
    return EffectQueue.getMax(EffectTypes.MATRIX.ordinal());
543
    }
544

    
545
///////////////////////////////////////////////////////////////////////////////////////////////////
546
/**
547
 * Returns the maximum number of Vertex effects.
548
 *
549
 * @return The maximum number of Vertex effects
550
 */
551
  @SuppressWarnings("unused")
552
  public static int getMaxVertex()
553
    {
554
    return EffectQueue.getMax(EffectTypes.VERTEX.ordinal());
555
    }
556

    
557
///////////////////////////////////////////////////////////////////////////////////////////////////
558
/**
559
 * Returns the maximum number of Fragment effects.
560
 *
561
 * @return The maximum number of Fragment effects
562
 */
563
  @SuppressWarnings("unused")
564
  public static int getMaxFragment()
565
    {
566
    return EffectQueue.getMax(EffectTypes.FRAGMENT.ordinal());
567
    }
568

    
569
///////////////////////////////////////////////////////////////////////////////////////////////////
570
/**
571
 * Sets the maximum number of Matrix effects that can be stored in a single EffectQueue at one time.
572
 * This can fail if:
573
 * <ul>
574
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
575
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
576
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link Distorted#onCreate}. After this
577
 *     time only decreasing the value of 'max' is permitted.
578
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
579
 * </ul>
580
 *
581
 * @param max new maximum number of simultaneous Matrix Effects. Has to be a non-negative number not greater
582
 *            than Byte.MAX_VALUE
583
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
584
 */
585
  @SuppressWarnings("unused")
586
  public static boolean setMaxMatrix(int max)
587
    {
588
    return EffectQueue.setMax(EffectTypes.MATRIX.ordinal(),max);
589
    }
590

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

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

    
635
///////////////////////////////////////////////////////////////////////////////////////////////////   
636
///////////////////////////////////////////////////////////////////////////////////////////////////
637
// Individual effect functions.
638
///////////////////////////////////////////////////////////////////////////////////////////////////
639
// Matrix-based effects
640
///////////////////////////////////////////////////////////////////////////////////////////////////
641
/**
642
 * Moves the Object by a (possibly changing in time) vector.
643
 * 
644
 * @param vector 3-dimensional Data which at any given time will return a Static3D
645
 *               representing the current coordinates of the vector we want to move the Object with.
646
 * @return       ID of the effect added, or -1 if we failed to add one.
647
 */
648
  public long move(Data3D vector)
649
    {   
650
    return mM.add(EffectNames.MOVE,vector);
651
    }
652

    
653
///////////////////////////////////////////////////////////////////////////////////////////////////
654
/**
655
 * Scales the Object by (possibly changing in time) 3D scale factors.
656
 * 
657
 * @param scale 3-dimensional Data which at any given time returns a Static3D
658
 *              representing the current x- , y- and z- scale factors.
659
 * @return      ID of the effect added, or -1 if we failed to add one.
660
 */
661
  public long scale(Data3D scale)
662
    {   
663
    return mM.add(EffectNames.SCALE,scale);
664
    }
665

    
666
///////////////////////////////////////////////////////////////////////////////////////////////////
667
/**
668
 * Scales the Object by one uniform, constant factor in all 3 dimensions. Convenience function.
669
 *
670
 * @param scale The factor to scale all 3 dimensions with.
671
 * @return      ID of the effect added, or -1 if we failed to add one.
672
 */
673
  public long scale(float scale)
674
    {
675
    return mM.add(EffectNames.SCALE, new Static3D(scale,scale,scale));
676
    }
677

    
678
///////////////////////////////////////////////////////////////////////////////////////////////////
679
/**
680
 * Rotates the Object by 'angle' degrees around the center.
681
 * Static axis of rotation is given by the last parameter.
682
 *
683
 * @param angle  Angle that we want to rotate the Object to. Unit: degrees
684
 * @param axis   Axis of rotation
685
 * @param center Coordinates of the Point we are rotating around.
686
 * @return       ID of the effect added, or -1 if we failed to add one.
687
 */
688
  public long rotate(Data1D angle, Static3D axis, Data3D center )
689
    {   
690
    return mM.add(EffectNames.ROTATE, angle, axis, center);
691
    }
692

    
693
///////////////////////////////////////////////////////////////////////////////////////////////////
694
/**
695
 * Rotates the Object by 'angle' degrees around the center.
696
 * Here both angle and axis can dynamically change.
697
 *
698
 * @param angleaxis Combined 4-tuple representing the (angle,axisX,axisY,axisZ).
699
 * @param center    Coordinates of the Point we are rotating around.
700
 * @return          ID of the effect added, or -1 if we failed to add one.
701
 */
702
  public long rotate(Data4D angleaxis, Data3D center)
703
    {
704
    return mM.add(EffectNames.ROTATE, angleaxis, center);
705
    }
706

    
707
///////////////////////////////////////////////////////////////////////////////////////////////////
708
/**
709
 * Rotates the Object by quaternion.
710
 *
711
 * @param quaternion The quaternion describing the rotation.
712
 * @param center     Coordinates of the Point we are rotating around.
713
 * @return           ID of the effect added, or -1 if we failed to add one.
714
 */
715
  public long quaternion(Data4D quaternion, Data3D center )
716
    {
717
    return mM.add(EffectNames.QUATERNION,quaternion,center);
718
    }
719

    
720
///////////////////////////////////////////////////////////////////////////////////////////////////
721
/**
722
 * Shears the Object.
723
 *
724
 * @param shear   The 3-tuple of shear factors. The first controls level
725
 *                of shearing in the X-axis, second - Y-axis and the third -
726
 *                Z-axis. Each is the tangens of the shear angle, i.e 0 -
727
 *                no shear, 1 - shear by 45 degrees (tan(45deg)=1) etc.
728
 * @param center  Center of shearing, i.e. the point which stays unmoved.
729
 * @return        ID of the effect added, or -1 if we failed to add one.
730
 */
731
  public long shear(Data3D shear, Data3D center)
732
    {
733
    return mM.add(EffectNames.SHEAR, shear, center);
734
    }
735

    
736
///////////////////////////////////////////////////////////////////////////////////////////////////
737
// Fragment-based effects  
738
///////////////////////////////////////////////////////////////////////////////////////////////////
739
/**
740
 * Makes a certain sub-region of the Object smoothly change all three of its RGB components.
741
 *        
742
 * @param blend  1-dimensional Data that returns the level of blend a given pixel will be
743
 *               mixed with the next parameter 'color': pixel = (1-level)*pixel + level*color.
744
 *               Valid range: <0,1>
745
 * @param color  Color to mix. (1,0,0) is RED.
746
 * @param region Region this Effect is limited to.
747
 * @param smooth If true, the level of 'blend' will smoothly fade out towards the edges of the region.
748
 * @return       ID of the effect added, or -1 if we failed to add one.
749
 */
750
  public long chroma(Data1D blend, Data3D color, Data4D region, boolean smooth)
751
    {
752
    return mF.add( smooth? EffectNames.SMOOTH_CHROMA:EffectNames.CHROMA, blend, color, region);
753
    }
754

    
755
///////////////////////////////////////////////////////////////////////////////////////////////////
756
/**
757
 * Makes the whole Object smoothly change all three of its RGB components.
758
 *
759
 * @param blend  1-dimensional Data that returns the level of blend a given pixel will be
760
 *               mixed with the next parameter 'color': pixel = (1-level)*pixel + level*color.
761
 *               Valid range: <0,1>
762
 * @param color  Color to mix. (1,0,0) is RED.
763
 * @return       ID of the effect added, or -1 if we failed to add one.
764
 */
765
  public long chroma(Data1D blend, Data3D color)
766
    {
767
    return mF.add(EffectNames.CHROMA, blend, color);
768
    }
769

    
770
///////////////////////////////////////////////////////////////////////////////////////////////////
771
/**
772
 * Makes a certain sub-region of the Object smoothly change its transparency level.
773
 *        
774
 * @param alpha  1-dimensional Data that returns the level of transparency we want to have at any given
775
 *               moment: pixel.a *= alpha.
776
 *               Valid range: <0,1>
777
 * @param region Region this Effect is limited to. 
778
 * @param smooth If true, the level of 'alpha' will smoothly fade out towards the edges of the region.
779
 * @return       ID of the effect added, or -1 if we failed to add one. 
780
 */
781
  public long alpha(Data1D alpha, Data4D region, boolean smooth)
782
    {
783
    return mF.add( smooth? EffectNames.SMOOTH_ALPHA:EffectNames.ALPHA, alpha, region);
784
    }
785

    
786
///////////////////////////////////////////////////////////////////////////////////////////////////
787
/**
788
 * Makes the whole Object smoothly change its transparency level.
789
 *
790
 * @param alpha  1-dimensional Data that returns the level of transparency we want to have at any
791
 *               given moment: pixel.a *= alpha.
792
 *               Valid range: <0,1>
793
 * @return       ID of the effect added, or -1 if we failed to add one.
794
 */
795
  public long alpha(Data1D alpha)
796
    {
797
    return mF.add(EffectNames.ALPHA, alpha);
798
    }
799

    
800
///////////////////////////////////////////////////////////////////////////////////////////////////
801
/**
802
 * Makes a certain sub-region of the Object smoothly change its brightness level.
803
 *        
804
 * @param brightness 1-dimensional Data that returns the level of brightness we want to have
805
 *                   at any given moment. Valid range: <0,infinity)
806
 * @param region     Region this Effect is limited to.
807
 * @param smooth     If true, the level of 'brightness' will smoothly fade out towards the edges of the region.
808
 * @return           ID of the effect added, or -1 if we failed to add one.
809
 */
810
  public long brightness(Data1D brightness, Data4D region, boolean smooth)
811
    {
812
    return mF.add( smooth ? EffectNames.SMOOTH_BRIGHTNESS: EffectNames.BRIGHTNESS, brightness, region);
813
    }
814

    
815
///////////////////////////////////////////////////////////////////////////////////////////////////
816
/**
817
 * Makes the whole Object smoothly change its brightness level.
818
 *
819
 * @param brightness 1-dimensional Data that returns the level of brightness we want to have
820
 *                   at any given moment. Valid range: <0,infinity)
821
 * @return           ID of the effect added, or -1 if we failed to add one.
822
 */
823
  public long brightness(Data1D brightness)
824
    {
825
    return mF.add(EffectNames.BRIGHTNESS, brightness);
826
    }
827

    
828
///////////////////////////////////////////////////////////////////////////////////////////////////
829
/**
830
 * Makes a certain sub-region of the Object smoothly change its contrast level.
831
 *        
832
 * @param contrast 1-dimensional Data that returns the level of contrast we want to have
833
 *                 at any given moment. Valid range: <0,infinity)
834
 * @param region   Region this Effect is limited to.
835
 * @param smooth   If true, the level of 'contrast' will smoothly fade out towards the edges of the region.
836
 * @return         ID of the effect added, or -1 if we failed to add one.
837
 */
838
  public long contrast(Data1D contrast, Data4D region, boolean smooth)
839
    {
840
    return mF.add( smooth ? EffectNames.SMOOTH_CONTRAST:EffectNames.CONTRAST, contrast, region);
841
    }
842

    
843
///////////////////////////////////////////////////////////////////////////////////////////////////
844
/**
845
 * Makes the whole Object smoothly change its contrast level.
846
 *
847
 * @param contrast 1-dimensional Data that returns the level of contrast we want to have
848
 *                 at any given moment. Valid range: <0,infinity)
849
 * @return         ID of the effect added, or -1 if we failed to add one.
850
 */
851
  public long contrast(Data1D contrast)
852
    {
853
    return mF.add(EffectNames.CONTRAST, contrast);
854
    }
855

    
856
///////////////////////////////////////////////////////////////////////////////////////////////////
857
/**
858
 * Makes a certain sub-region of the Object smoothly change its saturation level.
859
 *        
860
 * @param saturation 1-dimensional Data that returns the level of saturation we want to have
861
 *                   at any given moment. Valid range: <0,infinity)
862
 * @param region     Region this Effect is limited to.
863
 * @param smooth     If true, the level of 'saturation' will smoothly fade out towards the edges of the region.
864
 * @return           ID of the effect added, or -1 if we failed to add one.
865
 */
866
  public long saturation(Data1D saturation, Data4D region, boolean smooth)
867
    {
868
    return mF.add( smooth ? EffectNames.SMOOTH_SATURATION:EffectNames.SATURATION, saturation, region);
869
    }
870

    
871
///////////////////////////////////////////////////////////////////////////////////////////////////
872
/**
873
 * Makes the whole Object smoothly change its saturation level.
874
 *
875
 * @param saturation 1-dimensional Data that returns the level of saturation we want to have
876
 *                   at any given moment. Valid range: <0,infinity)
877
 * @return           ID of the effect added, or -1 if we failed to add one.
878
 */
879
  public long saturation(Data1D saturation)
880
    {
881
    return mF.add(EffectNames.SATURATION, saturation);
882
    }
883

    
884
///////////////////////////////////////////////////////////////////////////////////////////////////
885
// Vertex-based effects  
886
///////////////////////////////////////////////////////////////////////////////////////////////////
887
/**
888
 * Distort a (possibly changing in time) part of the Object by a (possibly changing in time) vector of force.
889
 *
890
 * @param vector 3-dimensional Vector which represents the force the Center of the Effect is
891
 *               currently being dragged with.
892
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
893
 * @param region Region that masks the Effect.
894
 * @return       ID of the effect added, or -1 if we failed to add one.
895
 */
896
  public long distort(Data3D vector, Data3D center, Data4D region)
897
    {  
898
    return mV.add(EffectNames.DISTORT, vector, center, region);
899
    }
900

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

    
915
///////////////////////////////////////////////////////////////////////////////////////////////////
916
/**
917
 * Deform the shape of the whole Object with a (possibly changing in time) vector of force applied to
918
 * a (possibly changing in time) point on the Object.
919
 *
920
 * @param vector Vector of force that deforms the shape of the whole Object.
921
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
922
 * @param region Region that masks the Effect.
923
 * @return       ID of the effect added, or -1 if we failed to add one.
924
 */
925
  public long deform(Data3D vector, Data3D center, Data4D region)
926
    {
927
    return mV.add(EffectNames.DEFORM, vector, center, region);
928
    }
929

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

    
944
///////////////////////////////////////////////////////////////////////////////////////////////////  
945
/**
946
 * Pull all points around the center of the Effect towards the center (if degree>=1) or push them
947
 * away from the center (degree<=1)
948
 *
949
 * @param sink   The current degree of the Effect.
950
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
951
 * @param region Region that masks the Effect.
952
 * @return       ID of the effect added, or -1 if we failed to add one.
953
 */
954
  public long sink(Data1D sink, Data3D center, Data4D region)
955
    {
956
    return mV.add(EffectNames.SINK, sink, center, region);
957
    }
958

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

    
973
///////////////////////////////////////////////////////////////////////////////////////////////////
974
/**
975
 * Pull all points around the center of the Effect towards a line passing through the center
976
 * (that's if degree>=1) or push them away from the line (degree<=1)
977
 *
978
 * @param pinch  The current degree of the Effect + angle the line forms with X-axis
979
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
980
 * @param region Region that masks the Effect.
981
 * @return       ID of the effect added, or -1 if we failed to add one.
982
 */
983
  public long pinch(Data2D pinch, Data3D center, Data4D region)
984
    {
985
    return mV.add(EffectNames.PINCH, pinch, center, region);
986
    }
987

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

    
1002
///////////////////////////////////////////////////////////////////////////////////////////////////  
1003
/**
1004
 * Rotate part of the Object around the Center of the Effect by a certain angle.
1005
 *
1006
 * @param swirl  The angle of Swirl (in degrees). Positive values swirl clockwise.
1007
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
1008
 * @param region Region that masks the Effect.
1009
 * @return       ID of the effect added, or -1 if we failed to add one.
1010
 */
1011
  public long swirl(Data1D swirl, Data3D center, Data4D region)
1012
    {    
1013
    return mV.add(EffectNames.SWIRL, swirl, center, region);
1014
    }
1015

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

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

    
1063
///////////////////////////////////////////////////////////////////////////////////////////////////
1064
/**
1065
 * Directional, sinusoidal wave effect.
1066
 *
1067
 * @param wave   see {@link DistortedEffects#wave(Data5D,Data3D)}
1068
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
1069
 * @param region Region that masks the Effect.
1070
 * @return       ID of the effect added, or -1 if we failed to add one.
1071
 */
1072
  public long wave(Data5D wave, Data3D center, Data4D region)
1073
    {
1074
    return mV.add(EffectNames.WAVE, wave, center, region);
1075
    }
1076
  }
(2-2/26)