misc.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * Copyright (c) 2018-2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. export const halfPI = Math.PI / 2;
  7. export const PiDiv180 = Math.PI / 180;
  8. export function degToRad(deg: number) {
  9. return deg * PiDiv180; // deg * Math.PI / 180
  10. }
  11. export function radToDeg(rad: number) {
  12. return rad / PiDiv180; // rad * 180 / Math.PI
  13. }
  14. export function isPowerOfTwo(x: number) {
  15. return (x !== 0) && (x & (x - 1)) === 0;
  16. }
  17. /** return the value that has the largest absolute value */
  18. export function absMax(...values: number[]) {
  19. let max = 0;
  20. let absMax = 0;
  21. for (let i = 0, il = values.length; i < il; ++i) {
  22. const value = values[i];
  23. const abs = Math.abs(value);
  24. if (abs > absMax) {
  25. max = value;
  26. absMax = abs;
  27. }
  28. }
  29. return max;
  30. }
  31. /** Length of an arc with angle in radians */
  32. export function arcLength(angle: number, radius: number) {
  33. return angle * radius;
  34. }
  35. /** Create an outward spiral of given `radius` on a 2d grid */
  36. export function spiral2d(radius: number) {
  37. let x = 0;
  38. let y = 0;
  39. const delta = [0, -1];
  40. const size = radius * 2 + 1;
  41. const halfSize = size / 2;
  42. const out: [number, number][] = [];
  43. for (let i = Math.pow(size, 2); i > 0; --i) {
  44. if ((-halfSize < x && x <= halfSize) && (-halfSize < y && y <= halfSize)) {
  45. out.push([x, y]);
  46. }
  47. if (x === y || (x < 0 && x === -y) || (x > 0 && x === 1 - y)) {
  48. [delta[0], delta[1]] = [-delta[1], delta[0]]; // change direction
  49. }
  50. x += delta[0];
  51. y += delta[1];
  52. }
  53. return out;
  54. }