Project

General

Profile

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

library / src / main / java / org / distorted / library / type / DynamicQuat.java @ 246d021c

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 java.util.Vector;
23

    
24
///////////////////////////////////////////////////////////////////////////////////////////////////
25
/** 
26
* A 4-dimensional implementation of the Dynamic class to interpolate between a list
27
* of Static4Ds.
28
* Here, the Points are assumed to be Quaternions - thus we do the Spherical Linear Interpolation, aka
29
* SLERP. Noise not supported (yet?).
30
*
31
* Only unit quaternions represent valid rotations in 3D - and interpolating through rotations is the
32
* most common use case for this class. No effort is done to normalize the Points though.
33
*
34
* Rotation Quaternion is assumed to be in the form ( axisX*sinT, axisY*sinT, axisZ*sinT, cosT ).
35
*/
36

    
37
public class DynamicQuat extends Dynamic implements Data4D
38
  {
39
 
40
///////////////////////////////////////////////////////////////////////////////////////////////////
41
// Here we implement our own Cache as we need something slightly different.
42
// omega, sinOmega, cosOmega - angle between pair of quaternions, its sinus and cosinus.
43
//  
44
// (vx,vy,vz,vw) is the original vector from vv (copied here so when interpolating we can see if it is 
45
// still valid and if not - rebuild the Cache.
46
  
47
  private class VectorCacheQuat
48
    {
49
    float omega, sinOmega,cosOmega;
50
    float vx,vy,vz,vw;
51
    }
52
  
53
  private Vector<VectorCacheQuat> vc;
54
  private VectorCacheQuat tmp1, tmp2;
55

    
56
  private Vector<Static4D> vv;
57
  private Static4D curr, next;
58
 
59
///////////////////////////////////////////////////////////////////////////////////////////////////
60
// Abramowitz / Stegun
61

    
62
  private static float arcCos(float x)
63
    {
64
    if( x<0 )
65
      return 3.14159265358979f - (float)Math.sqrt(1+x)*(1.5707288f + 0.2121144f*x + 0.074261f*x*x + 0.0187293f*x*x*x);
66
     
67
    return (float)Math.sqrt(1-x)*(1.5707288f - 0.2121144f*x + 0.074261f*x*x - 0.0187293f*x*x*x);
68
    }
69

    
70
///////////////////////////////////////////////////////////////////////////////////////////////////
71

    
72
  private void recomputeCache()
73
    {  
74
    if( numPoints>=2 )
75
      {
76
      int i, n;  
77
      Static4D cu,ne;
78
      VectorCacheQuat vq;
79

    
80
      for(i=0; i<numPoints; i++)
81
        {
82
        n = i<numPoints-1 ? i+1:0;  
83
      
84
        vq= vc.elementAt(i);
85
        cu= vv.elementAt(i);
86
        ne= vv.elementAt(n);
87
      
88
        vq.vx = cu.x;
89
        vq.vy = cu.y;
90
        vq.vz = cu.z;
91
        vq.vw = cu.w;
92
    	
93
        vq.cosOmega = cu.x*ne.x + cu.y*ne.y + cu.z*ne.z + cu.w*ne.w;
94
        vq.sinOmega = (float)Math.sqrt(1-vq.cosOmega*vq.cosOmega);
95
        vq.omega    = arcCos(vq.cosOmega);
96
        }
97
      }
98
   
99
    cacheDirty = false;
100
    }
101

    
102
///////////////////////////////////////////////////////////////////////////////////////////////////
103
// PUBLIC API
104
///////////////////////////////////////////////////////////////////////////////////////////////////
105
/**
106
 * Default constructor.
107
 */
108
  public DynamicQuat()
109
    {
110
    this(0,0.5f);
111
    }
112

    
113
///////////////////////////////////////////////////////////////////////////////////////////////////
114
/**
115
 * Constructor setting the speed of interpolation and the number of revolutions.
116
 *
117
 * What constitutes 'one revolution' depends on the MODE:
118
 * {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
119
 *
120
 * @param duration number of milliseconds it takes to do one revolution.
121
 * @param count    number of revolutions we will do. Count<=0 means 'infinite'.
122
 */
123
  public DynamicQuat(int duration, float count)
124
    {
125
    vv         = new Vector<>();
126
    vc         = new Vector<>();
127
    numPoints  = 0;
128
    cacheDirty = false;
129
    mMode      = MODE_LOOP;
130
    mDuration  = duration;
131
    mCount     = count;
132
    mLastPos   = -1;
133
    mAccessType = ACCESS_TYPE_RANDOM;
134
    mDimension = 4;
135
    }
136

    
137
///////////////////////////////////////////////////////////////////////////////////////////////////
138
/**
139
 * Returns the location'th Static4D.
140
 *   
141
 * @param location the index of the Point we are interested in.
142
 * @return The Static4D, if 0<=location&lt;getNumPoints(), or null otherwise.
143
 */  
144
  public synchronized Static4D getPoint(int location)
145
    {
146
    return (location>=0 && location<numPoints) ? vv.elementAt(location) : null;  
147
    }
148
  
149
///////////////////////////////////////////////////////////////////////////////////////////////////
150
/**
151
 * Resets the location'th Point.
152
 * <p>
153
 * Rotation Quaternion is assumed to be in the form ( axisX*sinT, axisY*sinT, axisZ*sinT, cosT ).
154
 *
155
 * @param location the index of the Point we are setting.
156
 * @param x New value of its first float.
157
 */
158
  public synchronized void setPoint(int location, float x, float y, float z, float w)
159
    {
160
    if( location>=0 && location<numPoints )
161
      {
162
      curr = vv.elementAt(location);
163
   
164
      if( curr!=null )
165
        {
166
        curr.set(x,y,z,w);
167
        cacheDirty=true;
168
        }
169
      }
170
    }
171

    
172
///////////////////////////////////////////////////////////////////////////////////////////////////
173
/**
174
 * Adds a new Static4D to the end of our list of Points to interpolate through.
175
 * <p>   
176
 * Only a reference to the Point gets added to the List; this means that one can add a Point 
177
 * here, and later on {@link Static4D#set(float,float,float,float)} it to some new value and
178
 * the change will be seamlessly reflected in the interpolated path.  
179
 * <p>
180
 * A Point can be added multiple times.
181
 *   
182
 * @param v The Point to add.
183
 */    
184
  public synchronized void add(Static4D v)
185
    {
186
    if( v!=null )
187
      {
188
      vv.add(v);
189
      
190
      switch(numPoints)
191
         {
192
         case 0: 
193
         case 1: vc.add(new VectorCacheQuat());
194
                 vc.add(new VectorCacheQuat());
195
        	     break;
196
         default:vc.add(new VectorCacheQuat());
197
         }
198

    
199
       numPoints++;
200
       cacheDirty = true;
201
       }
202
    }
203

    
204
///////////////////////////////////////////////////////////////////////////////////////////////////
205
/**
206
 * Adds a new Static4D to the location'th place in our List of Points to interpolate through.
207
 *   
208
 * @param location Index in our List to add the new Point at.
209
 * @param v The Static4D to add.
210
 */  
211
  public synchronized void add(int location, Static4D v)
212
    {
213
    if( v!=null )
214
      {
215
      vv.add(location, v);
216
      
217
      switch(numPoints)
218
        {
219
        case 0: 
220
        case 1: vc.add(new VectorCacheQuat());
221
                vc.add(new VectorCacheQuat());
222
                break;
223
        default:vc.add(location,new VectorCacheQuat());
224
        }
225

    
226
      numPoints++;
227
      cacheDirty = true;
228
      }
229
    }
230
  
231
///////////////////////////////////////////////////////////////////////////////////////////////////
232
/**
233
 * Removes all occurrences of Point v from the List of Points to interpolate through.  
234
 * 
235
 * @param v The Point to remove.
236
 * @return <code>true</code> if we have removed at least one Point.
237
 */
238
  public synchronized boolean remove(Static4D v)
239
    {
240
    int n = vv.indexOf(v);
241
    boolean found = false;
242
   
243
    while( n>=0 ) 
244
      {
245
      vv.remove(n);
246
     
247
      switch(numPoints)
248
        {
249
        case 0:
250
        case 1: break;
251
        case 2: vc.removeAllElements();
252
                break;
253
        default:vc.remove(n);
254
        }
255

    
256
      numPoints--;
257
      found = true;
258
      n = vv.indexOf(v);
259
      }
260
   
261
    if( found ) 
262
      {
263
      cacheDirty=true;
264
      }
265
   
266
    return found;
267
    }
268

    
269
///////////////////////////////////////////////////////////////////////////////////////////////////
270
/**
271
 * Removes a location'th Point from the List of Points we interpolate through.
272
 * 
273
 * @param location index of the Point we want to remove. 
274
 * @return <code>true</code> if location is valid, i.e. if 0<=location&lt;getNumPoints().
275
 */
276
  public synchronized boolean remove(int location)
277
    {
278
    if( location>=0 && location<numPoints ) 
279
      {
280
      vv.removeElementAt(location);
281
      
282
      switch(numPoints)
283
        {
284
        case 0: 
285
        case 1: break;
286
        case 2: vc.removeAllElements();
287
                break;
288
        default:vc.removeElementAt(location);
289
        }
290

    
291
      numPoints--;
292
      cacheDirty = true; 
293
      return true;
294
      }
295

    
296
    return false;
297
    }
298
  
299
///////////////////////////////////////////////////////////////////////////////////////////////////
300
/**
301
 * Removes all Points.
302
 */
303
  public synchronized void removeAll()
304
    {
305
    numPoints = 0;
306
    vv.removeAllElements();
307
    vc.removeAllElements();
308
    cacheDirty = false;
309
    }
310
  
311
///////////////////////////////////////////////////////////////////////////////////////////////////
312
/**
313
 * Writes the results of interpolation between the Points at time 'time' to the passed float buffer.
314
 * Interpolation is done using the spherical linear algorithm, aka SLERP.
315
 * <p>
316
 * Since this is a 4-dimensional Dynamic, the resulting interpolated Static4D gets written
317
 * to four locations in the buffer: buffer[offset], buffer[offset+1], buffer[offset+2] and buffer[offset+3]. 
318
 * 
319
 * @param buffer Float buffer we will write the resulting Static4D to.
320
 * @param offset Offset in the buffer where to write the result.
321
 * @param time   Time of interpolation. Time=0.0 is the beginning of the first revolution, time=1.0 - the end
322
 *               of the first revolution, time=2.5 - the middle of the third revolution.
323
 *               What constitutes 'one revolution' depends on the MODE:
324
 *               {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
325
 **/
326
  synchronized void interpolate(float[] buffer, int offset, float time)
327
    {  
328
    switch(numPoints)
329
      {
330
      case 0: buffer[offset  ] = 0.0f;
331
              buffer[offset+1] = 0.0f;
332
              buffer[offset+2] = 0.0f;
333
              buffer[offset+3] = 0.0f;
334
              break;
335
      case 1: curr = vv.elementAt(0);
336
              buffer[offset  ] = curr.x; 
337
              buffer[offset+1] = curr.y;
338
              buffer[offset+2] = curr.z;
339
              buffer[offset+3] = curr.w;
340
              break;
341
      default:float t = time;
342
              int vecCurr, segment;
343
              float scale0, scale1;
344

    
345
              switch(mMode)
346
                {
347
                case MODE_LOOP: time = time*numPoints;
348
                                segment = (int)time;
349
                                vecCurr = segment;
350
                                break;
351
                case MODE_PATH: if( t>0.5f ) t = 1.0f-t;
352
                                time = 2*t*(numPoints-1);
353
                                segment = (int)(2*t*(numPoints-1));
354
                                vecCurr = segment;
355
                                break;
356
                case MODE_JUMP: time = time*(numPoints-1);
357
                                segment = (int)time;
358
                                vecCurr = segment;
359
                                break;
360
                default       : vecCurr = 0;
361
                                segment = 0;
362
                }
363

    
364
              if( vecCurr>=0 && vecCurr<numPoints )
365
                {
366
                int vecNext = getNext(vecCurr,t);
367

    
368
                curr = vv.elementAt(vecCurr);
369
                tmp1 = vc.elementAt(vecCurr);
370
                next = vv.elementAt(vecNext);
371

    
372
                if( cacheDirty ) recomputeCache();  // recompute cache if we have added or remove vectors since last computation
373
                else if( mSegment!= segment )       // ...or if we have just passed a vector and the vector we are currently flying to has changed
374
                  {
375
                  tmp2 = vc.elementAt(vecNext);
376

    
377
                  if( tmp2.vx!=next.x || tmp2.vy!=next.y || tmp2.vz!=next.z || tmp2.vw!=next.w ) recomputeCache();
378
                  }
379

    
380
                mSegment = segment;
381

    
382
                time = time-vecCurr;
383

    
384
                if( tmp1.sinOmega==0 )
385
                  {
386
                  scale0 = 1f;
387
                  scale1 = 0f;
388
                  }
389
                else if( tmp1.cosOmega < 0.99 )
390
                  {
391
                  scale0 = (float)Math.sin( (1f-time)*tmp1.omega ) / tmp1.sinOmega;
392
                  scale1 = (float)Math.sin(     time *tmp1.omega ) / tmp1.sinOmega;
393
                  }
394
                else
395
                  {
396
                  scale0 = 1f-time;
397
                  scale1 = time;
398
                  }
399

    
400
                buffer[offset  ] = scale0*curr.x + scale1*next.x;
401
                buffer[offset+1] = scale0*curr.y + scale1*next.y;
402
                buffer[offset+2] = scale0*curr.z + scale1*next.z;
403
                buffer[offset+3] = scale0*curr.w + scale1*next.w;
404

    
405
                break;
406
                }
407
      }
408
    }  
409

    
410
  }
(12-12/18)