Project

General

Profile

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

library / src / main / java / org / distorted / library / type / Dynamic.java @ c0255951

1 2c8310b1 Leszek Koltunski
////////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski  leszek@koltunski.pl                                          //
3 e0a16874 Leszek Koltunski
//                                                                                               //
4 46b572b5 Leszek Koltunski
// This file is part of Distorted.                                                               //
5 e0a16874 Leszek Koltunski
//                                                                                               //
6 2c8310b1 Leszek Koltunski
// 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 e0a16874 Leszek Koltunski
//                                                                                               //
11 2c8310b1 Leszek Koltunski
// This library is distributed in the hope that it will be useful,                               //
12 e0a16874 Leszek Koltunski
// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
13 2c8310b1 Leszek Koltunski
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU                             //
14
// Lesser General Public License for more details.                                               //
15 e0a16874 Leszek Koltunski
//                                                                                               //
16 2c8310b1 Leszek Koltunski
// 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 e0a16874 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
20
21 a4835695 Leszek Koltunski
package org.distorted.library.type;
22 6a06a912 Leszek Koltunski
23 8c57d77b Leszek Koltunski
import org.distorted.library.main.DistortedLibrary;
24
25 6a06a912 Leszek Koltunski
import java.util.Random;
26 3002bef3 Leszek Koltunski
import java.util.Vector;
27 6a06a912 Leszek Koltunski
28
///////////////////////////////////////////////////////////////////////////////////////////////////
29 ea16dc89 Leszek Koltunski
/** A class to interpolate between a list of Statics.
30 6a06a912 Leszek Koltunski
* <p><ul>
31 c45c2ab1 Leszek Koltunski
* <li>if there is only one Point, just return it.
32 6a06a912 Leszek Koltunski
* <li>if there are two Points, linearly bounce between them
33 c45c2ab1 Leszek Koltunski
* <li>if there are more, interpolate a path between them. Exact way we interpolate depends on the MODE.
34 6a06a912 Leszek Koltunski
* </ul>
35
*/
36
37
// The way Interpolation between more than 2 Points is done:
38
// 
39 f871c455 Leszek Koltunski
// 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 6a06a912 Leszek Koltunski
//
42 f871c455 Leszek Koltunski
// 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 6a06a912 Leszek Koltunski
//
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 f871c455 Leszek Koltunski
// 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 6a06a912 Leszek Koltunski
//
51
// we have the solution:  X(t) = at^3 + bt^2 + ct + d where
52 f871c455 Leszek Koltunski
// 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 6a06a912 Leszek Koltunski
//
57
// and similarly Y(t) and Z(t).
58
59 24b1f190 Leszek Koltunski
public abstract class Dynamic
60 6a06a912 Leszek Koltunski
  {
61 9aabc9eb Leszek Koltunski
  /**
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 d403b466 Leszek Koltunski
  public static final int SPEED_MODE_GLOBALLY_CONSTANT = 2;  // TODO: not supported yet
76 9aabc9eb Leszek Koltunski
77 6a06a912 Leszek Koltunski
  /**
78 c45c2ab1 Leszek Koltunski
   * One revolution takes us from the first point to the last and back to first through the shortest path.
79 6a06a912 Leszek Koltunski
   */
80
  public static final int MODE_LOOP = 0; 
81
  /**
82 c45c2ab1 Leszek Koltunski
   * One revolution takes us from the first point to the last and back to first through the same path.
83 6a06a912 Leszek Koltunski
   */
84
  public static final int MODE_PATH = 1; 
85
  /**
86 c45c2ab1 Leszek Koltunski
   * One revolution takes us from the first point to the last and jumps straight back to the first point.
87 6a06a912 Leszek Koltunski
   */
88
  public static final int MODE_JUMP = 2; 
89 3002bef3 Leszek Koltunski
90 bdb341bc Leszek Koltunski
  /**
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 c45c2ab1 Leszek Koltunski
  public static final int ACCESS_TYPE_RANDOM     = 0;
97 bdb341bc Leszek Koltunski
  /**
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 24d22f93 Leszek Koltunski
   * Dynamic can only be used in one effect at a time.
102 bdb341bc Leszek Koltunski
   */
103 c45c2ab1 Leszek Koltunski
  public static final int ACCESS_TYPE_SEQUENTIAL = 1;
104 bdb341bc Leszek Koltunski
105 310e14fb leszek
  protected int mDimension;
106 6a06a912 Leszek Koltunski
  protected int numPoints;
107 291705f6 Leszek Koltunski
  protected int mSegment;       // between which pair of points are we currently? (in case of PATH this is a bit complicated!)
108 6a06a912 Leszek Koltunski
  protected boolean cacheDirty; // VectorCache not up to date
109
  protected int mMode;          // LOOP, PATH or JUMP
110 8c893ffc Leszek Koltunski
  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 6a06a912 Leszek Koltunski
  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 bdb341bc Leszek Koltunski
  protected double mLastPos;
113 c45c2ab1 Leszek Koltunski
  protected int mAccessType;
114 9aabc9eb Leszek Koltunski
  protected int mSpeedMode;
115 d403b466 Leszek Koltunski
  protected float mTmpTime;
116
  protected int mTmpVec, mTmpSeg;
117 3002bef3 Leszek Koltunski
118
  protected class VectorNoise
119
    {
120
    float[][] n;
121
122 291705f6 Leszek Koltunski
    VectorNoise()
123 3002bef3 Leszek Koltunski
      {
124 291705f6 Leszek Koltunski
      n = new float[mDimension][NUM_NOISE];
125
      }
126 3002bef3 Leszek Koltunski
127 291705f6 Leszek Koltunski
    void computeNoise()
128
      {
129 3002bef3 Leszek Koltunski
      n[0][0] = mRnd.nextFloat();
130
      for(int i=1; i<NUM_NOISE; i++) n[0][i] = n[0][i-1]+mRnd.nextFloat();
131 291705f6 Leszek Koltunski
132 3002bef3 Leszek Koltunski
      float sum = n[0][NUM_NOISE-1] + mRnd.nextFloat();
133
134 291705f6 Leszek Koltunski
      for(int i=0; i<NUM_NOISE; i++)
135 3002bef3 Leszek Koltunski
        {
136 291705f6 Leszek Koltunski
        n[0][i] /=sum;
137
        for(int j=1; j<mDimension; j++) n[j][i] = mRnd.nextFloat()-0.5f;
138 3002bef3 Leszek Koltunski
        }
139
      }
140
    }
141
142
  protected Vector<VectorNoise> vn;
143
  protected float[] mFactor;
144 1e22c248 Leszek Koltunski
  protected float[] mNoise;
145 649544b8 Leszek Koltunski
  protected float[][] baseV;
146
147
  ///////////////////////////////////////////////////////////////////////////////////////////////////
148 9aabc9eb Leszek Koltunski
  // 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 649544b8 Leszek Koltunski
  // (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 9aabc9eb Leszek Koltunski
    float[] velocity;
160 649544b8 Leszek Koltunski
    float[] cached;
161 9aabc9eb Leszek Koltunski
    float[] path_ratio;
162 649544b8 Leszek Koltunski
163 291705f6 Leszek Koltunski
    VectorCache()
164 649544b8 Leszek Koltunski
      {
165 291705f6 Leszek Koltunski
      a = new float[mDimension];
166
      b = new float[mDimension];
167
      c = new float[mDimension];
168
      d = new float[mDimension];
169 9aabc9eb Leszek Koltunski
170
      velocity   = new float[mDimension];
171
      cached     = new float[mDimension];
172
      path_ratio = new float[NUM_RATIO];
173 649544b8 Leszek Koltunski
      }
174
    }
175
176
  protected Vector<VectorCache> vc;
177 9aabc9eb Leszek Koltunski
  protected VectorCache tmpCache1, tmpCache2;
178 12ecac18 Leszek Koltunski
  protected float mConvexity;
179 3002bef3 Leszek Koltunski
180 9aabc9eb Leszek Koltunski
  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 6a2ebb18 Leszek Koltunski
  private float[] buf;
186
  private float[] old;
187 4f9ec5d6 Leszek Koltunski
  private static final Random mRnd = new Random();
188 6a2ebb18 Leszek Koltunski
  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 0273ef2a Leszek Koltunski
  private long mStartTime;
191 246d021c Leszek Koltunski
  private long mCorrectedTime;
192 0273ef2a Leszek Koltunski
  private static long mPausedTime;
193 6a2ebb18 Leszek Koltunski
194 6a06a912 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
195
// hide this from Javadoc
196
  
197 649544b8 Leszek Koltunski
  protected Dynamic()
198 6a06a912 Leszek Koltunski
    {
199 310e14fb leszek
200 6a06a912 Leszek Koltunski
    }
201 8c893ffc Leszek Koltunski
202 649544b8 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
203
204
  protected Dynamic(int duration, float count, int dimension)
205
    {
206 291705f6 Leszek Koltunski
    vc         = new Vector<>();
207
    vn         = null;
208
    numPoints  = 0;
209 649544b8 Leszek Koltunski
    cacheDirty = false;
210 291705f6 Leszek Koltunski
    mMode      = MODE_LOOP;
211
    mDuration  = duration;
212
    mCount     = count;
213 649544b8 Leszek Koltunski
    mDimension = dimension;
214 291705f6 Leszek Koltunski
    mSegment   = -1;
215 bdb341bc Leszek Koltunski
    mLastPos   = -1;
216 12ecac18 Leszek Koltunski
    mAccessType= ACCESS_TYPE_RANDOM;
217 9aabc9eb Leszek Koltunski
    mSpeedMode = SPEED_MODE_SMOOTH;
218 12ecac18 Leszek Koltunski
    mConvexity = 1.0f;
219 78ff6ea9 Leszek Koltunski
    mStartTime = -1;
220 246d021c Leszek Koltunski
    mCorrectedTime = 0;
221 142c7236 Leszek Koltunski
222 291705f6 Leszek Koltunski
    baseV      = new float[mDimension][mDimension];
223
    buf        = new float[mDimension];
224
    old        = new float[mDimension];
225 649544b8 Leszek Koltunski
    }
226
227 3ac42a4c Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
228
229
  void initDynamic()
230
    {
231
    mStartTime = -1;
232
    mCorrectedTime = 0;
233
    }
234
235 0273ef2a Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
236
237
  public static void onPause()
238
    {
239
    mPausedTime = System.currentTimeMillis();
240
    }
241
242 d403b466 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 9aabc9eb Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 3002bef3 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 1e22c248 Leszek Koltunski
      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 3002bef3 Leszek Koltunski
                      len = ((float)NUM_NOISE)/(NUM_NOISE+1);
372 1e22c248 Leszek Koltunski
                      lower = len + mNoise[0]*(tmpN.n[0][NUM_NOISE-1]-len);
373 3002bef3 Leszek Koltunski
                      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 1e22c248 Leszek Koltunski
                        mFactor[i] = mNoise[i+1]*((yb-ya)*t+ya);
381 3002bef3 Leszek Koltunski
                        }
382
383
                      len = ((float)index)/(NUM_NOISE+1);
384 1e22c248 Leszek Koltunski
                      lower = len + mNoise[0]*(tmpN.n[0][index-1]-len);
385 3002bef3 Leszek Koltunski
                      len = ((float)index+1)/(NUM_NOISE+1);
386 1e22c248 Leszek Koltunski
                      upper = len + mNoise[0]*(tmpN.n[0][index  ]-len);
387 3002bef3 Leszek Koltunski
388
                      return (upper-lower)*(d-index) + lower;
389
      }
390
    }
391
392 649544b8 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 8c57d77b Leszek Koltunski
      DistortedLibrary.logMessage("Dynamic: "+str+" base "+i+" : " + s);
410 649544b8 Leszek Koltunski
      }
411
    }
412
413
///////////////////////////////////////////////////////////////////////////////////////////////////
414
// debugging only
415
416 24d22f93 Leszek Koltunski
  @SuppressWarnings("unused")
417 649544b8 Leszek Koltunski
  private void checkBase()
418
    {
419 6a2ebb18 Leszek Koltunski
    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 8c57d77b Leszek Koltunski
        DistortedLibrary.logMessage("Dynamic: length of vector "+i+" : "+Math.sqrt(len[i]));
435 6a2ebb18 Leszek Koltunski
        error = true;
436
        }
437
      }
438 649544b8 Leszek Koltunski
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 6a2ebb18 Leszek Koltunski
        cosA = ( (len[i]==0.0f || len[j]==0.0f) ? 0.0f : tmp/(float)Math.sqrt(len[i]*len[j]));
450 649544b8 Leszek Koltunski
451 6a2ebb18 Leszek Koltunski
        if( cosA > 0.05f || cosA < -0.05f )
452
          {
453 8c57d77b Leszek Koltunski
          DistortedLibrary.logMessage("Dynamic: cos angle between vectors "+i+" and "+j+" : "+cosA);
454 6a2ebb18 Leszek Koltunski
          error = true;
455
          }
456 649544b8 Leszek Koltunski
        }
457
458 6a2ebb18 Leszek Koltunski
    if( error ) printBase("");
459 649544b8 Leszek Koltunski
    }
460
461 9dacabea Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 c6dec65b Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 649544b8 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
491
// helper function in case we are interpolating through exactly 2 points
492
493 a20f274f Leszek Koltunski
  protected void computeOrthonormalBase2(Static curr, Static next)
494 649544b8 Leszek Koltunski
    {
495
    switch(mDimension)
496
      {
497 a20f274f Leszek Koltunski
      case 1: Static1D curr1 = (Static1D)curr;
498
              Static1D next1 = (Static1D)next;
499
              baseV[0][0] = (next1.x-curr1.x);
500 649544b8 Leszek Koltunski
              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 6a2ebb18 Leszek Koltunski
      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 649544b8 Leszek Koltunski
      }
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 6a2ebb18 Leszek Koltunski
    float tmp;
591 649544b8 Leszek Koltunski
592 6a2ebb18 Leszek Koltunski
    for(int i=0; i<mDimension; i++)
593
      if( baseV[0][i] != 0.0f )
594 649544b8 Leszek Koltunski
        last_non_zero=i;
595 6a2ebb18 Leszek Koltunski
596 a36b0cbb Leszek Koltunski
    if( last_non_zero==-1 )                                               ///
597 6a2ebb18 Leszek Koltunski
      {                                                                   //  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 649544b8 Leszek Koltunski
    else
603
      {
604 6a2ebb18 Leszek Koltunski
      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 649544b8 Leszek Koltunski
      }
644 6a06a912 Leszek Koltunski
    }
645 3002bef3 Leszek Koltunski
646 6a06a912 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
647 3002bef3 Leszek Koltunski
648 6a06a912 Leszek Koltunski
  abstract void interpolate(float[] buffer, int offset, float time);
649
650
///////////////////////////////////////////////////////////////////////////////////////////////////
651
// PUBLIC API
652
///////////////////////////////////////////////////////////////////////////////////////////////////
653 8c893ffc Leszek Koltunski
654 6a06a912 Leszek Koltunski
/**
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 c45c2ab1 Leszek Koltunski
 * <li>Jump is when we go from first to last and then jump straight back to the first.
661 6a06a912 Leszek Koltunski
 * </ul>
662
 * 
663 568b29d8 Leszek Koltunski
 * @param mode {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
664 6a06a912 Leszek Koltunski
 */
665
  public void setMode(int mode)
666
    {
667
    mMode = mode;  
668
    }
669
670
///////////////////////////////////////////////////////////////////////////////////////////////////
671
/**
672 c45c2ab1 Leszek Koltunski
 * Returns the number of Points this Dynamic has been fed with.
673 6a06a912 Leszek Koltunski
 *   
674 c45c2ab1 Leszek Koltunski
 * @return the number of Points we are currently interpolating through.
675 6a06a912 Leszek Koltunski
 */
676
  public synchronized int getNumPoints()
677
    {
678
    return numPoints;  
679
    }
680
681
///////////////////////////////////////////////////////////////////////////////////////////////////
682
/**
683 c45c2ab1 Leszek Koltunski
 * Sets how many revolutions we want to do.
684 6a06a912 Leszek Koltunski
 * <p>
685 c45c2ab1 Leszek Koltunski
 * 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 6a06a912 Leszek Koltunski
 * Count<=0 means 'go on interpolating indefinitely'.
688
 * 
689 c45c2ab1 Leszek Koltunski
 * @param count the number of times we want to interpolate between our collection of Points.
690 6a06a912 Leszek Koltunski
 */
691
  public void setCount(float count)
692
    {
693
    mCount = count;  
694
    }
695
696
///////////////////////////////////////////////////////////////////////////////////////////////////
697
/**
698 c45c2ab1 Leszek Koltunski
 * 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 b920c848 Leszek Koltunski
 *
702 c45c2ab1 Leszek Koltunski
 * @return the number revolutions this Dynamic will make.
703 b920c848 Leszek Koltunski
 */
704
  public float getCount()
705
    {
706
    return mCount;
707
    }
708
709
///////////////////////////////////////////////////////////////////////////////////////////////////
710
/**
711
 * Start running from the beginning again.
712 c45c2ab1 Leszek Koltunski
 *
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 6a06a912 Leszek Koltunski
 */
716 b920c848 Leszek Koltunski
  public void resetToBeginning()
717 6a06a912 Leszek Koltunski
    {
718 24b1f190 Leszek Koltunski
    mStartTime = -1;
719 b920c848 Leszek Koltunski
    }
720
721
///////////////////////////////////////////////////////////////////////////////////////////////////
722
/**
723 c45c2ab1 Leszek Koltunski
 * @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 b920c848 Leszek Koltunski
 */
727
  public void setDuration(long duration)
728
    {
729
    mDuration = duration;
730
    }
731
732
///////////////////////////////////////////////////////////////////////////////////////////////////
733
/**
734 c45c2ab1 Leszek Koltunski
 * @return Number of milliseconds one revolution will take.
735 b920c848 Leszek Koltunski
 */
736
  public long getDuration()
737
    {
738
    return mDuration;
739 6a06a912 Leszek Koltunski
    }
740
741 12ecac18 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 bdb341bc Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
770
/**
771 c45c2ab1 Leszek Koltunski
 * Sets the access type this Dynamic will be working in.
772 bdb341bc Leszek Koltunski
 *
773 c45c2ab1 Leszek Koltunski
 * @param type {@link Dynamic#ACCESS_TYPE_RANDOM} or {@link Dynamic#ACCESS_TYPE_SEQUENTIAL}.
774 bdb341bc Leszek Koltunski
 */
775 c45c2ab1 Leszek Koltunski
  public void setAccessType(int type)
776 bdb341bc Leszek Koltunski
    {
777 c45c2ab1 Leszek Koltunski
    mAccessType = type;
778 bdb341bc Leszek Koltunski
    mLastPos = -1;
779
    }
780
781 9aabc9eb Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 6d62a900 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
815
/**
816
 * Return the Dimension, ie number of floats in a single Point this Dynamic interpolates through.
817 c45c2ab1 Leszek Koltunski
 *
818
 * @return number of floats in a single Point (ie its dimension) contained in the Dynamic.
819 6d62a900 Leszek Koltunski
 */
820
  public int getDimension()
821
    {
822
    return mDimension;
823
    }
824
825 bdb341bc Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 24d22f93 Leszek Koltunski
 * @param buffer Float buffer we will write the results to.
833 bdb341bc Leszek Koltunski
 * @param offset Offset in the buffer where to write the result.
834 c45c2ab1 Leszek Koltunski
 * @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 012901f5 Leszek Koltunski
 * @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 bdb341bc Leszek Koltunski
 * @return true if the interpolation reached its end.
841
 */
842 a1d92a36 leszek
  public boolean get(float[] buffer, int offset, long time, long step)
843 bdb341bc Leszek Koltunski
    {
844
    if( mDuration<=0.0f )
845
      {
846
      interpolate(buffer,offset,mCount-(int)mCount);
847
      return false;
848
      }
849 b920c848 Leszek Koltunski
850 78ff6ea9 Leszek Koltunski
    if( mStartTime==-1 )
851 b920c848 Leszek Koltunski
      {
852 0273ef2a Leszek Koltunski
      mStartTime = time;
853 b920c848 Leszek Koltunski
      mLastPos   = -1;
854
      }
855
856 0273ef2a Leszek Koltunski
    long diff = time-mPausedTime;
857
858 246d021c Leszek Koltunski
    if( mStartTime<mPausedTime && mCorrectedTime<mPausedTime && diff>=0 && diff<=step )
859 0273ef2a Leszek Koltunski
      {
860 246d021c Leszek Koltunski
      mCorrectedTime = mPausedTime;
861 0273ef2a Leszek Koltunski
      mStartTime += diff;
862
      step -= diff;
863
      }
864
865
    time -= mStartTime;
866 b920c848 Leszek Koltunski
867 48d0867a leszek
    if( time+step > mDuration*mCount && mCount>0.0f )
868
      {
869
      interpolate(buffer,offset,mCount-(int)mCount);
870
      return true;
871
      }
872 bdb341bc Leszek Koltunski
873
    double pos;
874
875 c45c2ab1 Leszek Koltunski
    if( mAccessType ==ACCESS_TYPE_SEQUENTIAL )
876 bdb341bc Leszek Koltunski
      {
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 48d0867a leszek
    interpolate(buffer,offset, (float)(pos-(int)pos) );
886 bdb341bc Leszek Koltunski
    return false;
887
    }
888 6a06a912 Leszek Koltunski
  }