Fix64.cs 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  1. using System;
  2. using System.IO;
  3. namespace TrueSync {
  4. /// <summary>
  5. /// Represents a Q31.32 fixed-point number.
  6. /// </summary>
  7. [Serializable]
  8. public partial struct FP : IEquatable<FP>, IComparable<FP> {
  9. public long _serializedValue;
  10. public const long MAX_VALUE = long.MaxValue;
  11. public const long MIN_VALUE = long.MinValue;
  12. public const int NUM_BITS = 64;
  13. public const int FRACTIONAL_PLACES = 32;
  14. public const long ONE = 1L << FRACTIONAL_PLACES;
  15. public const long TEN = 10L << FRACTIONAL_PLACES;
  16. public const long HALF = 1L << (FRACTIONAL_PLACES - 1);
  17. public const long PI_TIMES_2 = 0x6487ED511;
  18. public const long PI = 0x3243F6A88;
  19. public const long PI_OVER_2 = 0x1921FB544;
  20. public const long LN2 = 0xB17217F7;
  21. public const long LOG2MAX = 0x1F00000000;
  22. public const long LOG2MIN = -0x2000000000;
  23. public const int LUT_SIZE = (int)(PI_OVER_2 >> 15);
  24. // Precision of this type is 2^-32, that is 2,3283064365386962890625E-10
  25. public static readonly decimal Precision = (decimal)(new FP(1L));//0.00000000023283064365386962890625m;
  26. public static readonly FP MaxValue = new FP(MAX_VALUE-1);
  27. public static readonly FP MinValue = new FP(MIN_VALUE+2);
  28. public static readonly FP One = new FP(ONE);
  29. public static readonly FP Ten = new FP(TEN);
  30. public static readonly FP Half = new FP(HALF);
  31. public static readonly FP Zero = new FP();
  32. public static readonly FP PositiveInfinity = new FP(MAX_VALUE);
  33. public static readonly FP NegativeInfinity = new FP(MIN_VALUE+1);
  34. public static readonly FP NaN = new FP(MIN_VALUE);
  35. public static readonly FP EN1 = FP.One / 10;
  36. public static readonly FP EN2 = FP.One / 100;
  37. public static readonly FP EN3 = FP.One / 1000;
  38. public static readonly FP EN4 = FP.One / 10000;
  39. public static readonly FP EN5 = FP.One / 100000;
  40. public static readonly FP EN6 = FP.One / 1000000;
  41. public static readonly FP EN7 = FP.One / 10000000;
  42. public static readonly FP EN8 = FP.One / 100000000;
  43. public static readonly FP Epsilon = FP.EN3;
  44. /// <summary>
  45. /// The value of Pi
  46. /// </summary>
  47. public static readonly FP Pi = new FP(PI);
  48. public static readonly FP PiOver2 = new FP(PI_OVER_2);
  49. public static readonly FP PiTimes2 = new FP(PI_TIMES_2);
  50. public static readonly FP PiInv = (FP)0.3183098861837906715377675267M;
  51. public static readonly FP PiOver2Inv = (FP)0.6366197723675813430755350535M;
  52. public static readonly FP Deg2Rad = Pi / new FP(180);
  53. public static readonly FP Rad2Deg = new FP(180) / Pi;
  54. public static readonly FP LutInterval = (FP)(LUT_SIZE - 1) / PiOver2;
  55. public static readonly FP Log2Max = new FP(LOG2MAX);
  56. public static readonly FP Log2Min = new FP(LOG2MIN);
  57. public static readonly FP Ln2 = new FP(LN2);
  58. /// <summary>
  59. /// Returns a number indicating the sign of a Fix64 number.
  60. /// Returns 1 if the value is positive, 0 if is 0, and -1 if it is negative.
  61. /// </summary>
  62. public static int Sign(FP value) {
  63. return
  64. value._serializedValue < 0 ? -1 :
  65. value._serializedValue > 0 ? 1 :
  66. 0;
  67. }
  68. /// <summary>
  69. /// Returns the absolute value of a Fix64 number.
  70. /// Note: Abs(Fix64.MinValue) == Fix64.MaxValue.
  71. /// </summary>
  72. public static FP Abs(FP value) {
  73. if (value._serializedValue == MIN_VALUE) {
  74. return MaxValue;
  75. }
  76. // branchless implementation, see http://www.strchr.com/optimized_abs_function
  77. var mask = value._serializedValue >> 63;
  78. FP result;
  79. result._serializedValue = (value._serializedValue + mask) ^ mask;
  80. return result;
  81. //return new FP((value._serializedValue + mask) ^ mask);
  82. }
  83. /// <summary>
  84. /// Returns the absolute value of a Fix64 number.
  85. /// FastAbs(Fix64.MinValue) is undefined.
  86. /// </summary>
  87. public static FP FastAbs(FP value) {
  88. // branchless implementation, see http://www.strchr.com/optimized_abs_function
  89. var mask = value._serializedValue >> 63;
  90. FP result;
  91. result._serializedValue = (value._serializedValue + mask) ^ mask;
  92. return result;
  93. //return new FP((value._serializedValue + mask) ^ mask);
  94. }
  95. /// <summary>
  96. /// Returns the largest integer less than or equal to the specified number.
  97. /// </summary>
  98. public static FP Floor(FP value) {
  99. // Just zero out the fractional part
  100. FP result;
  101. result._serializedValue = (long)((ulong)value._serializedValue & 0xFFFFFFFF00000000);
  102. return result;
  103. //return new FP((long)((ulong)value._serializedValue & 0xFFFFFFFF00000000));
  104. }
  105. /// <summary>
  106. /// Returns the smallest integral value that is greater than or equal to the specified number.
  107. /// </summary>
  108. public static FP Ceiling(FP value) {
  109. var hasFractionalPart = (value._serializedValue & 0x00000000FFFFFFFF) != 0;
  110. return hasFractionalPart ? Floor(value) + One : value;
  111. }
  112. /// <summary>
  113. /// Rounds a value to the nearest integral value.
  114. /// If the value is halfway between an even and an uneven value, returns the even value.
  115. /// </summary>
  116. public static FP Round(FP value) {
  117. var fractionalPart = value._serializedValue & 0x00000000FFFFFFFF;
  118. var integralPart = Floor(value);
  119. if (fractionalPart < 0x80000000) {
  120. return integralPart;
  121. }
  122. if (fractionalPart > 0x80000000) {
  123. return integralPart + One;
  124. }
  125. // if number is halfway between two values, round to the nearest even number
  126. // this is the method used by System.Math.Round().
  127. return (integralPart._serializedValue & ONE) == 0
  128. ? integralPart
  129. : integralPart + One;
  130. }
  131. /// <summary>
  132. /// Adds x and y. Performs saturating addition, i.e. in case of overflow,
  133. /// rounds to MinValue or MaxValue depending on sign of operands.
  134. /// </summary>
  135. public static FP operator +(FP x, FP y) {
  136. FP result;
  137. result._serializedValue = x._serializedValue + y._serializedValue;
  138. return result;
  139. //return new FP(x._serializedValue + y._serializedValue);
  140. }
  141. /// <summary>
  142. /// Adds x and y performing overflow checking. Should be inlined by the CLR.
  143. /// </summary>
  144. public static FP OverflowAdd(FP x, FP y) {
  145. var xl = x._serializedValue;
  146. var yl = y._serializedValue;
  147. var sum = xl + yl;
  148. // if signs of operands are equal and signs of sum and x are different
  149. if (((~(xl ^ yl) & (xl ^ sum)) & MIN_VALUE) != 0) {
  150. sum = xl > 0 ? MAX_VALUE : MIN_VALUE;
  151. }
  152. FP result;
  153. result._serializedValue = sum;
  154. return result;
  155. //return new FP(sum);
  156. }
  157. /// <summary>
  158. /// Adds x and y witout performing overflow checking. Should be inlined by the CLR.
  159. /// </summary>
  160. public static FP FastAdd(FP x, FP y) {
  161. FP result;
  162. result._serializedValue = x._serializedValue + y._serializedValue;
  163. return result;
  164. //return new FP(x._serializedValue + y._serializedValue);
  165. }
  166. /// <summary>
  167. /// Subtracts y from x. Performs saturating substraction, i.e. in case of overflow,
  168. /// rounds to MinValue or MaxValue depending on sign of operands.
  169. /// </summary>
  170. public static FP operator -(FP x, FP y) {
  171. FP result;
  172. result._serializedValue = x._serializedValue - y._serializedValue;
  173. return result;
  174. //return new FP(x._serializedValue - y._serializedValue);
  175. }
  176. /// <summary>
  177. /// Subtracts y from x witout performing overflow checking. Should be inlined by the CLR.
  178. /// </summary>
  179. public static FP OverflowSub(FP x, FP y) {
  180. var xl = x._serializedValue;
  181. var yl = y._serializedValue;
  182. var diff = xl - yl;
  183. // if signs of operands are different and signs of sum and x are different
  184. if ((((xl ^ yl) & (xl ^ diff)) & MIN_VALUE) != 0) {
  185. diff = xl < 0 ? MIN_VALUE : MAX_VALUE;
  186. }
  187. FP result;
  188. result._serializedValue = diff;
  189. return result;
  190. //return new FP(diff);
  191. }
  192. /// <summary>
  193. /// Subtracts y from x witout performing overflow checking. Should be inlined by the CLR.
  194. /// </summary>
  195. public static FP FastSub(FP x, FP y) {
  196. return new FP(x._serializedValue - y._serializedValue);
  197. }
  198. static long AddOverflowHelper(long x, long y, ref bool overflow) {
  199. var sum = x + y;
  200. // x + y overflows if sign(x) ^ sign(y) != sign(sum)
  201. overflow |= ((x ^ y ^ sum) & MIN_VALUE) != 0;
  202. return sum;
  203. }
  204. public static FP operator *(FP x, FP y) {
  205. var xl = x._serializedValue;
  206. var yl = y._serializedValue;
  207. var xlo = (ulong)(xl & 0x00000000FFFFFFFF);
  208. var xhi = xl >> FRACTIONAL_PLACES;
  209. var ylo = (ulong)(yl & 0x00000000FFFFFFFF);
  210. var yhi = yl >> FRACTIONAL_PLACES;
  211. var lolo = xlo * ylo;
  212. var lohi = (long)xlo * yhi;
  213. var hilo = xhi * (long)ylo;
  214. var hihi = xhi * yhi;
  215. var loResult = lolo >> FRACTIONAL_PLACES;
  216. var midResult1 = lohi;
  217. var midResult2 = hilo;
  218. var hiResult = hihi << FRACTIONAL_PLACES;
  219. var sum = (long)loResult + midResult1 + midResult2 + hiResult;
  220. FP result;// = default(FP);
  221. result._serializedValue = sum;
  222. return result;
  223. }
  224. /// <summary>
  225. /// Performs multiplication without checking for overflow.
  226. /// Useful for performance-critical code where the values are guaranteed not to cause overflow
  227. /// </summary>
  228. public static FP OverflowMul(FP x, FP y) {
  229. var xl = x._serializedValue;
  230. var yl = y._serializedValue;
  231. var xlo = (ulong)(xl & 0x00000000FFFFFFFF);
  232. var xhi = xl >> FRACTIONAL_PLACES;
  233. var ylo = (ulong)(yl & 0x00000000FFFFFFFF);
  234. var yhi = yl >> FRACTIONAL_PLACES;
  235. var lolo = xlo * ylo;
  236. var lohi = (long)xlo * yhi;
  237. var hilo = xhi * (long)ylo;
  238. var hihi = xhi * yhi;
  239. var loResult = lolo >> FRACTIONAL_PLACES;
  240. var midResult1 = lohi;
  241. var midResult2 = hilo;
  242. var hiResult = hihi << FRACTIONAL_PLACES;
  243. bool overflow = false;
  244. var sum = AddOverflowHelper((long)loResult, midResult1, ref overflow);
  245. sum = AddOverflowHelper(sum, midResult2, ref overflow);
  246. sum = AddOverflowHelper(sum, hiResult, ref overflow);
  247. bool opSignsEqual = ((xl ^ yl) & MIN_VALUE) == 0;
  248. // if signs of operands are equal and sign of result is negative,
  249. // then multiplication overflowed positively
  250. // the reverse is also true
  251. if (opSignsEqual) {
  252. if (sum < 0 || (overflow && xl > 0)) {
  253. return MaxValue;
  254. }
  255. } else {
  256. if (sum > 0) {
  257. return MinValue;
  258. }
  259. }
  260. // if the top 32 bits of hihi (unused in the result) are neither all 0s or 1s,
  261. // then this means the result overflowed.
  262. var topCarry = hihi >> FRACTIONAL_PLACES;
  263. if (topCarry != 0 && topCarry != -1 /*&& xl != -17 && yl != -17*/) {
  264. return opSignsEqual ? MaxValue : MinValue;
  265. }
  266. // If signs differ, both operands' magnitudes are greater than 1,
  267. // and the result is greater than the negative operand, then there was negative overflow.
  268. if (!opSignsEqual) {
  269. long posOp, negOp;
  270. if (xl > yl) {
  271. posOp = xl;
  272. negOp = yl;
  273. } else {
  274. posOp = yl;
  275. negOp = xl;
  276. }
  277. if (sum > negOp && negOp < -ONE && posOp > ONE) {
  278. return MinValue;
  279. }
  280. }
  281. FP result;
  282. result._serializedValue = sum;
  283. return result;
  284. //return new FP(sum);
  285. }
  286. /// <summary>
  287. /// Performs multiplication without checking for overflow.
  288. /// Useful for performance-critical code where the values are guaranteed not to cause overflow
  289. /// </summary>
  290. public static FP FastMul(FP x, FP y) {
  291. var xl = x._serializedValue;
  292. var yl = y._serializedValue;
  293. var xlo = (ulong)(xl & 0x00000000FFFFFFFF);
  294. var xhi = xl >> FRACTIONAL_PLACES;
  295. var ylo = (ulong)(yl & 0x00000000FFFFFFFF);
  296. var yhi = yl >> FRACTIONAL_PLACES;
  297. var lolo = xlo * ylo;
  298. var lohi = (long)xlo * yhi;
  299. var hilo = xhi * (long)ylo;
  300. var hihi = xhi * yhi;
  301. var loResult = lolo >> FRACTIONAL_PLACES;
  302. var midResult1 = lohi;
  303. var midResult2 = hilo;
  304. var hiResult = hihi << FRACTIONAL_PLACES;
  305. var sum = (long)loResult + midResult1 + midResult2 + hiResult;
  306. FP result;// = default(FP);
  307. result._serializedValue = sum;
  308. return result;
  309. //return new FP(sum);
  310. }
  311. //[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
  312. public static int CountLeadingZeroes(ulong x) {
  313. int result = 0;
  314. while ((x & 0xF000000000000000) == 0) { result += 4; x <<= 4; }
  315. while ((x & 0x8000000000000000) == 0) { result += 1; x <<= 1; }
  316. return result;
  317. }
  318. public static FP operator /(FP x, FP y) {
  319. var xl = x._serializedValue;
  320. var yl = y._serializedValue;
  321. if (yl == 0) {
  322. return MAX_VALUE;
  323. //throw new DivideByZeroException();
  324. }
  325. var remainder = (ulong)(xl >= 0 ? xl : -xl);
  326. var divider = (ulong)(yl >= 0 ? yl : -yl);
  327. var quotient = 0UL;
  328. var bitPos = NUM_BITS / 2 + 1;
  329. // If the divider is divisible by 2^n, take advantage of it.
  330. while ((divider & 0xF) == 0 && bitPos >= 4) {
  331. divider >>= 4;
  332. bitPos -= 4;
  333. }
  334. while (remainder != 0 && bitPos >= 0) {
  335. int shift = CountLeadingZeroes(remainder);
  336. if (shift > bitPos) {
  337. shift = bitPos;
  338. }
  339. remainder <<= shift;
  340. bitPos -= shift;
  341. var div = remainder / divider;
  342. remainder = remainder % divider;
  343. quotient += div << bitPos;
  344. // Detect overflow
  345. if ((div & ~(0xFFFFFFFFFFFFFFFF >> bitPos)) != 0) {
  346. return ((xl ^ yl) & MIN_VALUE) == 0 ? MaxValue : MinValue;
  347. }
  348. remainder <<= 1;
  349. --bitPos;
  350. }
  351. // rounding
  352. ++quotient;
  353. var result = (long)(quotient >> 1);
  354. if (((xl ^ yl) & MIN_VALUE) != 0) {
  355. result = -result;
  356. }
  357. FP r;
  358. r._serializedValue = result;
  359. return r;
  360. //return new FP(result);
  361. }
  362. public static FP operator %(FP x, FP y) {
  363. FP result;
  364. result._serializedValue = x._serializedValue == MIN_VALUE & y._serializedValue == -1 ?
  365. 0 :
  366. x._serializedValue % y._serializedValue;
  367. return result;
  368. //return new FP(
  369. // x._serializedValue == MIN_VALUE & y._serializedValue == -1 ?
  370. // 0 :
  371. // x._serializedValue % y._serializedValue);
  372. }
  373. /// <summary>
  374. /// Performs modulo as fast as possible; throws if x == MinValue and y == -1.
  375. /// Use the operator (%) for a more reliable but slower modulo.
  376. /// </summary>
  377. public static FP FastMod(FP x, FP y) {
  378. FP result;
  379. result._serializedValue = x._serializedValue % y._serializedValue;
  380. return result;
  381. //return new FP(x._serializedValue % y._serializedValue);
  382. }
  383. public static FP operator -(FP x) {
  384. return x._serializedValue == MIN_VALUE ? MaxValue : new FP(-x._serializedValue);
  385. }
  386. public static bool operator ==(FP x, FP y) {
  387. return x._serializedValue == y._serializedValue;
  388. }
  389. public static bool operator !=(FP x, FP y) {
  390. return x._serializedValue != y._serializedValue;
  391. }
  392. public static bool operator >(FP x, FP y) {
  393. return x._serializedValue > y._serializedValue;
  394. }
  395. public static bool operator <(FP x, FP y) {
  396. return x._serializedValue < y._serializedValue;
  397. }
  398. public static bool operator >=(FP x, FP y) {
  399. return x._serializedValue >= y._serializedValue;
  400. }
  401. public static bool operator <=(FP x, FP y) {
  402. return x._serializedValue <= y._serializedValue;
  403. }
  404. /// <summary>
  405. /// Returns the square root of a specified number.
  406. /// </summary>
  407. /// <exception cref="ArgumentOutOfRangeException">
  408. /// The argument was negative.
  409. /// </exception>
  410. public static FP Sqrt(FP x) {
  411. var xl = x._serializedValue;
  412. if (xl < 0) {
  413. // We cannot represent infinities like Single and Double, and Sqrt is
  414. // mathematically undefined for x < 0. So we just throw an exception.
  415. throw new ArgumentOutOfRangeException("Negative value passed to Sqrt", "x");
  416. }
  417. var num = (ulong)xl;
  418. var result = 0UL;
  419. // second-to-top bit
  420. var bit = 1UL << (NUM_BITS - 2);
  421. while (bit > num) {
  422. bit >>= 2;
  423. }
  424. // The main part is executed twice, in order to avoid
  425. // using 128 bit values in computations.
  426. for (var i = 0; i < 2; ++i) {
  427. // First we get the top 48 bits of the answer.
  428. while (bit != 0) {
  429. if (num >= result + bit) {
  430. num -= result + bit;
  431. result = (result >> 1) + bit;
  432. } else {
  433. result = result >> 1;
  434. }
  435. bit >>= 2;
  436. }
  437. if (i == 0) {
  438. // Then process it again to get the lowest 16 bits.
  439. if (num > (1UL << (NUM_BITS / 2)) - 1) {
  440. // The remainder 'num' is too large to be shifted left
  441. // by 32, so we have to add 1 to result manually and
  442. // adjust 'num' accordingly.
  443. // num = a - (result + 0.5)^2
  444. // = num + result^2 - (result + 0.5)^2
  445. // = num - result - 0.5
  446. num -= result;
  447. num = (num << (NUM_BITS / 2)) - 0x80000000UL;
  448. result = (result << (NUM_BITS / 2)) + 0x80000000UL;
  449. } else {
  450. num <<= (NUM_BITS / 2);
  451. result <<= (NUM_BITS / 2);
  452. }
  453. bit = 1UL << (NUM_BITS / 2 - 2);
  454. }
  455. }
  456. // Finally, if next bit would have been 1, round the result upwards.
  457. if (num > result) {
  458. ++result;
  459. }
  460. FP r;
  461. r._serializedValue = (long)result;
  462. return r;
  463. //return new FP((long)result);
  464. }
  465. /// <summary>
  466. /// Returns the Sine of x.
  467. /// This function has about 9 decimals of accuracy for small values of x.
  468. /// It may lose accuracy as the value of x grows.
  469. /// Performance: about 25% slower than Math.Sin() in x64, and 200% slower in x86.
  470. /// </summary>
  471. public static FP Sin(FP x) {
  472. bool flipHorizontal, flipVertical;
  473. var clampedL = ClampSinValue(x._serializedValue, out flipHorizontal, out flipVertical);
  474. var clamped = new FP(clampedL);
  475. // Find the two closest values in the LUT and perform linear interpolation
  476. // This is what kills the performance of this function on x86 - x64 is fine though
  477. var rawIndex = FastMul(clamped, LutInterval);
  478. var roundedIndex = Round(rawIndex);
  479. var indexError = 0;//FastSub(rawIndex, roundedIndex);
  480. var nearestValue = new FP(SinLut[flipHorizontal ?
  481. SinLut.Length - 1 - (int)roundedIndex :
  482. (int)roundedIndex]);
  483. var secondNearestValue = new FP(SinLut[flipHorizontal ?
  484. SinLut.Length - 1 - (int)roundedIndex - Sign(indexError) :
  485. (int)roundedIndex + Sign(indexError)]);
  486. var delta = FastMul(indexError, FastAbs(FastSub(nearestValue, secondNearestValue)))._serializedValue;
  487. var interpolatedValue = nearestValue._serializedValue + (flipHorizontal ? -delta : delta);
  488. var finalValue = flipVertical ? -interpolatedValue : interpolatedValue;
  489. //FP a2 = new FP(finalValue);
  490. FP a2;
  491. a2._serializedValue = finalValue;
  492. return a2;
  493. }
  494. /// <summary>
  495. /// Returns a rough approximation of the Sine of x.
  496. /// This is at least 3 times faster than Sin() on x86 and slightly faster than Math.Sin(),
  497. /// however its accuracy is limited to 4-5 decimals, for small enough values of x.
  498. /// </summary>
  499. public static FP FastSin(FP x) {
  500. bool flipHorizontal, flipVertical;
  501. var clampedL = ClampSinValue(x._serializedValue, out flipHorizontal, out flipVertical);
  502. // Here we use the fact that the SinLut table has a number of entries
  503. // equal to (PI_OVER_2 >> 15) to use the angle to index directly into it
  504. var rawIndex = (uint)(clampedL >> 15);
  505. if (rawIndex >= LUT_SIZE) {
  506. rawIndex = LUT_SIZE - 1;
  507. }
  508. var nearestValue = SinLut[flipHorizontal ?
  509. SinLut.Length - 1 - (int)rawIndex :
  510. (int)rawIndex];
  511. FP result;
  512. result._serializedValue = flipVertical ? -nearestValue : nearestValue;
  513. return result;
  514. //return new FP(flipVertical ? -nearestValue : nearestValue);
  515. }
  516. //[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
  517. public static long ClampSinValue(long angle, out bool flipHorizontal, out bool flipVertical) {
  518. // Clamp value to 0 - 2*PI using modulo; this is very slow but there's no better way AFAIK
  519. var clamped2Pi = angle % PI_TIMES_2;
  520. if (angle < 0) {
  521. clamped2Pi += PI_TIMES_2;
  522. }
  523. // The LUT contains values for 0 - PiOver2; every other value must be obtained by
  524. // vertical or horizontal mirroring
  525. flipVertical = clamped2Pi >= PI;
  526. // obtain (angle % PI) from (angle % 2PI) - much faster than doing another modulo
  527. var clampedPi = clamped2Pi;
  528. while (clampedPi >= PI) {
  529. clampedPi -= PI;
  530. }
  531. flipHorizontal = clampedPi >= PI_OVER_2;
  532. // obtain (angle % PI_OVER_2) from (angle % PI) - much faster than doing another modulo
  533. var clampedPiOver2 = clampedPi;
  534. if (clampedPiOver2 >= PI_OVER_2) {
  535. clampedPiOver2 -= PI_OVER_2;
  536. }
  537. return clampedPiOver2;
  538. }
  539. /// <summary>
  540. /// Returns the cosine of x.
  541. /// See Sin() for more details.
  542. /// </summary>
  543. public static FP Cos(FP x) {
  544. var xl = x._serializedValue;
  545. var rawAngle = xl + (xl > 0 ? -PI - PI_OVER_2 : PI_OVER_2);
  546. FP a2 = Sin(new FP(rawAngle));
  547. return a2;
  548. }
  549. /// <summary>
  550. /// Returns a rough approximation of the cosine of x.
  551. /// See FastSin for more details.
  552. /// </summary>
  553. public static FP FastCos(FP x) {
  554. var xl = x._serializedValue;
  555. var rawAngle = xl + (xl > 0 ? -PI - PI_OVER_2 : PI_OVER_2);
  556. return FastSin(new FP(rawAngle));
  557. }
  558. /// <summary>
  559. /// Returns the tangent of x.
  560. /// </summary>
  561. /// <remarks>
  562. /// This function is not well-tested. It may be wildly inaccurate.
  563. /// </remarks>
  564. public static FP Tan(FP x) {
  565. var clampedPi = x._serializedValue % PI;
  566. var flip = false;
  567. if (clampedPi < 0) {
  568. clampedPi = -clampedPi;
  569. flip = true;
  570. }
  571. if (clampedPi > PI_OVER_2) {
  572. flip = !flip;
  573. clampedPi = PI_OVER_2 - (clampedPi - PI_OVER_2);
  574. }
  575. var clamped = new FP(clampedPi);
  576. // Find the two closest values in the LUT and perform linear interpolation
  577. var rawIndex = FastMul(clamped, LutInterval);
  578. var roundedIndex = Round(rawIndex);
  579. var indexError = FastSub(rawIndex, roundedIndex);
  580. var nearestValue = new FP(TanLut[(int)roundedIndex]);
  581. var secondNearestValue = new FP(TanLut[(int)roundedIndex + Sign(indexError)]);
  582. var delta = FastMul(indexError, FastAbs(FastSub(nearestValue, secondNearestValue)))._serializedValue;
  583. var interpolatedValue = nearestValue._serializedValue + delta;
  584. var finalValue = flip ? -interpolatedValue : interpolatedValue;
  585. FP a2 = new FP(finalValue);
  586. return a2;
  587. }
  588. /// <summary>
  589. /// Returns the arctan of of the specified number, calculated using Euler series
  590. /// This function has at least 7 decimals of accuracy.
  591. /// </summary>
  592. public static FP Atan(FP z)
  593. {
  594. if (z.RawValue == 0) return Zero;
  595. // Force positive values for argument
  596. // Atan(-z) = -Atan(z).
  597. var neg = z.RawValue < 0;
  598. if (neg)
  599. {
  600. z = -z;
  601. }
  602. FP result;
  603. var two = (FP)2;
  604. var three = (FP)3;
  605. bool invert = z > One;
  606. if (invert) z = One / z;
  607. result = One;
  608. var term = One;
  609. var zSq = z * z;
  610. var zSq2 = zSq * two;
  611. var zSqPlusOne = zSq + One;
  612. var zSq12 = zSqPlusOne * two;
  613. var dividend = zSq2;
  614. var divisor = zSqPlusOne * three;
  615. for (var i = 2; i < 30; ++i)
  616. {
  617. term *= dividend / divisor;
  618. result += term;
  619. dividend += zSq2;
  620. divisor += zSq12;
  621. if (term.RawValue == 0) break;
  622. }
  623. result = result * z / zSqPlusOne;
  624. if (invert)
  625. {
  626. result = PiOver2 - result;
  627. }
  628. if (neg)
  629. {
  630. result = -result;
  631. }
  632. return result;
  633. }
  634. public static FP Atan2(FP y, FP x) {
  635. var yl = y._serializedValue;
  636. var xl = x._serializedValue;
  637. if (xl == 0) {
  638. if (yl > 0) {
  639. return PiOver2;
  640. }
  641. if (yl == 0) {
  642. return Zero;
  643. }
  644. return -PiOver2;
  645. }
  646. FP atan;
  647. var z = y / x;
  648. FP sm = FP.EN2 * 28;
  649. // Deal with overflow
  650. if (One + sm * z * z == MaxValue) {
  651. return y < Zero ? -PiOver2 : PiOver2;
  652. }
  653. if (Abs(z) < One) {
  654. atan = z / (One + sm * z * z);
  655. if (xl < 0) {
  656. if (yl < 0) {
  657. return atan - Pi;
  658. }
  659. return atan + Pi;
  660. }
  661. } else {
  662. atan = PiOver2 - z / (z * z + sm);
  663. if (yl < 0) {
  664. return atan - Pi;
  665. }
  666. }
  667. return atan;
  668. }
  669. public static FP Asin(FP value) {
  670. return FastSub(PiOver2, Acos(value));
  671. }
  672. /// <summary>
  673. /// Returns the arccos of of the specified number, calculated using Atan and Sqrt
  674. /// This function has at least 7 decimals of accuracy.
  675. /// </summary>
  676. public static FP Acos(FP x)
  677. {
  678. if (x < -One || x > One)
  679. {
  680. throw new ArgumentOutOfRangeException("Must between -FP.One and FP.One", "x");
  681. }
  682. if (x.RawValue == 0) return PiOver2;
  683. var result = Atan(Sqrt(One - x * x) / x);
  684. return x.RawValue < 0 ? result + Pi : result;
  685. }
  686. public static implicit operator FP(long value) {
  687. FP result;
  688. result._serializedValue = value * ONE;
  689. return result;
  690. //return new FP(value * ONE);
  691. }
  692. public static explicit operator long(FP value) {
  693. return value._serializedValue >> FRACTIONAL_PLACES;
  694. }
  695. public static implicit operator FP(float value) {
  696. FP result;
  697. result._serializedValue = (long)(value * ONE);
  698. return result;
  699. //return new FP((long)(value * ONE));
  700. }
  701. public static explicit operator float(FP value) {
  702. return (float)value._serializedValue / ONE;
  703. }
  704. public static implicit operator FP(double value) {
  705. FP result;
  706. result._serializedValue = (long)(value * ONE);
  707. return result;
  708. //return new FP((long)(value * ONE));
  709. }
  710. public static explicit operator double(FP value) {
  711. return (double)value._serializedValue / ONE;
  712. }
  713. public static explicit operator FP(decimal value) {
  714. FP result;
  715. result._serializedValue = (long)(value * ONE);
  716. return result;
  717. //return new FP((long)(value * ONE));
  718. }
  719. public static implicit operator FP(int value) {
  720. FP result;
  721. result._serializedValue = value * ONE;
  722. return result;
  723. //return new FP(value * ONE);
  724. }
  725. public static explicit operator decimal(FP value) {
  726. return (decimal)value._serializedValue / ONE;
  727. }
  728. public float AsFloat() {
  729. return (float) this;
  730. }
  731. public int AsInt() {
  732. return (int) this;
  733. }
  734. public long AsLong() {
  735. return (long)this;
  736. }
  737. public double AsDouble() {
  738. return (double)this;
  739. }
  740. public decimal AsDecimal() {
  741. return (decimal)this;
  742. }
  743. public static float ToFloat(FP value) {
  744. return (float)value;
  745. }
  746. public static int ToInt(FP value) {
  747. return (int)value;
  748. }
  749. public static FP FromFloat(float value) {
  750. return (FP)value;
  751. }
  752. public static bool IsInfinity(FP value) {
  753. return value == NegativeInfinity || value == PositiveInfinity;
  754. }
  755. public static bool IsNaN(FP value) {
  756. return value == NaN;
  757. }
  758. public override bool Equals(object obj) {
  759. return obj is FP && ((FP)obj)._serializedValue == _serializedValue;
  760. }
  761. public override int GetHashCode() {
  762. return _serializedValue.GetHashCode();
  763. }
  764. public bool Equals(FP other) {
  765. return _serializedValue == other._serializedValue;
  766. }
  767. public int CompareTo(FP other) {
  768. return _serializedValue.CompareTo(other._serializedValue);
  769. }
  770. public override string ToString() {
  771. return ((float)this).ToString();
  772. }
  773. public string ToString(IFormatProvider provider) {
  774. return ((float)this).ToString(provider);
  775. }
  776. public string ToString(string format) {
  777. return ((float)this).ToString(format);
  778. }
  779. public static FP FromRaw(long rawValue) {
  780. return new FP(rawValue);
  781. }
  782. internal static void GenerateAcosLut() {
  783. using (var writer = new StreamWriter("Fix64AcosLut.cs")) {
  784. writer.Write(
  785. @"namespace TrueSync {
  786. partial struct FP {
  787. public static readonly long[] AcosLut = new[] {");
  788. int lineCounter = 0;
  789. for (int i = 0; i < LUT_SIZE; ++i) {
  790. var angle = i / ((float)(LUT_SIZE - 1));
  791. if (lineCounter++ % 8 == 0) {
  792. writer.WriteLine();
  793. writer.Write(" ");
  794. }
  795. var acos = Math.Acos(angle);
  796. var rawValue = ((FP)acos)._serializedValue;
  797. writer.Write(string.Format("0x{0:X}L, ", rawValue));
  798. }
  799. writer.Write(
  800. @"
  801. };
  802. }
  803. }");
  804. }
  805. }
  806. internal static void GenerateSinLut() {
  807. using (var writer = new StreamWriter("Fix64SinLut.cs")) {
  808. writer.Write(
  809. @"namespace FixMath.NET {
  810. partial struct Fix64 {
  811. public static readonly long[] SinLut = new[] {");
  812. int lineCounter = 0;
  813. for (int i = 0; i < LUT_SIZE; ++i) {
  814. var angle = i * Math.PI * 0.5 / (LUT_SIZE - 1);
  815. if (lineCounter++ % 8 == 0) {
  816. writer.WriteLine();
  817. writer.Write(" ");
  818. }
  819. var sin = Math.Sin(angle);
  820. var rawValue = ((FP)sin)._serializedValue;
  821. writer.Write(string.Format("0x{0:X}L, ", rawValue));
  822. }
  823. writer.Write(
  824. @"
  825. };
  826. }
  827. }");
  828. }
  829. }
  830. internal static void GenerateTanLut() {
  831. using (var writer = new StreamWriter("Fix64TanLut.cs")) {
  832. writer.Write(
  833. @"namespace FixMath.NET {
  834. partial struct Fix64 {
  835. public static readonly long[] TanLut = new[] {");
  836. int lineCounter = 0;
  837. for (int i = 0; i < LUT_SIZE; ++i) {
  838. var angle = i * Math.PI * 0.5 / (LUT_SIZE - 1);
  839. if (lineCounter++ % 8 == 0) {
  840. writer.WriteLine();
  841. writer.Write(" ");
  842. }
  843. var tan = Math.Tan(angle);
  844. if (tan > (double)MaxValue || tan < 0.0) {
  845. tan = (double)MaxValue;
  846. }
  847. var rawValue = (((decimal)tan > (decimal)MaxValue || tan < 0.0) ? MaxValue : (FP)tan)._serializedValue;
  848. writer.Write(string.Format("0x{0:X}L, ", rawValue));
  849. }
  850. writer.Write(
  851. @"
  852. };
  853. }
  854. }");
  855. }
  856. }
  857. /// <summary>
  858. /// The underlying integer representation
  859. /// </summary>
  860. public long RawValue { get { return _serializedValue; } }
  861. /// <summary>
  862. /// This is the constructor from raw value; it can only be used interally.
  863. /// </summary>
  864. /// <param name="rawValue"></param>
  865. FP(long rawValue) {
  866. _serializedValue = rawValue;
  867. }
  868. public FP(int value) {
  869. _serializedValue = value * ONE;
  870. }
  871. }
  872. }