Project

General

Profile

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

library / src / main / java / org / distorted / library / type / Dynamic.java @ 8c57d77b

1
////////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski  leszek@koltunski.pl                                          //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// This library is free software; you can redistribute it and/or                                 //
7
// modify it under the terms of the GNU Lesser General Public                                    //
8
// License as published by the Free Software Foundation; either                                  //
9
// version 2.1 of the License, or (at your option) any later version.                            //
10
//                                                                                               //
11
// This library 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 GNU                             //
14
// Lesser General Public License for more details.                                               //
15
//                                                                                               //
16
// You should have received a copy of the GNU Lesser General Public                              //
17
// License along with this library; if not, write to the Free Software                           //
18
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA                //
19
///////////////////////////////////////////////////////////////////////////////////////////////////
20

    
21
package org.distorted.library.type;
22

    
23
import org.distorted.library.main.DistortedLibrary;
24

    
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
60
  {
61
  /**
62
   * Keep the speed of interpolation always changing. Time to cover one segment (distance between
63
   * two consecutive points) always the same. Smoothly interpolate the speed between two segments.
64
   */
65
  public static final int SPEED_MODE_SMOOTH            = 0;
66
  /**
67
   * Make each segment have constant speed. Time to cover each segment is still the same, thus the
68
   * speed will jump when passing through a point and then keep constant.
69
   */
70
  public static final int SPEED_MODE_SEGMENT_CONSTANT  = 1;
71
  /**
72
   * Have the speed be always, globally the same across all segments. Time to cover one segment will
73
   * thus generally no longer be the same.
74
   */
75
  public static final int SPEED_MODE_GLOBALLY_CONSTANT = 2;  // TODO: not supported yet
76

    
77
  /**
78
   * One revolution takes us from the first point to the last and back to first through the shortest path.
79
   */
80
  public static final int MODE_LOOP = 0; 
81
  /**
82
   * One revolution takes us from the first point to the last and back to first through the same path.
83
   */
84
  public static final int MODE_PATH = 1; 
85
  /**
86
   * One revolution takes us from the first point to the last and jumps straight back to the first point.
87
   */
88
  public static final int MODE_JUMP = 2; 
89

    
90
  /**
91
   * The default mode of access. When in this mode, we are able to call interpolate() with points in time
92
   * in any random order. This means one single Dynamic can be used in many effects simultaneously.
93
   * On the other hand, when in this mode, it is not possible to smoothly interpolate when mDuration suddenly
94
   * changes.
95
   */
96
  public static final int ACCESS_TYPE_RANDOM     = 0;
97
  /**
98
   * Set the mode to ACCESS_SEQUENTIAL if you need to change mDuration and you would rather have the Dynamic
99
   * keep on smoothly interpolating.
100
   * On the other hand, in this mode, a Dynamic can only be accessed in sequential manner, which means one
101
   * Dynamic can only be used in one effect at a time.
102
   */
103
  public static final int ACCESS_TYPE_SEQUENTIAL = 1;
104

    
105
  protected int mDimension;
106
  protected int numPoints;
107
  protected int mSegment;       // between which pair of points are we currently? (in case of PATH this is a bit complicated!)
108
  protected boolean cacheDirty; // VectorCache not up to date
109
  protected int mMode;          // LOOP, PATH or JUMP
110
  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
111
  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. 
112
  protected double mLastPos;
113
  protected int mAccessType;
114
  protected int mSpeedMode;
115
  protected float mTmpTime;
116
  protected int mTmpVec, mTmpSeg;
117

    
118
  protected class VectorNoise
119
    {
120
    float[][] n;
121

    
122
    VectorNoise()
123
      {
124
      n = new float[mDimension][NUM_NOISE];
125
      }
126

    
127
    void computeNoise()
128
      {
129
      n[0][0] = mRnd.nextFloat();
130
      for(int i=1; i<NUM_NOISE; i++) n[0][i] = n[0][i-1]+mRnd.nextFloat();
131

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

    
134
      for(int i=0; i<NUM_NOISE; i++)
135
        {
136
        n[0][i] /=sum;
137
        for(int j=1; j<mDimension; j++) n[j][i] = mRnd.nextFloat()-0.5f;
138
        }
139
      }
140
    }
141

    
142
  protected Vector<VectorNoise> vn;
143
  protected float[] mFactor;
144
  protected float[] mNoise;
145
  protected float[][] baseV;
146

    
147
  ///////////////////////////////////////////////////////////////////////////////////////////////////
148
  // the coefficients of the X(t), Y(t) and Z(t) polynomials: X(t) = a[0]*T^3 + b[0]*T^2 + c[0]*t + d[0]  etc.
149
  // (velocity) is the velocity vector.
150
  // (cached) is the original vector from vv (copied here so when interpolating we can see if it is
151
  // still valid and if not - rebuild the Cache
152

    
153
  protected class VectorCache
154
    {
155
    float[] a;
156
    float[] b;
157
    float[] c;
158
    float[] d;
159
    float[] velocity;
160
    float[] cached;
161
    float[] path_ratio;
162

    
163
    VectorCache()
164
      {
165
      a = new float[mDimension];
166
      b = new float[mDimension];
167
      c = new float[mDimension];
168
      d = new float[mDimension];
169

    
170
      velocity   = new float[mDimension];
171
      cached     = new float[mDimension];
172
      path_ratio = new float[NUM_RATIO];
173
      }
174
    }
175

    
176
  protected Vector<VectorCache> vc;
177
  protected VectorCache tmpCache1, tmpCache2;
178
  protected float mConvexity;
179

    
180
  private static final int NUM_RATIO = 10; // we attempt to 'smooth out' the speed in each segment -
181
                                           // remember this many 'points' inside the Cache for each segment.
182

    
183
  protected static final float[] mTmpRatio = new float[NUM_RATIO];
184

    
185
  private float[] buf;
186
  private float[] old;
187
  private static final Random mRnd = new Random();
188
  private static final int NUM_NOISE = 5; // used iff mNoise>0.0. Number of intermediary points between each pair of adjacent vectors
189
                                          // where we randomize noise factors to make the way between the two vectors not so smooth.
190
  private long mStartTime;
191
  private long mCorrectedTime;
192
  private static long mPausedTime;
193

    
194
///////////////////////////////////////////////////////////////////////////////////////////////////
195
// hide this from Javadoc
196
  
197
  protected Dynamic()
198
    {
199

    
200
    }
201

    
202
///////////////////////////////////////////////////////////////////////////////////////////////////
203

    
204
  protected Dynamic(int duration, float count, int dimension)
205
    {
206
    vc         = new Vector<>();
207
    vn         = null;
208
    numPoints  = 0;
209
    cacheDirty = false;
210
    mMode      = MODE_LOOP;
211
    mDuration  = duration;
212
    mCount     = count;
213
    mDimension = dimension;
214
    mSegment   = -1;
215
    mLastPos   = -1;
216
    mAccessType= ACCESS_TYPE_RANDOM;
217
    mSpeedMode = SPEED_MODE_SMOOTH;
218
    mConvexity = 1.0f;
219
    mStartTime = -1;
220
    mCorrectedTime = 0;
221

    
222
    baseV      = new float[mDimension][mDimension];
223
    buf        = new float[mDimension];
224
    old        = new float[mDimension];
225
    }
226

    
227
///////////////////////////////////////////////////////////////////////////////////////////////////
228

    
229
  void initDynamic()
230
    {
231
    mStartTime = -1;
232
    mCorrectedTime = 0;
233
    }
234

    
235
///////////////////////////////////////////////////////////////////////////////////////////////////
236

    
237
  public static void onPause()
238
    {
239
    mPausedTime = System.currentTimeMillis();
240
    }
241

    
242
///////////////////////////////////////////////////////////////////////////////////////////////////
243

    
244
  protected void computeSegmentAndTime(float time)
245
    {
246
    switch(mMode)
247
      {
248
      case MODE_LOOP: mTmpTime= time*numPoints;
249
                      mTmpSeg = (int)mTmpTime;
250
                      mTmpVec = mTmpSeg;
251
                      break;
252
      case MODE_PATH: mTmpSeg = (int)(2*time*(numPoints-1));
253

    
254
                      if( time<=0.5f )  // this has to be <= (otherwise when effect ends at t=0.5, then time=1.0
255
                        {               // and end position is slightly not equal to the end point => might not get autodeleted!
256
                        mTmpTime = 2*time*(numPoints-1);
257
                        mTmpVec = mTmpSeg;
258
                        }
259
                      else
260
                        {
261
                        mTmpTime = 2*(1-time)*(numPoints-1);
262
                        mTmpVec  = 2*numPoints-3-mTmpSeg;
263
                        }
264
                      break;
265
      case MODE_JUMP: mTmpTime= time*(numPoints-1);
266
                      mTmpSeg = (int)mTmpTime;
267
                      mTmpVec = mTmpSeg;
268
                      break;
269
      default       : mTmpVec = 0;
270
                      mTmpSeg = 0;
271
      }
272
    }
273

    
274
///////////////////////////////////////////////////////////////////////////////////////////////////
275

    
276
  private float valueAtPoint(float t, VectorCache cache)
277
    {
278
    float tmp,sum = 0.0f;
279

    
280
    for(int d=0; d<mDimension; d++)
281
      {
282
      tmp = (3*cache.a[d]*t + 2*cache.b[d])*t + cache.c[d];
283
      sum += tmp*tmp;
284
      }
285

    
286
    return (float)Math.sqrt(sum);
287
    }
288

    
289
///////////////////////////////////////////////////////////////////////////////////////////////////
290

    
291
  protected float smoothSpeed(float time, VectorCache cache)
292
    {
293
    float fndex = time*NUM_RATIO;
294
    int index = (int)fndex;
295
    float prev = index==0 ? 0.0f : cache.path_ratio[index-1];
296
    float next = cache.path_ratio[index];
297

    
298
    return prev + (next-prev)*(fndex-index);
299
    }
300

    
301
///////////////////////////////////////////////////////////////////////////////////////////////////
302
// First, compute the approx length of the segment from time=0 to time=(i+1)/NUM_TIME and store this
303
// in cache.path_ratio[i]. Then the last path_ratio is the length from 0 to 1, i.e. the total length
304
// of the segment.
305
// We do this by computing the integral from 0 to 1 of sqrt( (dx/dt)^2 + (dy/dt)^2 ) (i.e. the length
306
// of the segment) using the approx 'trapezoids' integration method.
307
//
308
// Then, for every i, divide path_ratio[i] by the total length to get the percentage of total path
309
// length covered at time i. At this time, path_ratio[3] = 0.45 means 'at time 3/NUM_RATIO, we cover
310
// 0.45 = 45% of the total length of the segment.
311
//
312
// Finally, invert this function (for quicker lookups in smoothSpeed) so that after this step,
313
// path_ratio[3] = 0.45 means 'at 45% of the time, we cover 3/NUM_RATIO distance'.
314

    
315
  protected void smoothOutSegment(VectorCache cache)
316
    {
317
    float vPrev, sum = 0.0f;
318
    float vNext = valueAtPoint(0.0f,cache);
319

    
320
    for(int i=0; i<NUM_RATIO; i++)
321
      {
322
      vPrev = vNext;
323
      vNext = valueAtPoint( (float)(i+1)/NUM_RATIO,cache);
324
      sum += (vPrev+vNext);
325
      cache.path_ratio[i] = sum;
326
      }
327

    
328
    float total = cache.path_ratio[NUM_RATIO-1];
329

    
330
    for(int i=0; i<NUM_RATIO; i++) cache.path_ratio[i] /= total;
331

    
332
    int writeIndex = 0;
333
    float prev=0.0f, next, ratio= 1.0f/NUM_RATIO;
334

    
335
    for(int readIndex=0; readIndex<NUM_RATIO; readIndex++)
336
      {
337
      next = cache.path_ratio[readIndex];
338

    
339
      while( prev<ratio && ratio<=next )
340
        {
341
        float a = (next-ratio)/(next-prev);
342
        mTmpRatio[writeIndex] = (readIndex+1-a)/NUM_RATIO;
343
        writeIndex++;
344
        ratio = (writeIndex+1.0f)/NUM_RATIO;
345
        }
346

    
347
      prev = next;
348
      }
349

    
350
    System.arraycopy(mTmpRatio, 0, cache.path_ratio, 0, NUM_RATIO);
351
    }
352

    
353
///////////////////////////////////////////////////////////////////////////////////////////////////
354

    
355
  protected float noise(float time,int vecNum)
356
    {
357
    float lower, upper, len;
358
    float d = time*(NUM_NOISE+1);
359
    int index = (int)d;
360
    if( index>=NUM_NOISE+1 ) index=NUM_NOISE;
361
    VectorNoise tmpN = vn.elementAt(vecNum);
362

    
363
    float t = d-index;
364
    t = t*t*(3-2*t);
365

    
366
    switch(index)
367
      {
368
      case 0        : for(int i=0;i<mDimension-1;i++) mFactor[i] = mNoise[i+1]*tmpN.n[i+1][0]*t;
369
                      return time + mNoise[0]*(d*tmpN.n[0][0]-time);
370
      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);
371
                      len = ((float)NUM_NOISE)/(NUM_NOISE+1);
372
                      lower = len + mNoise[0]*(tmpN.n[0][NUM_NOISE-1]-len);
373
                      return (1.0f-lower)*(d-NUM_NOISE) + lower;
374
      default       : float ya,yb;
375

    
376
                      for(int i=0;i<mDimension-1;i++)
377
                        {
378
                        yb = tmpN.n[i+1][index  ];
379
                        ya = tmpN.n[i+1][index-1];
380
                        mFactor[i] = mNoise[i+1]*((yb-ya)*t+ya);
381
                        }
382

    
383
                      len = ((float)index)/(NUM_NOISE+1);
384
                      lower = len + mNoise[0]*(tmpN.n[0][index-1]-len);
385
                      len = ((float)index+1)/(NUM_NOISE+1);
386
                      upper = len + mNoise[0]*(tmpN.n[0][index  ]-len);
387

    
388
                      return (upper-lower)*(d-index) + lower;
389
      }
390
    }
391

    
392
///////////////////////////////////////////////////////////////////////////////////////////////////
393
// debugging only
394

    
395
  private void printBase(String str)
396
    {
397
    String s;
398
    float t;
399

    
400
    for(int i=0; i<mDimension; i++)
401
      {
402
      s = "";
403

    
404
      for(int j=0; j<mDimension; j++)
405
        {
406
        t = ((int)(1000*baseV[i][j]))/(1000.0f);
407
        s+=(" "+t);
408
        }
409
      DistortedLibrary.logMessage("Dynamic: "+str+" base "+i+" : " + s);
410
      }
411
    }
412

    
413
///////////////////////////////////////////////////////////////////////////////////////////////////
414
// debugging only
415

    
416
  @SuppressWarnings("unused")
417
  private void checkBase()
418
    {
419
    float tmp, cosA;
420
    float[] len= new float[mDimension];
421
    boolean error=false;
422

    
423
    for(int i=0; i<mDimension; i++)
424
      {
425
      len[i] = 0.0f;
426

    
427
      for(int k=0; k<mDimension; k++)
428
        {
429
        len[i] += baseV[i][k]*baseV[i][k];
430
        }
431

    
432
      if( len[i] == 0.0f || len[0]/len[i] < 0.95f || len[0]/len[i]>1.05f )
433
        {
434
        DistortedLibrary.logMessage("Dynamic: length of vector "+i+" : "+Math.sqrt(len[i]));
435
        error = true;
436
        }
437
      }
438

    
439
    for(int i=0; i<mDimension; i++)
440
      for(int j=i+1; j<mDimension; j++)
441
        {
442
        tmp = 0.0f;
443

    
444
        for(int k=0; k<mDimension; k++)
445
          {
446
          tmp += baseV[i][k]*baseV[j][k];
447
          }
448

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

    
451
        if( cosA > 0.05f || cosA < -0.05f )
452
          {
453
          DistortedLibrary.logMessage("Dynamic: cos angle between vectors "+i+" and "+j+" : "+cosA);
454
          error = true;
455
          }
456
        }
457

    
458
    if( error ) printBase("");
459
    }
460

    
461
///////////////////////////////////////////////////////////////////////////////////////////////////
462

    
463
  int getNext(int curr, float time)
464
    {
465
    switch(mMode)
466
      {
467
      case MODE_LOOP: return curr==numPoints-1 ? 0:curr+1;
468
      case MODE_PATH: return time<0.5f ? (curr+1) : (curr==0 ? 1 : curr-1);
469
      case MODE_JUMP: return curr==numPoints-1 ? 1:curr+1;
470
      default       : return 0;
471
      }
472
    }
473

    
474
///////////////////////////////////////////////////////////////////////////////////////////////////
475

    
476
  private void checkAngle(int index)
477
    {
478
    float cosA = 0.0f;
479

    
480
    for(int k=0;k<mDimension; k++)
481
      cosA += baseV[index][k]*old[k];
482

    
483
    if( cosA<0.0f )
484
      {
485
      for(int j=0; j<mDimension; j++)
486
        baseV[index][j] = -baseV[index][j];
487
      }
488
    }
489

    
490
///////////////////////////////////////////////////////////////////////////////////////////////////
491
// helper function in case we are interpolating through exactly 2 points
492

    
493
  protected void computeOrthonormalBase2(Static curr, Static next)
494
    {
495
    switch(mDimension)
496
      {
497
      case 1: Static1D curr1 = (Static1D)curr;
498
              Static1D next1 = (Static1D)next;
499
              baseV[0][0] = (next1.x-curr1.x);
500
              break;
501
      case 2: Static2D curr2 = (Static2D)curr;
502
              Static2D next2 = (Static2D)next;
503
              baseV[0][0] = (next2.x-curr2.x);
504
              baseV[0][1] = (next2.y-curr2.y);
505
              break;
506
      case 3: Static3D curr3 = (Static3D)curr;
507
              Static3D next3 = (Static3D)next;
508
              baseV[0][0] = (next3.x-curr3.x);
509
              baseV[0][1] = (next3.y-curr3.y);
510
              baseV[0][2] = (next3.z-curr3.z);
511
              break;
512
      case 4: Static4D curr4 = (Static4D)curr;
513
              Static4D next4 = (Static4D)next;
514
              baseV[0][0] = (next4.x-curr4.x);
515
              baseV[0][1] = (next4.y-curr4.y);
516
              baseV[0][2] = (next4.z-curr4.z);
517
              baseV[0][3] = (next4.w-curr4.w);
518
              break;
519
      case 5: Static5D curr5 = (Static5D)curr;
520
              Static5D next5 = (Static5D)next;
521
              baseV[0][0] = (next5.x-curr5.x);
522
              baseV[0][1] = (next5.y-curr5.y);
523
              baseV[0][2] = (next5.z-curr5.z);
524
              baseV[0][3] = (next5.w-curr5.w);
525
              baseV[0][4] = (next5.v-curr5.v);
526
              break;
527
      default: throw new RuntimeException("Unsupported dimension");
528
      }
529

    
530
    if( baseV[0][0] == 0.0f )
531
      {
532
      baseV[1][0] = 1.0f;
533
      baseV[1][1] = 0.0f;
534
      }
535
    else
536
      {
537
      baseV[1][0] = 0.0f;
538
      baseV[1][1] = 1.0f;
539
      }
540

    
541
    for(int i=2; i<mDimension; i++)
542
      {
543
      baseV[1][i] = 0.0f;
544
      }
545

    
546
    computeOrthonormalBase();
547
    }
548

    
549
///////////////////////////////////////////////////////////////////////////////////////////////////
550
// helper function in case we are interpolating through more than 2 points
551

    
552
  protected void computeOrthonormalBaseMore(float time,VectorCache vc)
553
    {
554
    for(int i=0; i<mDimension; i++)
555
      {
556
      baseV[0][i] = (3*vc.a[i]*time+2*vc.b[i])*time+vc.c[i];   // first derivative, i.e. velocity vector
557
      old[i]      = baseV[1][i];
558
      baseV[1][i] =  6*vc.a[i]*time+2*vc.b[i];                 // second derivative,i.e. acceleration vector
559
      }
560

    
561
    computeOrthonormalBase();
562
    }
563

    
564
///////////////////////////////////////////////////////////////////////////////////////////////////
565
// When this function gets called, baseV[0] and baseV[1] should have been filled with two mDimension-al
566
// vectors. This function then fills the rest of the baseV array with a mDimension-al Orthonormal base.
567
// (mDimension-2 vectors, pairwise orthogonal to each other and to the original 2). The function always
568
// leaves base[0] alone but generally speaking must adjust base[1] to make it orthogonal to base[0]!
569
// The whole baseV is then used to compute Noise.
570
//
571
// When computing noise of a point travelling along a N-dimensional path, there are three cases:
572
// a) we may be interpolating through 1 point, i.e. standing in place - nothing to do in this case
573
// b) we may be interpolating through 2 points, i.e. travelling along a straight line between them -
574
//    then pass the velocity vector in baseV[0] and anything linearly independent in base[1].
575
//    The output will then be discontinuous in dimensions>2 (sad corollary from the Hairy Ball Theorem)
576
//    but we don't care - we are travelling along a straight line, so velocity (aka baseV[0]!) does
577
//    not change.
578
// c) we may be interpolating through more than 2 points. Then interpolation formulas ensure the path
579
//    will never be a straight line, even locally -> we can pass in baseV[0] and baseV[1] the velocity
580
//    and the acceleration (first and second derivatives of the path) which are then guaranteed to be
581
//    linearly independent. Then we can ensure this is continuous in dimensions <=4. This leaves
582
//    dimension 5 (ATM WAVE is 5-dimensional) discontinuous -> WAVE will suffer from chaotic noise.
583
//
584
// Bear in mind here the 'normal' in 'orthonormal' means 'length equal to the length of the original
585
// velocity vector' (rather than the standard 1)
586

    
587
  protected void computeOrthonormalBase()
588
    {
589
    int last_non_zero=-1;
590
    float tmp;
591

    
592
    for(int i=0; i<mDimension; i++)
593
      if( baseV[0][i] != 0.0f )
594
        last_non_zero=i;
595

    
596
    if( last_non_zero==-1 )                                               ///
597
      {                                                                   //  velocity is the 0 vector -> two
598
      for(int i=0; i<mDimension-1; i++)                                   //  consecutive points we are interpolating
599
        for(int j=0; j<mDimension; j++)                                   //  through are identical -> no noise,
600
          baseV[i+1][j]= 0.0f;                                            //  set the base to 0 vectors.
601
      }                                                                   ///
602
    else
603
      {
604
      for(int i=1; i<mDimension; i++)                                     /// One iteration computes baseV[i][*]
605
        {                                                                 //  (aka b[i]), the i-th orthonormal vector.
606
        buf[i-1]=0.0f;                                                    //
607
                                                                          //  We can use (modified!) Gram-Schmidt.
608
        for(int k=0; k<mDimension; k++)                                   //
609
          {                                                               //
610
          if( i>=2 )                                                      //  b[0] = b[0]
611
            {                                                             //  b[1] = b[1] - (<b[1],b[0]>/<b[0],b[0]>)*b[0]
612
            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]
613
            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]
614
            }                                                             //  (...)
615
                                                                          //  then b[i] = b[i] / |b[i]|  ( Here really b[i] = b[i] / (|b[0]|/|b[i]|)
616
          tmp = baseV[i-1][k];                                            //
617
          buf[i-1] += tmp*tmp;                                            //
618
          }                                                               //
619
                                                                          //
620
        for(int j=0; j<i; j++)                                            //
621
          {                                                               //
622
          tmp = 0.0f;                                                     //
623
          for(int k=0;k<mDimension; k++) tmp += baseV[i][k]*baseV[j][k];  //
624
          tmp /= buf[j];                                                  //
625
          for(int k=0;k<mDimension; k++) baseV[i][k] -= tmp*baseV[j][k];  //
626
          }                                                               //
627
                                                                          //
628
        checkAngle(i);                                                    //
629
        }                                                                 /// end compute baseV[i][*]
630

    
631
      buf[mDimension-1]=0.0f;                                             /// Normalize
632
      for(int k=0; k<mDimension; k++)                                     //
633
        {                                                                 //
634
        tmp = baseV[mDimension-1][k];                                     //
635
        buf[mDimension-1] += tmp*tmp;                                     //
636
        }                                                                 //
637
                                                                          //
638
      for(int i=1; i<mDimension; i++)                                     //
639
        {                                                                 //
640
        tmp = (float)Math.sqrt(buf[0]/buf[i]);                            //
641
        for(int k=0;k<mDimension; k++) baseV[i][k] *= tmp;                //
642
        }                                                                 /// End Normalize
643
      }
644
    }
645

    
646
///////////////////////////////////////////////////////////////////////////////////////////////////
647

    
648
  abstract void interpolate(float[] buffer, int offset, float time);
649

    
650
///////////////////////////////////////////////////////////////////////////////////////////////////
651
// PUBLIC API
652
///////////////////////////////////////////////////////////////////////////////////////////////////
653

    
654
/**
655
 * Sets the mode of the interpolation to Loop, Path or Jump.
656
 * <ul>
657
 * <li>Loop is when we go from the first point all the way to the last, and the back to the first through 
658
 * the shortest way.
659
 * <li>Path is when we come back from the last point back to the first the same way we got there.
660
 * <li>Jump is when we go from first to last and then jump straight back to the first.
661
 * </ul>
662
 * 
663
 * @param mode {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
664
 */
665
  public void setMode(int mode)
666
    {
667
    mMode = mode;  
668
    }
669

    
670
///////////////////////////////////////////////////////////////////////////////////////////////////
671
/**
672
 * Returns the number of Points this Dynamic has been fed with.
673
 *   
674
 * @return the number of Points we are currently interpolating through.
675
 */
676
  public synchronized int getNumPoints()
677
    {
678
    return numPoints;  
679
    }
680

    
681
///////////////////////////////////////////////////////////////////////////////////////////////////
682
/**
683
 * Sets how many revolutions we want to do.
684
 * <p>
685
 * Does not have to be an integer. What constitutes 'one revolution' depends on the MODE:
686
 * {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
687
 * Count<=0 means 'go on interpolating indefinitely'.
688
 * 
689
 * @param count the number of times we want to interpolate between our collection of Points.
690
 */
691
  public void setCount(float count)
692
    {
693
    mCount = count;  
694
    }
695

    
696
///////////////////////////////////////////////////////////////////////////////////////////////////
697
/**
698
 * Return the number of revolutions this Dynamic will make.
699
 * What constitutes 'one revolution' depends on the MODE:
700
 * {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
701
 *
702
 * @return the number revolutions this Dynamic will make.
703
 */
704
  public float getCount()
705
    {
706
    return mCount;
707
    }
708

    
709
///////////////////////////////////////////////////////////////////////////////////////////////////
710
/**
711
 * Start running from the beginning again.
712
 *
713
 * If a Dynamic has been used already, and we want to use it again and start interpolating from the
714
 * first Point, first we need to reset it using this method.
715
 */
716
  public void resetToBeginning()
717
    {
718
    mStartTime = -1;
719
    }
720

    
721
///////////////////////////////////////////////////////////////////////////////////////////////////
722
/**
723
 * @param duration Number of milliseconds one revolution will take.
724
 *                 What constitutes 'one revolution' depends on the MODE:
725
 *                 {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
726
 */
727
  public void setDuration(long duration)
728
    {
729
    mDuration = duration;
730
    }
731

    
732
///////////////////////////////////////////////////////////////////////////////////////////////////
733
/**
734
 * @return Number of milliseconds one revolution will take.
735
 */
736
  public long getDuration()
737
    {
738
    return mDuration;
739
    }
740

    
741
///////////////////////////////////////////////////////////////////////////////////////////////////
742
/**
743
 * @param convexity If set to the default (1.0f) then interpolation between 4 points
744
 *                  (1,0) (0,1) (-1,0) (0,-1) will be the natural circle centered at (0,0) with radius 1.
745
 *                  The less it is, the less convex the circle becomes, ultimately when convexity=0.0f
746
 *                  then the interpolation shape will be straight lines connecting the four points.
747
 *                  Further setting this to negative values will make the shape concave.
748
 *                  Valid values: all floats. (although probably only something around (0,2) actually
749
 *                  makes sense)
750
 */
751
  public void setConvexity(float convexity)
752
    {
753
    if( mConvexity!=convexity )
754
      {
755
      mConvexity = convexity;
756
      cacheDirty = true;
757
      }
758
    }
759

    
760
///////////////////////////////////////////////////////////////////////////////////////////////////
761
/**
762
 * @return See {@link Dynamic#setConvexity(float)}
763
 */
764
  public float getConvexity()
765
    {
766
    return mConvexity;
767
    }
768

    
769
///////////////////////////////////////////////////////////////////////////////////////////////////
770
/**
771
 * Sets the access type this Dynamic will be working in.
772
 *
773
 * @param type {@link Dynamic#ACCESS_TYPE_RANDOM} or {@link Dynamic#ACCESS_TYPE_SEQUENTIAL}.
774
 */
775
  public void setAccessType(int type)
776
    {
777
    mAccessType = type;
778
    mLastPos = -1;
779
    }
780

    
781
///////////////////////////////////////////////////////////////////////////////////////////////////
782
/**
783
 * @return See {@link Dynamic#setSpeedMode(int)}
784
 */
785
  public float getSpeedMode()
786
    {
787
    return mSpeedMode;
788
    }
789

    
790
///////////////////////////////////////////////////////////////////////////////////////////////////
791
/**
792
 * Sets the way we compute the interpolation speed.
793
 *
794
 * @param mode {@link Dynamic#SPEED_MODE_SMOOTH} or {@link Dynamic#SPEED_MODE_SEGMENT_CONSTANT} or
795
 *             {@link Dynamic#SPEED_MODE_GLOBALLY_CONSTANT}
796
 */
797
  public void setSpeedMode(int mode)
798
    {
799
    if( mSpeedMode!=mode )
800
      {
801
      if( mSpeedMode==SPEED_MODE_SMOOTH )
802
        {
803
        for(int i=0; i<numPoints; i++)
804
          {
805
          tmpCache1 = vc.elementAt(i);
806
          smoothOutSegment(tmpCache1);
807
          }
808
        }
809

    
810
      mSpeedMode = mode;
811
      }
812
    }
813

    
814
///////////////////////////////////////////////////////////////////////////////////////////////////
815
/**
816
 * Return the Dimension, ie number of floats in a single Point this Dynamic interpolates through.
817
 *
818
 * @return number of floats in a single Point (ie its dimension) contained in the Dynamic.
819
 */
820
  public int getDimension()
821
    {
822
    return mDimension;
823
    }
824

    
825
///////////////////////////////////////////////////////////////////////////////////////////////////
826
/**
827
 * Writes the results of interpolation between the Points at time 'time' to the passed float buffer.
828
 * <p>
829
 * This version differs from the previous in that it returns a boolean value which indicates whether
830
 * the interpolation is finished.
831
 *
832
 * @param buffer Float buffer we will write the results to.
833
 * @param offset Offset in the buffer where to write the result.
834
 * @param time   Time of interpolation. Time=0.0 is the beginning of the first revolution, time=1.0 - the end
835
 *               of the first revolution, time=2.5 - the middle of the third revolution.
836
 *               What constitutes 'one revolution' depends on the MODE:
837
 *               {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
838
 * @param step   Time difference between now and the last time we called this function. Needed to figure
839
 *               out if the previous time we were called the effect wasn't finished yet, but now it is.
840
 * @return true if the interpolation reached its end.
841
 */
842
  public boolean get(float[] buffer, int offset, long time, long step)
843
    {
844
    if( mDuration<=0.0f )
845
      {
846
      interpolate(buffer,offset,mCount-(int)mCount);
847
      return false;
848
      }
849

    
850
    if( mStartTime==-1 )
851
      {
852
      mStartTime = time;
853
      mLastPos   = -1;
854
      }
855

    
856
    long diff = time-mPausedTime;
857

    
858
    if( mStartTime<mPausedTime && mCorrectedTime<mPausedTime && diff>=0 && diff<=step )
859
      {
860
      mCorrectedTime = mPausedTime;
861
      mStartTime += diff;
862
      step -= diff;
863
      }
864

    
865
    time -= mStartTime;
866

    
867
    if( time+step > mDuration*mCount && mCount>0.0f )
868
      {
869
      interpolate(buffer,offset,mCount-(int)mCount);
870
      return true;
871
      }
872

    
873
    double pos;
874

    
875
    if( mAccessType ==ACCESS_TYPE_SEQUENTIAL )
876
      {
877
      pos = mLastPos<0 ? (double)time/mDuration : (double)step/mDuration + mLastPos;
878
      mLastPos = pos;
879
      }
880
    else
881
      {
882
      pos = (double)time/mDuration;
883
      }
884

    
885
    interpolate(buffer,offset, (float)(pos-(int)pos) );
886
    return false;
887
    }
888
  }
(6-6/18)