Project

General

Profile

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

library / src / main / java / org / distorted / library / type / Dynamic.java @ 4f9ec5d6

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

    
22
import org.distorted.library.main.InternalMaster;
23

    
24
import java.util.ArrayList;
25
import java.util.Random;
26
import java.util.Vector;
27

    
28
///////////////////////////////////////////////////////////////////////////////////////////////////
29
/** A class to interpolate between a list of Statics.
30
* <p><ul>
31
* <li>if there is only one Point, just return it.
32
* <li>if there are two Points, linearly bounce between them
33
* <li>if there are more, interpolate a path between them. Exact way we interpolate depends on the MODE.
34
* </ul>
35
*/
36

    
37
// The way Interpolation between more than 2 Points is done:
38
// 
39
// Def: let V[i] = (V[i](x), V[i](y), V[i](z)) be the direction and speed (i.e. velocity) we have to
40
// be flying at Point P[i]
41
//
42
// Time it takes to fly though one segment P[i] --> P[i+1] : 0.0 --> 1.0
43
//
44
// We arbitrarily decide that V[i] should be equal to (|curr|*prev + |prev|*curr) / min(|prev|,|curr|)
45
// where prev = P[i]-P[i-1] and curr = P[i+1]-P[i]
46
//
47
// Given that the flight route (X(t), Y(t), Z(t)) from P(i) to P(i+1)  (0<=t<=1) has to satisfy
48
// X(0) = P[i  ](x), Y(0)=P[i  ](y), Z(0)=P[i  ](z), X'(0) = V[i  ](x), Y'(0) = V[i  ](y), Z'(0) = V[i  ](z)
49
// X(1) = P[i+1](x), Y(1)=P[i+1](y), Z(1)=P[i+1](z), X'(1) = V[i+1](x), Y'(1) = V[i+1](y), Z'(1) = V[i+1](z)
50
//
51
// we have the solution:  X(t) = at^3 + bt^2 + ct + d where
52
// a =  2*P[i](x) +   V[i](x) - 2*P[i+1](x) + V[i+1](x)
53
// b = -3*P[i](x) - 2*V[i](x) + 3*P[i+1](x) - V[i+1](x)
54
// c =                V[i](x)
55
// d =    P[i](x)
56
//
57
// and similarly Y(t) and Z(t).
58

    
59
public abstract class Dynamic implements InternalMaster.Slave
60
  {
61
  /**
62
   * One revolution takes us from the first point to the last and back to first through the shortest path.
63
   */
64
  public static final int MODE_LOOP = 0; 
65
  /**
66
   * One revolution takes us from the first point to the last and back to first through the same path.
67
   */
68
  public static final int MODE_PATH = 1; 
69
  /**
70
   * One revolution takes us from the first point to the last and jumps straight back to the first point.
71
   */
72
  public static final int MODE_JUMP = 2; 
73

    
74
  /**
75
   * The default mode of access. When in this mode, we are able to call interpolate() with points in time
76
   * in any random order. This means one single Dynamic can be used in many effects simultaneously.
77
   * On the other hand, when in this mode, it is not possible to smoothly interpolate when mDuration suddenly
78
   * changes.
79
   */
80
  public static final int ACCESS_TYPE_RANDOM     = 0;
81
  /**
82
   * Set the mode to ACCESS_SEQUENTIAL if you need to change mDuration and you would rather have the Dynamic
83
   * keep on smoothly interpolating.
84
   * On the other hand, in this mode, a Dynamic can only be accessed in sequential manner, which means one
85
   * Dynamic can only be used in one effect at a time.
86
   */
87
  public static final int ACCESS_TYPE_SEQUENTIAL = 1;
88

    
89
  protected int mDimension;
90
  protected int numPoints;
91
  protected int mSegment;       // between which pair of points are we currently? (in case of PATH this is a bit complicated!)
92
  protected boolean cacheDirty; // VectorCache not up to date
93
  protected int mMode;          // LOOP, PATH or JUMP
94
  protected long mDuration;     // number of milliseconds it takes to do a full loop/path from first vector to the last and back to the first
95
  protected float mCount;       // number of loops/paths we will do; mCount = 1.5 means we go from the first vector to the last, back to first, and to the last again. 
96
  protected double mLastPos;
97
  protected int mAccessType;
98

    
99
  protected class VectorNoise
100
    {
101
    float[][] n;
102

    
103
    VectorNoise()
104
      {
105
      n = new float[mDimension][NUM_NOISE];
106
      }
107

    
108
    void computeNoise()
109
      {
110
      n[0][0] = mRnd.nextFloat();
111
      for(int i=1; i<NUM_NOISE; i++) n[0][i] = n[0][i-1]+mRnd.nextFloat();
112

    
113
      float sum = n[0][NUM_NOISE-1] + mRnd.nextFloat();
114

    
115
      for(int i=0; i<NUM_NOISE; i++)
116
        {
117
        n[0][i] /=sum;
118
        for(int j=1; j<mDimension; j++) n[j][i] = mRnd.nextFloat()-0.5f;
119
        }
120
      }
121
    }
122

    
123
  protected Vector<VectorNoise> vn;
124
  protected float[] mFactor;
125
  protected float[] mNoise;
126
  protected float[][] baseV;
127

    
128
  ///////////////////////////////////////////////////////////////////////////////////////////////////
129
  // the coefficients of the X(t), Y(t) and Z(t) polynomials: X(t) = ax*T^3 + bx*T^2 + cx*t + dx  etc.
130
  // (tangent) is the vector tangent to the path.
131
  // (cached) is the original vector from vv (copied here so when interpolating we can see if it is
132
  // still valid and if not - rebuild the Cache
133

    
134
  protected class VectorCache
135
    {
136
    float[] a;
137
    float[] b;
138
    float[] c;
139
    float[] d;
140
    float[] tangent;
141
    float[] cached;
142

    
143
    VectorCache()
144
      {
145
      a = new float[mDimension];
146
      b = new float[mDimension];
147
      c = new float[mDimension];
148
      d = new float[mDimension];
149
      tangent = new float[mDimension];
150
      cached = new float[mDimension];
151
      }
152
    }
153

    
154
  protected Vector<VectorCache> vc;
155
  protected VectorCache tmp1, tmp2;
156
  protected float mConvexity;
157

    
158
  private float[] buf;
159
  private float[] old;
160
  private static final Random mRnd = new Random();
161
  private static final int NUM_NOISE = 5; // used iff mNoise>0.0. Number of intermediary points between each pair of adjacent vectors
162
                                          // where we randomize noise factors to make the way between the two vectors not so smooth.
163
  private long mStartTime;
164
  private long mCorrectedTime;
165
  private static long mPausedTime;
166

    
167
  private static final int JOB_RESET = 0;
168

    
169
  private static class Job
170
    {
171
    int type;
172

    
173
    Job(int t)
174
      {
175
      type  = t;
176
      }
177
    }
178

    
179
  private ArrayList<Job> mJobs;
180

    
181
///////////////////////////////////////////////////////////////////////////////////////////////////
182
// hide this from Javadoc
183
  
184
  protected Dynamic()
185
    {
186

    
187
    }
188

    
189
///////////////////////////////////////////////////////////////////////////////////////////////////
190

    
191
  protected Dynamic(int duration, float count, int dimension)
192
    {
193
    vc         = new Vector<>();
194
    vn         = null;
195
    numPoints  = 0;
196
    cacheDirty = false;
197
    mMode      = MODE_LOOP;
198
    mDuration  = duration;
199
    mCount     = count;
200
    mDimension = dimension;
201
    mSegment   = -1;
202
    mLastPos   = -1;
203
    mAccessType= ACCESS_TYPE_RANDOM;
204
    mConvexity = 1.0f;
205
    mStartTime = -1;
206
    mCorrectedTime = 0;
207

    
208
    baseV      = new float[mDimension][mDimension];
209
    buf        = new float[mDimension];
210
    old        = new float[mDimension];
211
    }
212

    
213
///////////////////////////////////////////////////////////////////////////////////////////////////
214

    
215
  void initDynamic()
216
    {
217
    mStartTime = -1;
218
    mCorrectedTime = 0;
219
    }
220

    
221
///////////////////////////////////////////////////////////////////////////////////////////////////
222

    
223
  public static void onPause()
224
    {
225
    mPausedTime = System.currentTimeMillis();
226
    }
227

    
228
///////////////////////////////////////////////////////////////////////////////////////////////////
229

    
230
  protected float noise(float time,int vecNum)
231
    {
232
    float lower, upper, len;
233
    float d = time*(NUM_NOISE+1);
234
    int index = (int)d;
235
    if( index>=NUM_NOISE+1 ) index=NUM_NOISE;
236
    VectorNoise tmpN = vn.elementAt(vecNum);
237

    
238
    float t = d-index;
239
    t = t*t*(3-2*t);
240

    
241
    switch(index)
242
      {
243
      case 0        : for(int i=0;i<mDimension-1;i++) mFactor[i] = mNoise[i+1]*tmpN.n[i+1][0]*t;
244
                      return time + mNoise[0]*(d*tmpN.n[0][0]-time);
245
      case NUM_NOISE: for(int i=0;i<mDimension-1;i++) mFactor[i] = mNoise[i+1]*tmpN.n[i+1][NUM_NOISE-1]*(1-t);
246
                      len = ((float)NUM_NOISE)/(NUM_NOISE+1);
247
                      lower = len + mNoise[0]*(tmpN.n[0][NUM_NOISE-1]-len);
248
                      return (1.0f-lower)*(d-NUM_NOISE) + lower;
249
      default       : float ya,yb;
250

    
251
                      for(int i=0;i<mDimension-1;i++)
252
                        {
253
                        yb = tmpN.n[i+1][index  ];
254
                        ya = tmpN.n[i+1][index-1];
255
                        mFactor[i] = mNoise[i+1]*((yb-ya)*t+ya);
256
                        }
257

    
258
                      len = ((float)index)/(NUM_NOISE+1);
259
                      lower = len + mNoise[0]*(tmpN.n[0][index-1]-len);
260
                      len = ((float)index+1)/(NUM_NOISE+1);
261
                      upper = len + mNoise[0]*(tmpN.n[0][index  ]-len);
262

    
263
                      return (upper-lower)*(d-index) + lower;
264
      }
265
    }
266

    
267
///////////////////////////////////////////////////////////////////////////////////////////////////
268
// debugging only
269

    
270
  private void printBase(String str)
271
    {
272
    String s;
273
    float t;
274

    
275
    for(int i=0; i<mDimension; i++)
276
      {
277
      s = "";
278

    
279
      for(int j=0; j<mDimension; j++)
280
        {
281
        t = ((int)(1000*baseV[i][j]))/(1000.0f);
282
        s+=(" "+t);
283
        }
284
      android.util.Log.e("dynamic", str+" base "+i+" : " + s);
285
      }
286
    }
287

    
288
///////////////////////////////////////////////////////////////////////////////////////////////////
289
// debugging only
290

    
291
  @SuppressWarnings("unused")
292
  private void checkBase()
293
    {
294
    float tmp, cosA;
295
    float[] len= new float[mDimension];
296
    boolean error=false;
297

    
298
    for(int i=0; i<mDimension; i++)
299
      {
300
      len[i] = 0.0f;
301

    
302
      for(int k=0; k<mDimension; k++)
303
        {
304
        len[i] += baseV[i][k]*baseV[i][k];
305
        }
306

    
307
      if( len[i] == 0.0f || len[0]/len[i] < 0.95f || len[0]/len[i]>1.05f )
308
        {
309
        android.util.Log.e("dynamic", "length of vector "+i+" : "+Math.sqrt(len[i]));
310
        error = true;
311
        }
312
      }
313

    
314
    for(int i=0; i<mDimension; i++)
315
      for(int j=i+1; j<mDimension; j++)
316
        {
317
        tmp = 0.0f;
318

    
319
        for(int k=0; k<mDimension; k++)
320
          {
321
          tmp += baseV[i][k]*baseV[j][k];
322
          }
323

    
324
        cosA = ( (len[i]==0.0f || len[j]==0.0f) ? 0.0f : tmp/(float)Math.sqrt(len[i]*len[j]));
325

    
326
        if( cosA > 0.05f || cosA < -0.05f )
327
          {
328
          android.util.Log.e("dynamic", "cos angle between vectors "+i+" and "+j+" : "+cosA);
329
          error = true;
330
          }
331
        }
332

    
333
    if( error ) printBase("");
334
    }
335

    
336
///////////////////////////////////////////////////////////////////////////////////////////////////
337

    
338
  int getNext(int curr, float time)
339
    {
340
    switch(mMode)
341
      {
342
      case MODE_LOOP: return curr==numPoints-1 ? 0:curr+1;
343
      case MODE_PATH: return time<0.5f ? (curr+1) : (curr==0 ? 1 : curr-1);
344
      case MODE_JUMP: return curr==numPoints-1 ? 1:curr+1;
345
      default       : return 0;
346
      }
347
    }
348

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

    
351
  private void checkAngle(int index)
352
    {
353
    float cosA = 0.0f;
354

    
355
    for(int k=0;k<mDimension; k++)
356
      cosA += baseV[index][k]*old[k];
357

    
358
    if( cosA<0.0f )
359
      {
360
/*
361
      /// DEBUGGING ////
362
      String s = index+" (";
363
      float t;
364

    
365
      for(int j=0; j<mDimension; j++)
366
        {
367
        t = ((int)(100*baseV[index][j]))/(100.0f);
368
        s+=(" "+t);
369
        }
370
      s += ") (";
371

    
372
      for(int j=0; j<mDimension; j++)
373
        {
374
        t = ((int)(100*old[j]))/(100.0f);
375
        s+=(" "+t);
376
        }
377
      s+= ")";
378

    
379
      android.util.Log.e("dynamic", "kat: " + s);
380
      /// END DEBUGGING ///
381
*/
382
      for(int j=0; j<mDimension; j++)
383
        baseV[index][j] = -baseV[index][j];
384
      }
385
    }
386

    
387
///////////////////////////////////////////////////////////////////////////////////////////////////
388
// helper function in case we are interpolating through exactly 2 points
389

    
390
  protected void computeOrthonormalBase2(Static curr, Static next)
391
    {
392
    switch(mDimension)
393
      {
394
      case 1: Static1D curr1 = (Static1D)curr;
395
              Static1D next1 = (Static1D)next;
396
              baseV[0][0] = (next1.x-curr1.x);
397
              break;
398
      case 2: Static2D curr2 = (Static2D)curr;
399
              Static2D next2 = (Static2D)next;
400
              baseV[0][0] = (next2.x-curr2.x);
401
              baseV[0][1] = (next2.y-curr2.y);
402
              break;
403
      case 3: Static3D curr3 = (Static3D)curr;
404
              Static3D next3 = (Static3D)next;
405
              baseV[0][0] = (next3.x-curr3.x);
406
              baseV[0][1] = (next3.y-curr3.y);
407
              baseV[0][2] = (next3.z-curr3.z);
408
              break;
409
      case 4: Static4D curr4 = (Static4D)curr;
410
              Static4D next4 = (Static4D)next;
411
              baseV[0][0] = (next4.x-curr4.x);
412
              baseV[0][1] = (next4.y-curr4.y);
413
              baseV[0][2] = (next4.z-curr4.z);
414
              baseV[0][3] = (next4.w-curr4.w);
415
              break;
416
      case 5: Static5D curr5 = (Static5D)curr;
417
              Static5D next5 = (Static5D)next;
418
              baseV[0][0] = (next5.x-curr5.x);
419
              baseV[0][1] = (next5.y-curr5.y);
420
              baseV[0][2] = (next5.z-curr5.z);
421
              baseV[0][3] = (next5.w-curr5.w);
422
              baseV[0][4] = (next5.v-curr5.v);
423
              break;
424
      default: throw new RuntimeException("Unsupported dimension");
425
      }
426

    
427
    if( baseV[0][0] == 0.0f )
428
      {
429
      baseV[1][0] = 1.0f;
430
      baseV[1][1] = 0.0f;
431
      }
432
    else
433
      {
434
      baseV[1][0] = 0.0f;
435
      baseV[1][1] = 1.0f;
436
      }
437

    
438
    for(int i=2; i<mDimension; i++)
439
      {
440
      baseV[1][i] = 0.0f;
441
      }
442

    
443
    computeOrthonormalBase();
444
    }
445

    
446
///////////////////////////////////////////////////////////////////////////////////////////////////
447
// helper function in case we are interpolating through more than 2 points
448

    
449
  protected void computeOrthonormalBaseMore(float time,VectorCache vc)
450
    {
451
    for(int i=0; i<mDimension; i++)
452
      {
453
      baseV[0][i] = (3*vc.a[i]*time+2*vc.b[i])*time+vc.c[i];   // first derivative, i.e. velocity vector
454
      old[i]      = baseV[1][i];
455
      baseV[1][i] =  6*vc.a[i]*time+2*vc.b[i];                 // second derivative,i.e. acceleration vector
456
      }
457

    
458
    computeOrthonormalBase();
459
    }
460

    
461
///////////////////////////////////////////////////////////////////////////////////////////////////
462
// When this function gets called, baseV[0] and baseV[1] should have been filled with two mDimension-al
463
// vectors. This function then fills the rest of the baseV array with a mDimension-al Orthonormal base.
464
// (mDimension-2 vectors, pairwise orthogonal to each other and to the original 2). The function always
465
// leaves base[0] alone but generally speaking must adjust base[1] to make it orthogonal to base[0]!
466
// The whole baseV is then used to compute Noise.
467
//
468
// When computing noise of a point travelling along a N-dimensional path, there are three cases:
469
// a) we may be interpolating through 1 point, i.e. standing in place - nothing to do in this case
470
// b) we may be interpolating through 2 points, i.e. travelling along a straight line between them -
471
//    then pass the velocity vector in baseV[0] and anything linearly independent in base[1].
472
//    The output will then be discontinuous in dimensions>2 (sad corollary from the Hairy Ball Theorem)
473
//    but we don't care - we are travelling along a straight line, so velocity (aka baseV[0]!) does
474
//    not change.
475
// c) we may be interpolating through more than 2 points. Then interpolation formulas ensure the path
476
//    will never be a straight line, even locally -> we can pass in baseV[0] and baseV[1] the velocity
477
//    and the acceleration (first and second derivatives of the path) which are then guaranteed to be
478
//    linearly independent. Then we can ensure this is continuous in dimensions <=4. This leaves
479
//    dimension 5 (ATM WAVE is 5-dimensional) discontinuous -> WAVE will suffer from chaotic noise.
480
//
481
// Bear in mind here the 'normal' in 'orthonormal' means 'length equal to the length of the original
482
// velocity vector' (rather than the standard 1)
483

    
484
  protected void computeOrthonormalBase()
485
    {
486
    int last_non_zero=-1;
487
    float tmp;
488

    
489
    for(int i=0; i<mDimension; i++)
490
      if( baseV[0][i] != 0.0f )
491
        last_non_zero=i;
492

    
493
    if( last_non_zero==-1 )                                               ///
494
      {                                                                   //  velocity is the 0 vector -> two
495
      for(int i=0; i<mDimension-1; i++)                                   //  consecutive points we are interpolating
496
        for(int j=0; j<mDimension; j++)                                   //  through are identical -> no noise,
497
          baseV[i+1][j]= 0.0f;                                            //  set the base to 0 vectors.
498
      }                                                                   ///
499
    else
500
      {
501
      for(int i=1; i<mDimension; i++)                                     /// One iteration computes baseV[i][*]
502
        {                                                                 //  (aka b[i]), the i-th orthonormal vector.
503
        buf[i-1]=0.0f;                                                    //
504
                                                                          //  We can use (modified!) Gram-Schmidt.
505
        for(int k=0; k<mDimension; k++)                                   //
506
          {                                                               //
507
          if( i>=2 )                                                      //  b[0] = b[0]
508
            {                                                             //  b[1] = b[1] - (<b[1],b[0]>/<b[0],b[0]>)*b[0]
509
            old[k] = baseV[i][k];                                         //  b[2] = b[2] - (<b[2],b[0]>/<b[0],b[0]>)*b[0] - (<b[2],b[1]>/<b[1],b[1]>)*b[1]
510
            baseV[i][k]= (k==i-(last_non_zero>=i?1:0)) ? 1.0f : 0.0f;     //  b[3] = b[3] - (<b[3],b[0]>/<b[0],b[0]>)*b[0] - (<b[3],b[1]>/<b[1],b[1]>)*b[1] - (<b[3],b[2]>/<b[2],b[2]>)*b[2]
511
            }                                                             //  (...)
512
                                                                          //  then b[i] = b[i] / |b[i]|  ( Here really b[i] = b[i] / (|b[0]|/|b[i]|)
513
          tmp = baseV[i-1][k];                                            //
514
          buf[i-1] += tmp*tmp;                                            //
515
          }                                                               //
516
                                                                          //
517
        for(int j=0; j<i; j++)                                            //
518
          {                                                               //
519
          tmp = 0.0f;                                                     //
520
          for(int k=0;k<mDimension; k++) tmp += baseV[i][k]*baseV[j][k];  //
521
          tmp /= buf[j];                                                  //
522
          for(int k=0;k<mDimension; k++) baseV[i][k] -= tmp*baseV[j][k];  //
523
          }                                                               //
524
                                                                          //
525
        checkAngle(i);                                                    //
526
        }                                                                 /// end compute baseV[i][*]
527

    
528
      buf[mDimension-1]=0.0f;                                             /// Normalize
529
      for(int k=0; k<mDimension; k++)                                     //
530
        {                                                                 //
531
        tmp = baseV[mDimension-1][k];                                     //
532
        buf[mDimension-1] += tmp*tmp;                                     //
533
        }                                                                 //
534
                                                                          //
535
      for(int i=1; i<mDimension; i++)                                     //
536
        {                                                                 //
537
        tmp = (float)Math.sqrt(buf[0]/buf[i]);                            //
538
        for(int k=0;k<mDimension; k++) baseV[i][k] *= tmp;                //
539
        }                                                                 /// End Normalize
540
      }
541
    }
542

    
543
///////////////////////////////////////////////////////////////////////////////////////////////////
544

    
545
  private void resetToBeginningNow()
546
    {
547
    mStartTime = -1;
548
    }
549

    
550
///////////////////////////////////////////////////////////////////////////////////////////////////
551

    
552
  abstract void interpolate(float[] buffer, int offset, float time);
553

    
554
///////////////////////////////////////////////////////////////////////////////////////////////////
555
// PUBLIC API
556
///////////////////////////////////////////////////////////////////////////////////////////////////
557

    
558
/**
559
 * Sets the mode of the interpolation to Loop, Path or Jump.
560
 * <ul>
561
 * <li>Loop is when we go from the first point all the way to the last, and the back to the first through 
562
 * the shortest way.
563
 * <li>Path is when we come back from the last point back to the first the same way we got there.
564
 * <li>Jump is when we go from first to last and then jump straight back to the first.
565
 * </ul>
566
 * 
567
 * @param mode {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
568
 */
569
  public void setMode(int mode)
570
    {
571
    mMode = mode;  
572
    }
573

    
574
///////////////////////////////////////////////////////////////////////////////////////////////////
575
/**
576
 * Returns the number of Points this Dynamic has been fed with.
577
 *   
578
 * @return the number of Points we are currently interpolating through.
579
 */
580
  public synchronized int getNumPoints()
581
    {
582
    return numPoints;  
583
    }
584

    
585
///////////////////////////////////////////////////////////////////////////////////////////////////
586
/**
587
 * Sets how many revolutions we want to do.
588
 * <p>
589
 * Does not have to be an integer. What constitutes 'one revolution' depends on the MODE:
590
 * {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
591
 * Count<=0 means 'go on interpolating indefinitely'.
592
 * 
593
 * @param count the number of times we want to interpolate between our collection of Points.
594
 */
595
  public void setCount(float count)
596
    {
597
    mCount = count;  
598
    }
599

    
600
///////////////////////////////////////////////////////////////////////////////////////////////////
601
/**
602
 * Return the number of revolutions this Dynamic will make.
603
 * What constitutes 'one revolution' depends on the MODE:
604
 * {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
605
 *
606
 * @return the number revolutions this Dynamic will make.
607
 */
608
  public float getCount()
609
    {
610
    return mCount;
611
    }
612

    
613
///////////////////////////////////////////////////////////////////////////////////////////////////
614
/**
615
 * Start running from the beginning again.
616
 *
617
 * If a Dynamic has been used already, and we want to use it again and start interpolating from the
618
 * first Point, first we need to reset it using this method.
619
 */
620
  public void resetToBeginning()
621
    {
622
    if( mJobs==null ) mJobs = new ArrayList<>();
623

    
624
    mJobs.add(new Job(JOB_RESET));
625
    InternalMaster.newSlave(this);
626
    }
627

    
628
///////////////////////////////////////////////////////////////////////////////////////////////////
629
/**
630
 * @param duration Number of milliseconds one revolution will take.
631
 *                 What constitutes 'one revolution' depends on the MODE:
632
 *                 {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
633
 */
634
  public void setDuration(long duration)
635
    {
636
    mDuration = duration;
637
    }
638

    
639
///////////////////////////////////////////////////////////////////////////////////////////////////
640
/**
641
 * @return Number of milliseconds one revolution will take.
642
 */
643
  public long getDuration()
644
    {
645
    return mDuration;
646
    }
647

    
648
///////////////////////////////////////////////////////////////////////////////////////////////////
649
/**
650
 * @param convexity If set to the default (1.0f) then interpolation between 4 points
651
 *                  (1,0) (0,1) (-1,0) (0,-1) will be the natural circle centered at (0,0) with radius 1.
652
 *                  The less it is, the less convex the circle becomes, ultimately when convexity=0.0f
653
 *                  then the interpolation shape will be straight lines connecting the four points.
654
 *                  Further setting this to negative values will make the shape concave.
655
 *                  Valid values: all floats. (although probably only something around (0,2) actually
656
 *                  makes sense)
657
 */
658
  public void setConvexity(float convexity)
659
    {
660
    if( mConvexity!=convexity )
661
      {
662
      mConvexity = convexity;
663
      cacheDirty = true;
664
      }
665
    }
666

    
667
///////////////////////////////////////////////////////////////////////////////////////////////////
668
/**
669
 * @return See {@link Dynamic#setConvexity(float)}
670
 */
671
  public float getConvexity()
672
    {
673
    return mConvexity;
674
    }
675

    
676
///////////////////////////////////////////////////////////////////////////////////////////////////
677
/**
678
 * Sets the access type this Dynamic will be working in.
679
 *
680
 * @param type {@link Dynamic#ACCESS_TYPE_RANDOM} or {@link Dynamic#ACCESS_TYPE_SEQUENTIAL}.
681
 */
682
  public void setAccessType(int type)
683
    {
684
    mAccessType = type;
685
    mLastPos = -1;
686
    }
687

    
688
///////////////////////////////////////////////////////////////////////////////////////////////////
689
/**
690
 * Return the Dimension, ie number of floats in a single Point this Dynamic interpolates through.
691
 *
692
 * @return number of floats in a single Point (ie its dimension) contained in the Dynamic.
693
 */
694
  public int getDimension()
695
    {
696
    return mDimension;
697
    }
698

    
699
///////////////////////////////////////////////////////////////////////////////////////////////////
700
/**
701
 * Writes the results of interpolation between the Points at time 'time' to the passed float buffer.
702
 * <p>
703
 * This version differs from the previous in that it returns a boolean value which indicates whether
704
 * the interpolation is finished.
705
 *
706
 * @param buffer Float buffer we will write the results to.
707
 * @param offset Offset in the buffer where to write the result.
708
 * @param time   Time of interpolation. Time=0.0 is the beginning of the first revolution, time=1.0 - the end
709
 *               of the first revolution, time=2.5 - the middle of the third revolution.
710
 *               What constitutes 'one revolution' depends on the MODE:
711
 *               {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
712
 * @param step   Time difference between now and the last time we called this function. Needed to figure
713
 *               out if the previous time we were called the effect wasn't finished yet, but now it is.
714
 * @return true if the interpolation reached its end.
715
 */
716
  public boolean get(float[] buffer, int offset, long time, long step)
717
    {
718
    if( mDuration<=0.0f )
719
      {
720
      interpolate(buffer,offset,mCount-(int)mCount);
721
      return false;
722
      }
723

    
724
    if( mStartTime==-1 )
725
      {
726
      mStartTime = time;
727
      mLastPos   = -1;
728
      }
729

    
730
    long diff = time-mPausedTime;
731

    
732
    if( mStartTime<mPausedTime && mCorrectedTime<mPausedTime && diff>=0 && diff<=step )
733
      {
734
      mCorrectedTime = mPausedTime;
735
      mStartTime += diff;
736
      step -= diff;
737
      }
738

    
739
    time -= mStartTime;
740

    
741
    if( time+step > mDuration*mCount && mCount>0.0f )
742
      {
743
      interpolate(buffer,offset,mCount-(int)mCount);
744
      return true;
745
      }
746

    
747
    double pos;
748

    
749
    if( mAccessType ==ACCESS_TYPE_SEQUENTIAL )
750
      {
751
      pos = mLastPos<0 ? (double)time/mDuration : (double)step/mDuration + mLastPos;
752
      mLastPos = pos;
753
      }
754
    else
755
      {
756
      pos = (double)time/mDuration;
757
      }
758

    
759
    interpolate(buffer,offset, (float)(pos-(int)pos) );
760
    return false;
761
    }
762

    
763
///////////////////////////////////////////////////////////////////////////////////////////////////
764

    
765
  public void doWork()
766
    {
767
    int num = mJobs.size();
768
    Job job;
769

    
770
    for(int i=0; i<num; i++)
771
      {
772
      job = mJobs.remove(0);
773

    
774
      if (job.type == JOB_RESET )
775
        {
776
        resetToBeginningNow();
777
        }
778
      }
779
    }
780

    
781
///////////////////////////////////////////////////////////////////////////////////////////////////
782
  }
(6-6/18)