-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEuler.cs
702 lines (578 loc) · 24.2 KB
/
Euler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
using System;
using System.Text.RegularExpressions;
using Mogre;
namespace MOgreEditor
{
/// <summary>
/// This struct manages rotations by use of Euler Angles.
/// The rotation will be applied in the order Yaw-Pitch-Roll, which are related to the axis order Y-X-Z.
/// It's fully compatible with Ogre::Matrix3::FromEulerAnglesYXZ and Ogre::Matrix3::ToEulerAnglesYXZ.
/// For the Yaw angle the standard anticlockwise right handed rotation is used (as common in Ogre).
/// The Yaw-Pitch-Roll ordering is most convenient for upright character controllers and cameras.
/// </summary>
public struct Euler
{
/// <summary>Get or set the Yaw angle.</summary>
public Radian Yaw
{
get { return mYaw; }
set
{
mYaw = value;
mChanged = true;
}
}
/// <summary>Get or set the Pitch angle.</summary>
public Radian Pitch
{
get { return mPitch; }
set
{
mPitch = value;
mChanged = true;
}
}
/// <summary>Get or set the Roll angle.</summary>
public Radian Roll
{
get { return mRoll; }
set
{
mRoll = value;
mChanged = true;
}
}
/// <summary>
/// Constructor to create a new Euler Angle struct from angle values.
/// The rotation will be applied in the order Yaw-Pitch- Roll, which are related to the axis order Y-X-Z.
/// </summary>
public Euler(Radian yaw, Radian pitch, Radian roll)
{
mYaw = yaw;
mPitch = pitch;
mRoll = roll;
mChanged = true;
mCachedQuaternion = Quaternion.IDENTITY;
}
/// <summary>
/// Constructor which calculates the Euler Angles from a quaternion.
/// </summary>
public Euler(Quaternion oriantation)
{
Matrix3 rotMat;
rotMat = oriantation.ToRotationMatrix();
// BUGGY METHOD (NaN return in some cases)
// rotMat.ToEulerAnglesYXZ(out mYaw, out mPitch, out mRoll);
// WORKAROUND
Boolean isUnique;
Matrix3ToEulerAnglesYXZ(rotMat, out mYaw, out mPitch, out mRoll, out isUnique);
mChanged = true;
mCachedQuaternion = Quaternion.IDENTITY;
}
/// <summary>
/// Apply a relative yaw. (Adds the angle to the current yaw value)
/// </summary>
/// <param name="yaw">Yaw value as radian</param>
public void AddYaw(Radian yaw)
{
mYaw += yaw;
mChanged = true;
}
/// <summary>
/// Apply a relative pitch. (Adds the angle to the current pitch value)
/// </summary>
/// <param name="pitch">Pitch value as radian</param>
public void AddPitch(Radian pitch)
{
mPitch += pitch;
mChanged = true;
}
/// <summary>
/// Apply a relative roll. (Adds the angle to the current roll value)
/// </summary>
/// <param name="roll">Roll value as radian</param>
public void AddRoll(Radian roll)
{
mRoll += roll;
mChanged = true;
}
/// <summary>
/// Apply a relative yaw. (Adds the angle to the current yaw value)
/// </summary>
/// <param name="yaw">Yaw value as degree</param>
public void AddYaw(Degree yaw)
{
mYaw += yaw;
mChanged = true;
}
/// <summary>
/// Apply a relative pitch. (Adds the angle to the current pitch value)
/// </summary>
/// <param name="pitch">Pitch value as degree</param>
public void AddPitch(Degree pitch)
{
mPitch += pitch;
mChanged = true;
}
/// <summary>
/// Apply a relative roll. (Adds the angle to the current roll value)
/// </summary>
/// <param name="roll">Roll value as degree</param>
public void AddRoll(Degree roll)
{
mRoll += roll;
mChanged = true;
}
/// <summary>Get a vector pointing forwards. </summary>
public Vector3 Forward
{
get { return ToQuaternion() * Vector3.NEGATIVE_UNIT_Z; }
}
/// <summary>Get a vector pointing to the right.</summary>
public Vector3 Right
{
get { return ToQuaternion() * Vector3.UNIT_X; }
}
/// <summary> Get a vector pointing up.</summary>
public Vector3 Up
{
get { return ToQuaternion() * Vector3.UNIT_Y; }
}
/// <summary>
/// Calculate the quaternion of the euler object.
/// The result is cached. It will only be recalculated when the component euler angles are changed.
/// </summary>
public Quaternion ToQuaternion()
{
if (mChanged)
{
mCachedQuaternion = new Quaternion(mYaw, Vector3.UNIT_Y) * new Quaternion(mPitch, Vector3.UNIT_X) * new Quaternion(mRoll, Vector3.UNIT_Z);
mChanged = false;
}
return mCachedQuaternion;
}
/// <summary>
/// Return a String with degree values of the axis rotations (human readable style).
/// For example "X-axis: 0° Y-axis: 36° Z-axis: 90°"
/// </summary>
public String ToAxisString()
{
return String.Format("X: {0:00}° Y: {1:00}° Z: {2:00}°",
Pitch.ValueDegrees, Yaw.ValueDegrees, Roll.ValueDegrees);
}
/// <summary>
/// Return a String with degree values in the applied rotation order (human readable style).
/// For example "Yaw: 0° Pitch: 36° Roll: 90°"
/// </summary>
public String ToYawPitchRollString()
{
return String.Format("Yaw: {0:00}° Pitch: {1:00}° Roll: {2:00}°",
Yaw.ValueDegrees, Pitch.ValueDegrees, Roll.ValueDegrees);
}
/// <summary>
/// Try to parse 3 floating point values from a string, which are seperated by spaces or tabulators.
/// Input order for rotation values:: Yaw, Pitch, Roll (all in degree)
/// If success, an Euler struct will be returned.
/// If parsing failed, a FormatException will be thrown.
/// Example: "111 .99 -66"
/// </summary>
/// <param name="valueString">String which contains 3 floating point values</param>
/// <remarks>
/// Multiple and mixed usage of space/tabulator/commas are possible.
/// As decimal seperator a dot "." is expected.
/// </remarks>
/// <returns>Returns an Euler struct or a FormatException</returns>
public static Euler ParseStringYawPitchRoll(String valueString)
{
Single[] values = Parse3Params(valueString);
if (values == null)
throw new FormatException(String.Format("Can't parse floating point values of string '{0}'", valueString));
return new Euler(new Degree(values[0]), new Degree(values[1]), new Degree(values[2]));
}
/// <summary>
/// Try to parse 3 floating point values from a string, which are seperated by spaces or tabulators or comma.
/// Input order for rotation values: X-axis, Y-axis, Z-axis (all in degree)
/// If success, an Euler struct will be returned.
/// If parsing failed, a FormatException will be thrown.
/// Example: "111 .99 -66"
/// </summary>
/// <param name="valueString">String which contains 3 floating point values</param>
/// <remarks>
/// Multiple and mixed usage of space/tabulator/commas are possible.
/// As decimal seperator a dot "." is expected.
/// </remarks>
/// <returns>Returns an Euler struct or a FormatException</returns>
public static Euler ParseStringAxisXYZ(String valueString)
{
Single[] values = Parse3Params(valueString);
if (values == null)
throw new FormatException(String.Format("Can't parse floating point values of string '{0}'", valueString));
return new Euler(new Degree(values[1]), new Degree(values[0]), new Degree(values[2]));
}
/// <summary>
/// Try to parse 3 floating point values from a string, which are seperated by spaces or tabulators or comma.
/// If parsing failed, null will be returned.
/// Example: "111 .99 -66"
/// </summary>
/// <param name="valueString">String which contains 3 floating point values</param>
/// <remarks>
/// Multiple and mixed usage of space/tabulator/commas are possible.
/// As decimal seperator a dot "." is expected.
/// </remarks>
/// <returns>Returns 3 Single values or null</returns>
private static Single[] Parse3Params(String valueString)
{
// Some Regex explanation:
//
// The "@" prefix in front of the String means:
// Backslash are processed as Text instead of special symbols.
// Advantage: Just write "\" instead of "\\" for each backslash
//
// "^" at first position means: No text is allowed before
// "$" at the end means: No text is allowed after that
//
// Floating point values are matched
// Expression: "-?\d*\.?\d+"
// Examples: "111", "0.111", ".99", "-66"
//
// Seperator can be tabs or spaces or commas (at least one symbol; mixing is possible)
// Expression: "[, \t]+"
String val = @"[-\d\.]+"; // simplified (faster) floating point pattern (exact pattern would be @"-?\d*\.?\d+" )
String sep = @"[, \t]+"; // seperator pattern
// build target pattern
String searchPattern = "^(" + val + ")" + sep + "(" + val + ")" + sep + "(" + val + ")$";
Match match = Regex.Match(valueString, searchPattern);
try
{
if (match.Success)
{
// Force to parse "." as decimal char. (Can be different with other culture settings. E.g. German culture expect "," instad of ".")
System.Globalization.CultureInfo englishCulture = new System.Globalization.CultureInfo("en-US");
Single[] result = new Single[3];
result[0] = Convert.ToSingle(match.Groups[1].Value, englishCulture);
result[1] = Convert.ToSingle(match.Groups[2].Value, englishCulture);
result[2] = Convert.ToSingle(match.Groups[3].Value, englishCulture);
return result;
}
else
return null;
}
catch (FormatException) { return null; }
catch (OverflowException) { return null; }
} // Parse3Params()
/// <summary>
/// Return the Euler rotation state as quaternion.
/// </summary>
/// <param name="e">Euler Angle state</param>
/// <returns>Rotation state as Quaternion</returns>
public static implicit operator Quaternion(Euler e)
{
return e.ToQuaternion();
}
/// <summary>
/// Set the yaw and pitch to face in the given direction.
/// The direction doesn't need to be normalised.
/// Roll is always unaffected.
/// </summary>
/// <param name="directionVector">Vector which points to the wanted direction</param>
/// <param name="setYaw">if false, the yaw isn't changed.</param>
/// <param name="setPitch">if false, the pitch isn't changed.</param>
public void SetDirection(Vector3 directionVector, Boolean setYaw, Boolean setPitch)
{
Vector3 d = directionVector.NormalisedCopy;
if (setPitch)
mPitch = Mogre.Math.ASin(d.y);
if (setYaw)
mYaw = Mogre.Math.ATan2(-d.x, -d.z);//+Mogre.Math.PI/2.0;
mChanged = setYaw || setPitch;
}
/// <summary>
/// Normalise the selected rotations to be within the +/-180 degree range.
/// The normalise uses a wrap around, so for example a yaw of 360 degrees becomes 0 degrees,
/// and -190 degrees becomes 170.
/// By the parameters it's possible to choose which angles should be normalised.
/// </summary>
/// <param name="normYaw">If true, the angle will be normalised.</param>
/// <param name="normPitch">If true, the angle will be normalised.</param>
/// <param name="normRoll">If true, the angle will be normalised.</param>
/// <remarks></remarks>
public void Normalise(Boolean normYaw, Boolean normPitch, Boolean normRoll)
{
if (normYaw)
{
Single yaw = mYaw.ValueRadians;
if (yaw < -Mogre.Math.PI)
{
yaw = (Single)System.Math.IEEERemainder(yaw, Mogre.Math.PI * 2.0);
if (yaw < -Mogre.Math.PI)
{
yaw += Mogre.Math.PI * 2.0f;
}
mYaw = yaw;
mChanged = true;
}
else if (yaw > Mogre.Math.PI)
{
yaw = (Single)System.Math.IEEERemainder(yaw, Mogre.Math.PI * 2.0f);
if (yaw > Mogre.Math.PI)
{
yaw -= Mogre.Math.PI * 2.0f;
}
mYaw = yaw;
mChanged = true;
}
}
if (normPitch)
{
Single pitch = mPitch.ValueRadians;
if (pitch < -Mogre.Math.PI)
{
pitch = (Single)System.Math.IEEERemainder(pitch, Mogre.Math.PI * 2.0f);
if (pitch < -Mogre.Math.PI)
{
pitch += Mogre.Math.PI * 2.0f;
}
mPitch = pitch;
mChanged = true;
if (Single.IsNaN(mPitch.ValueDegrees)) // DEBUGGING
{
} // add breakpoint here
}
else if (pitch > Mogre.Math.PI)
{
pitch = (Single)System.Math.IEEERemainder(pitch, Mogre.Math.PI * 2.0f);
if (pitch > Mogre.Math.PI)
{
pitch -= Mogre.Math.PI * 2.0f;
}
mPitch = pitch;
mChanged = true;
if (Single.IsNaN(mPitch.ValueDegrees)) // DEBUGGING
{
} // add breakpoint here
}
}
if (normRoll)
{
Single roll = mRoll.ValueRadians;
if (roll < -Mogre.Math.PI)
{
roll = (Single)System.Math.IEEERemainder(roll, Mogre.Math.PI * 2.0f);
if (roll < -Mogre.Math.PI)
{
roll += Mogre.Math.PI * 2.0f;
}
mRoll = roll;
mChanged = true;
}
else if (roll > Mogre.Math.PI)
{
roll = (Single)System.Math.IEEERemainder(roll, Mogre.Math.PI * 2.0f);
if (roll > Mogre.Math.PI)
{
roll -= Mogre.Math.PI * 2.0f;
}
mRoll = roll;
mChanged = true;
}
}
} // Normalise()
/// <summary>
/// Return the relative euler angles required to rotate from the current forward direction to the specified direction vector.
/// The result euler can then be added to the current euler to immediately face dir.
/// Rotation is found to face the correct direction. For example, when false a yaw of 1000 degrees and a dir of
/// (0,0,-1) will return a -1000 degree yaw. When true, the same yaw and dir would give 80 degrees (1080 degrees faces
/// the same way as (0,0,-1).
/// The rotation won't flip upside down then roll instead of a 180 degree yaw.
/// </summary>
/// <param name="direction">...TODO...</param>
/// <param name="shortest">If false, the full value of each angle is used. If true, the angles are normalised and the shortest rotation is found to face the correct direction.</param>
/// <param name="setYaw">If true the angles are calculated. If false, the angle is set to 0. </param>
/// <param name="setPitch">If true the angles are calculated. If false, the angle is set to 0. </param>
public Euler GetRotationTo(Vector3 direction, Boolean setYaw, Boolean setPitch, Boolean shortest)
{
Euler t1 = Euler.IDENTITY;
Euler t2;
t1.SetDirection(direction, setYaw, setPitch);
t2 = t1 - this;
if (shortest && setYaw)
{
t2.Normalise(true, true, true);
}
return t2;
}
/// <summary>
/// Clamp the yaw angle to a range of +/-limit.
/// </summary>
/// <param name="limit">Wanted co-domain for the Yaw angle.</param>
public void LimitYaw(Radian limit)
{
if (mYaw > limit)
{
mYaw = limit;
mChanged = true;
}
else if (mYaw < -limit)
{
mYaw = -limit;
mChanged = true;
}
}
/// <summary>
/// Clamp the pitch angle to a range of +/-limit.
/// </summary>
/// <param name="limit">Wanted co-domain for the Pitch angle.</param>
public void LimitPitch(Radian limit)
{
if (mPitch > limit)
{
mPitch = limit;
mChanged = true;
}
else if (mPitch < -limit)
{
mPitch = -limit;
mChanged = true;
}
}
/// <summary>
/// Clamp the roll angle to a range of +/-limit.
/// </summary>
/// <param name="limit">Wanted co-domain for the Roll angle.</param>
public void LimitRoll(Radian limit)
{
if (mRoll > limit)
{
mRoll = limit;
mChanged = true;
}
else if (mRoll < -limit)
{
mRoll = -limit;
mChanged = true;
}
}
/// <summary>
/// Port of method <c>Matrix3.ToEulerAnglesYXZ()</c>, from MogreMatrix3.cpp as a workaround for a bug in the Math class.
/// (The bug was fixed, but is not present in common used binary files.)
/// </summary>
/// <param name="matrix">Rotation matrix</param>
/// <param name="isUnique">If false, the orientation can be described by different angle combinations.
/// In this case the returned angle values can be different than expected.</param>
public static void Matrix3ToEulerAnglesYXZ(Matrix3 matrix,
out Radian rfYAngle, out Radian rfPAngle, out Radian rfRAngle, out Boolean isUnique)
{
rfPAngle = Mogre.Math.ASin(-matrix.m12);
if (rfPAngle < new Radian(Mogre.Math.HALF_PI))
{
if (rfPAngle > new Radian(-Mogre.Math.HALF_PI))
{
rfYAngle = Mogre.Math.ATan2(matrix.m02, matrix.m22);
rfRAngle = Mogre.Math.ATan2(matrix.m10, matrix.m11);
isUnique = true;
return;
}
else
{
// WARNING. Not a unique solution.
Radian fRmY = Mogre.Math.ATan2(-matrix.m01, matrix.m00);
rfRAngle = new Radian(0f); // any angle works
rfYAngle = rfRAngle - fRmY;
isUnique = false;
return;
}
}
else
{
// WARNING. Not a unique solution.
Radian fRpY = Mogre.Math.ATan2(-matrix.m01, matrix.m00);
rfRAngle = new Radian(0f); // any angle works
rfYAngle = fRpY - rfRAngle;
isUnique = false;
return;
}
// "Original" CODE FROM CLASS Matrix3.ToEulerAnglesYXZ()
//rfPAngle = Mogre::Math::ASin(-m12);
//if ( rfPAngle < Radian(Math::HALF_PI) )
//{
// if ( rfPAngle > Radian(-Math::HALF_PI) )
// {
// rfYAngle = System::Math::Atan2(m02,m22);
// rfRAngle = System::Math::Atan2(m10,m11);
// return true;
// }
// else
// {
// // WARNING. Not a unique solution.
// Radian fRmY = System::Math::Atan2(-m01,m00);
// rfRAngle = Radian(0.0); // any angle works
// rfYAngle = rfRAngle - fRmY;
// return false;
// }
//}
//else
//{
// // WARNING. Not a unique solution.
// Radian fRpY = System::Math::Atan2(-m01,m00);
// rfRAngle = Radian(0.0); // any angle works
// rfYAngle = fRpY - rfRAngle;
// return false;
//}
} // Matrix3ToEulerAnglesYXZ()
/// <summary>
/// Add two euler objects.
/// </summary>
/// <returns>Calculation result</returns>
public static Euler operator +(Euler lhs, Euler rhs)
{
return new Euler(lhs.Yaw + rhs.Yaw, lhs.Pitch + rhs.Pitch, lhs.Roll + rhs.Roll);
}
/// <summary>
/// Subtract two euler objects. This finds the difference as relative angles.
/// </summary>
/// <returns>Calculation result</returns>
public static Euler operator -(Euler lhs, Euler rhs)
{
return new Euler(lhs.Yaw - rhs.Yaw, lhs.Pitch - rhs.Pitch, lhs.Roll - rhs.Roll);
}
/// <summary>
/// Interpolate each euler angle by the given factor.
/// (Each angle will be multiplied with the factor.)
/// </summary>
/// <returns>Calculation result</returns>
public static Euler operator *(Euler lhs, Single factor)
{
return new Euler(lhs.Yaw * factor, lhs.Pitch * factor, lhs.Roll * factor);
}
/// <summary>
/// Interpolate the euler angles by lhs.
/// (Each angle will be multiplied with the factor.)
/// </summary>
/// <returns>Calculation result</returns>
public static Euler operator *(Single factor, Euler rhs)
{
return new Euler(factor * rhs.Yaw, factor * rhs.Pitch, factor * rhs.Roll);
}
/// <summary>
/// Apply the euler rotation to the vector rhs.
/// The calculation is equal to: quaternion*vector
/// </summary>
/// <returns>Calculation result</returns>
public static Vector3 operator *(Euler lhs, Vector3 rhs)
{
return lhs.ToQuaternion() * rhs;
}
/// <summary>Base settings (all angles are 0)</summary>
public static Euler IDENTITY = new Euler(new Radian(0), new Radian(0), new Radian(0));
/// <summary>Rotation around the Y axis.</summary>
private Radian mYaw;
/// <summary>Rotation around the X axis.</summary>
private Radian mPitch;
/// <summary>Rotation around the Z axis.</summary>
private Radian mRoll;
/// <summary>Is the cached quaternion out of date?</summary>
private bool mChanged;
/// <summary>Cached quaternion equivalent of this euler object.</summary>
private Quaternion mCachedQuaternion;
} // struct Euler
}